Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 1 | //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===// |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 3 | // 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 Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 8 | //===----------------------------------------------------------------------===// |
| 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 Lattner | a4c8022 | 2005-05-08 22:18:06 +0000 | [diff] [blame] | 18 | #include "llvm/CallingConv.h" |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 19 | #include "llvm/Constants.h" |
| 20 | #include "llvm/DerivedTypes.h" |
| 21 | #include "llvm/Instructions.h" |
Chris Lattner | 7561ca1 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 22 | #include "llvm/IntrinsicInst.h" |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 23 | #include "llvm/Module.h" |
| 24 | #include "llvm/Pass.h" |
| 25 | #include "llvm/Support/Debug.h" |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 26 | #include "llvm/Target/TargetData.h" |
| 27 | #include "llvm/Transforms/Utils/Local.h" |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 28 | #include "llvm/ADT/Statistic.h" |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 29 | #include "llvm/ADT/StringExtras.h" |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 30 | #include <set> |
| 31 | #include <algorithm> |
| 32 | using namespace llvm; |
| 33 | |
| 34 | namespace { |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 35 | Statistic<> NumMarked ("globalopt", "Number of globals marked constant"); |
| 36 | Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken " |
| 37 | "into scalars"); |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 38 | Statistic<> NumSubstitute("globalopt", |
| 39 | "Number of globals with initializers stored into them"); |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 40 | Statistic<> NumDeleted ("globalopt", "Number of globals deleted"); |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 41 | Statistic<> NumFnDeleted("globalopt", "Number of functions deleted"); |
Chris Lattner | e42eb31 | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 42 | Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized"); |
Alkis Evlogimenos | c4a44c6 | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 43 | Statistic<> NumLocalized("globalopt", "Number of globals localized"); |
Chris Lattner | 40e4cec | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 44 | Statistic<> NumShrunkToBool("globalopt", |
| 45 | "Number of global vars shrunk to booleans"); |
Chris Lattner | a4c8022 | 2005-05-08 22:18:06 +0000 | [diff] [blame] | 46 | Statistic<> NumFastCallFns("globalopt", |
| 47 | "Number of functions converted to fastcc"); |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 48 | |
| 49 | struct GlobalOpt : public ModulePass { |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 50 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
| 51 | AU.addRequired<TargetData>(); |
| 52 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 53 | |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 54 | bool runOnModule(Module &M); |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 55 | |
| 56 | private: |
Chris Lattner | 531f9e9 | 2005-03-15 04:54:21 +0000 | [diff] [blame] | 57 | bool ProcessInternalGlobal(GlobalVariable *GV, Module::global_iterator &GVI); |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 58 | }; |
| 59 | |
| 60 | RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer"); |
| 61 | } |
| 62 | |
| 63 | ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); } |
| 64 | |
| 65 | /// GlobalStatus - As we analyze each global, keep track of some information |
| 66 | /// about it. If we find out that the address of the global is taken, none of |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 67 | /// this info will be accurate. |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 68 | struct GlobalStatus { |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 69 | /// isLoaded - True if the global is ever loaded. If the global isn't ever |
| 70 | /// loaded it can be deleted. |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 71 | bool isLoaded; |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 72 | |
| 73 | /// StoredType - Keep track of what stores to the global look like. |
| 74 | /// |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 75 | enum StoredType { |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 76 | /// NotStored - There is no store to this global. It can thus be marked |
| 77 | /// constant. |
| 78 | NotStored, |
| 79 | |
| 80 | /// isInitializerStored - This global is stored to, but the only thing |
| 81 | /// stored is the constant it was initialized with. This is only tracked |
| 82 | /// for scalar globals. |
| 83 | isInitializerStored, |
| 84 | |
| 85 | /// isStoredOnce - This global is stored to, but only its initializer and |
| 86 | /// one other value is ever stored to it. If this global isStoredOnce, we |
| 87 | /// track the value stored to it in StoredOnceValue below. This is only |
| 88 | /// tracked for scalar globals. |
| 89 | isStoredOnce, |
| 90 | |
| 91 | /// isStored - This global is stored to by multiple values or something else |
| 92 | /// that we cannot track. |
| 93 | isStored |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 94 | } StoredType; |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 95 | |
| 96 | /// StoredOnceValue - If only one value (besides the initializer constant) is |
| 97 | /// ever stored to this global, keep track of what value it is. |
| 98 | Value *StoredOnceValue; |
| 99 | |
Alkis Evlogimenos | c4a44c6 | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 100 | // AccessingFunction/HasMultipleAccessingFunctions - These start out |
| 101 | // null/false. When the first accessing function is noticed, it is recorded. |
| 102 | // When a second different accessing function is noticed, |
| 103 | // HasMultipleAccessingFunctions is set to true. |
| 104 | Function *AccessingFunction; |
| 105 | bool HasMultipleAccessingFunctions; |
| 106 | |
Chris Lattner | 50bdfcb | 2005-06-15 21:11:48 +0000 | [diff] [blame^] | 107 | // HasNonInstructionUser - Set to true if this global has a user that is not |
| 108 | // an instruction (e.g. a constant expr or GV initializer). |
| 109 | bool HasNonInstructionUser; |
| 110 | |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 111 | /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of |
| 112 | /// the global exist. Such users include GEP instruction with variable |
| 113 | /// indexes, and non-gep/load/store users like constant expr casts. |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 114 | bool isNotSuitableForSRA; |
| 115 | |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 116 | GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0), |
Alkis Evlogimenos | c4a44c6 | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 117 | AccessingFunction(0), HasMultipleAccessingFunctions(false), |
Chris Lattner | 50bdfcb | 2005-06-15 21:11:48 +0000 | [diff] [blame^] | 118 | HasNonInstructionUser(false), isNotSuitableForSRA(false) {} |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 119 | }; |
| 120 | |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 121 | |
| 122 | |
| 123 | /// ConstantIsDead - Return true if the specified constant is (transitively) |
| 124 | /// dead. The constant may be used by other constants (e.g. constant arrays and |
| 125 | /// constant exprs) as long as they are dead, but it cannot be used by anything |
| 126 | /// else. |
| 127 | static bool ConstantIsDead(Constant *C) { |
| 128 | if (isa<GlobalValue>(C)) return false; |
| 129 | |
| 130 | for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI) |
| 131 | if (Constant *CU = dyn_cast<Constant>(*UI)) { |
| 132 | if (!ConstantIsDead(CU)) return false; |
| 133 | } else |
| 134 | return false; |
| 135 | return true; |
| 136 | } |
| 137 | |
| 138 | |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 139 | /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus |
| 140 | /// structure. If the global has its address taken, return true to indicate we |
| 141 | /// can't do anything with it. |
| 142 | /// |
| 143 | static bool AnalyzeGlobal(Value *V, GlobalStatus &GS, |
| 144 | std::set<PHINode*> &PHIUsers) { |
| 145 | for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI) |
| 146 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) { |
Chris Lattner | 50bdfcb | 2005-06-15 21:11:48 +0000 | [diff] [blame^] | 147 | GS.HasNonInstructionUser = true; |
| 148 | |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 149 | if (AnalyzeGlobal(CE, GS, PHIUsers)) return true; |
| 150 | if (CE->getOpcode() != Instruction::GetElementPtr) |
| 151 | GS.isNotSuitableForSRA = true; |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 152 | else if (!GS.isNotSuitableForSRA) { |
| 153 | // Check to see if this ConstantExpr GEP is SRA'able. In particular, we |
| 154 | // don't like < 3 operand CE's, and we don't like non-constant integer |
| 155 | // indices. |
| 156 | if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue()) |
| 157 | GS.isNotSuitableForSRA = true; |
| 158 | else { |
| 159 | for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i) |
| 160 | if (!isa<ConstantInt>(CE->getOperand(i))) { |
| 161 | GS.isNotSuitableForSRA = true; |
| 162 | break; |
| 163 | } |
| 164 | } |
| 165 | } |
| 166 | |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 167 | } else if (Instruction *I = dyn_cast<Instruction>(*UI)) { |
Alkis Evlogimenos | c4a44c6 | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 168 | if (!GS.HasMultipleAccessingFunctions) { |
| 169 | Function *F = I->getParent()->getParent(); |
| 170 | if (GS.AccessingFunction == 0) |
| 171 | GS.AccessingFunction = F; |
| 172 | else if (GS.AccessingFunction != F) |
| 173 | GS.HasMultipleAccessingFunctions = true; |
| 174 | } |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 175 | if (isa<LoadInst>(I)) { |
| 176 | GS.isLoaded = true; |
| 177 | } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Chris Lattner | 02b6c91 | 2004-10-07 06:01:25 +0000 | [diff] [blame] | 178 | // Don't allow a store OF the address, only stores TO the address. |
| 179 | if (SI->getOperand(0) == V) return true; |
| 180 | |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 181 | // If this is a direct store to the global (i.e., the global is a scalar |
| 182 | // value, not an aggregate), keep more specific information about |
| 183 | // stores. |
| 184 | if (GS.StoredType != GlobalStatus::isStored) |
| 185 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){ |
Chris Lattner | 28eeb73 | 2004-11-14 20:50:30 +0000 | [diff] [blame] | 186 | Value *StoredVal = SI->getOperand(0); |
| 187 | if (StoredVal == GV->getInitializer()) { |
| 188 | if (GS.StoredType < GlobalStatus::isInitializerStored) |
| 189 | GS.StoredType = GlobalStatus::isInitializerStored; |
| 190 | } else if (isa<LoadInst>(StoredVal) && |
| 191 | cast<LoadInst>(StoredVal)->getOperand(0) == GV) { |
| 192 | // G = G |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 193 | if (GS.StoredType < GlobalStatus::isInitializerStored) |
| 194 | GS.StoredType = GlobalStatus::isInitializerStored; |
| 195 | } else if (GS.StoredType < GlobalStatus::isStoredOnce) { |
| 196 | GS.StoredType = GlobalStatus::isStoredOnce; |
Chris Lattner | 28eeb73 | 2004-11-14 20:50:30 +0000 | [diff] [blame] | 197 | GS.StoredOnceValue = StoredVal; |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 198 | } else if (GS.StoredType == GlobalStatus::isStoredOnce && |
Chris Lattner | 28eeb73 | 2004-11-14 20:50:30 +0000 | [diff] [blame] | 199 | GS.StoredOnceValue == StoredVal) { |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 200 | // noop. |
| 201 | } else { |
| 202 | GS.StoredType = GlobalStatus::isStored; |
| 203 | } |
| 204 | } else { |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 205 | GS.StoredType = GlobalStatus::isStored; |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 206 | } |
Chris Lattner | 7561ca1 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 207 | } else if (isa<GetElementPtrInst>(I)) { |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 208 | if (AnalyzeGlobal(I, GS, PHIUsers)) return true; |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 209 | |
| 210 | // If the first two indices are constants, this can be SRA'd. |
| 211 | if (isa<GlobalVariable>(I->getOperand(0))) { |
| 212 | if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) || |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 213 | !cast<Constant>(I->getOperand(1))->isNullValue() || |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 214 | !isa<ConstantInt>(I->getOperand(2))) |
| 215 | GS.isNotSuitableForSRA = true; |
| 216 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){ |
| 217 | if (CE->getOpcode() != Instruction::GetElementPtr || |
| 218 | CE->getNumOperands() < 3 || I->getNumOperands() < 2 || |
| 219 | !isa<Constant>(I->getOperand(0)) || |
| 220 | !cast<Constant>(I->getOperand(0))->isNullValue()) |
| 221 | GS.isNotSuitableForSRA = true; |
| 222 | } else { |
| 223 | GS.isNotSuitableForSRA = true; |
| 224 | } |
Chris Lattner | 7561ca1 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 225 | } else if (isa<SelectInst>(I)) { |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 226 | if (AnalyzeGlobal(I, GS, PHIUsers)) return true; |
| 227 | GS.isNotSuitableForSRA = true; |
| 228 | } else if (PHINode *PN = dyn_cast<PHINode>(I)) { |
| 229 | // PHI nodes we can check just like select or GEP instructions, but we |
| 230 | // have to be careful about infinite recursion. |
| 231 | if (PHIUsers.insert(PN).second) // Not already visited. |
| 232 | if (AnalyzeGlobal(I, GS, PHIUsers)) return true; |
| 233 | GS.isNotSuitableForSRA = true; |
| 234 | } else if (isa<SetCondInst>(I)) { |
| 235 | GS.isNotSuitableForSRA = true; |
Chris Lattner | 7561ca1 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 236 | } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) { |
| 237 | if (I->getOperand(1) == V) |
| 238 | GS.StoredType = GlobalStatus::isStored; |
| 239 | if (I->getOperand(2) == V) |
| 240 | GS.isLoaded = true; |
| 241 | GS.isNotSuitableForSRA = true; |
| 242 | } else if (isa<MemSetInst>(I)) { |
| 243 | assert(I->getOperand(1) == V && "Memset only takes one pointer!"); |
| 244 | GS.StoredType = GlobalStatus::isStored; |
| 245 | GS.isNotSuitableForSRA = true; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 246 | } else { |
| 247 | return true; // Any other non-load instruction might take address! |
| 248 | } |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 249 | } else if (Constant *C = dyn_cast<Constant>(*UI)) { |
Chris Lattner | 50bdfcb | 2005-06-15 21:11:48 +0000 | [diff] [blame^] | 250 | GS.HasNonInstructionUser = true; |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 251 | // We might have a dead and dangling constant hanging off of here. |
| 252 | if (!ConstantIsDead(C)) |
| 253 | return true; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 254 | } else { |
Chris Lattner | 50bdfcb | 2005-06-15 21:11:48 +0000 | [diff] [blame^] | 255 | GS.HasNonInstructionUser = true; |
| 256 | // Otherwise must be some other user. |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 257 | return true; |
| 258 | } |
| 259 | |
| 260 | return false; |
| 261 | } |
| 262 | |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 263 | static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) { |
| 264 | ConstantInt *CI = dyn_cast<ConstantInt>(Idx); |
| 265 | if (!CI) return 0; |
Chris Lattner | 46fa04b | 2005-01-08 19:45:31 +0000 | [diff] [blame] | 266 | unsigned IdxV = (unsigned)CI->getRawValue(); |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 267 | |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 268 | if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) { |
| 269 | if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV); |
| 270 | } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) { |
| 271 | if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV); |
| 272 | } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) { |
| 273 | if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV); |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 274 | } else if (isa<ConstantAggregateZero>(Agg)) { |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 275 | if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) { |
| 276 | if (IdxV < STy->getNumElements()) |
| 277 | return Constant::getNullValue(STy->getElementType(IdxV)); |
| 278 | } else if (const SequentialType *STy = |
| 279 | dyn_cast<SequentialType>(Agg->getType())) { |
| 280 | return Constant::getNullValue(STy->getElementType()); |
| 281 | } |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 282 | } else if (isa<UndefValue>(Agg)) { |
| 283 | if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) { |
| 284 | if (IdxV < STy->getNumElements()) |
| 285 | return UndefValue::get(STy->getElementType(IdxV)); |
| 286 | } else if (const SequentialType *STy = |
| 287 | dyn_cast<SequentialType>(Agg->getType())) { |
| 288 | return UndefValue::get(STy->getElementType()); |
| 289 | } |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 290 | } |
| 291 | return 0; |
| 292 | } |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 293 | |
| 294 | static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) { |
Chris Lattner | 7561ca1 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 295 | if (Init == 0) return 0; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 296 | if (GEP->getNumOperands() == 1 || |
| 297 | !isa<Constant>(GEP->getOperand(1)) || |
| 298 | !cast<Constant>(GEP->getOperand(1))->isNullValue()) |
| 299 | return 0; |
| 300 | |
| 301 | for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) { |
| 302 | ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 303 | if (!Idx) return 0; |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 304 | Init = getAggregateConstantElement(Init, Idx); |
| 305 | if (Init == 0) return 0; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 306 | } |
| 307 | return Init; |
| 308 | } |
| 309 | |
| 310 | /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all |
| 311 | /// users of the global, cleaning up the obvious ones. This is largely just a |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 312 | /// quick scan over the use list to clean up the easy and obvious cruft. This |
| 313 | /// returns true if it made a change. |
| 314 | static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) { |
| 315 | bool Changed = false; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 316 | for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) { |
| 317 | User *U = *UI++; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 318 | |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 319 | if (LoadInst *LI = dyn_cast<LoadInst>(U)) { |
Chris Lattner | 7561ca1 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 320 | if (Init) { |
| 321 | // Replace the load with the initializer. |
| 322 | LI->replaceAllUsesWith(Init); |
| 323 | LI->eraseFromParent(); |
| 324 | Changed = true; |
| 325 | } |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 326 | } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) { |
| 327 | // Store must be unreachable or storing Init into the global. |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 328 | SI->eraseFromParent(); |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 329 | Changed = true; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 330 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) { |
| 331 | if (CE->getOpcode() == Instruction::GetElementPtr) { |
Chris Lattner | 7561ca1 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 332 | Constant *SubInit = TraverseGEPInitializer(CE, Init); |
| 333 | Changed |= CleanupConstantGlobalUsers(CE, SubInit); |
| 334 | } else if (CE->getOpcode() == Instruction::Cast && |
| 335 | isa<PointerType>(CE->getType())) { |
| 336 | // Pointer cast, delete any stores and memsets to the global. |
| 337 | Changed |= CleanupConstantGlobalUsers(CE, 0); |
| 338 | } |
| 339 | |
| 340 | if (CE->use_empty()) { |
| 341 | CE->destroyConstant(); |
| 342 | Changed = true; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 343 | } |
| 344 | } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) { |
Chris Lattner | 7561ca1 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 345 | Constant *SubInit = TraverseGEPInitializer(GEP, Init); |
| 346 | Changed |= CleanupConstantGlobalUsers(GEP, SubInit); |
Chris Lattner | a0e769c | 2004-10-10 16:47:33 +0000 | [diff] [blame] | 347 | |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 348 | if (GEP->use_empty()) { |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 349 | GEP->eraseFromParent(); |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 350 | Changed = true; |
| 351 | } |
Chris Lattner | 7561ca1 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 352 | } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv |
| 353 | if (MI->getRawDest() == V) { |
| 354 | MI->eraseFromParent(); |
| 355 | Changed = true; |
| 356 | } |
| 357 | |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 358 | } else if (Constant *C = dyn_cast<Constant>(U)) { |
| 359 | // If we have a chain of dead constantexprs or other things dangling from |
| 360 | // us, and if they are all dead, nuke them without remorse. |
| 361 | if (ConstantIsDead(C)) { |
| 362 | C->destroyConstant(); |
Chris Lattner | 7561ca1 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 363 | // This could have invalidated UI, start over from scratch. |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 364 | CleanupConstantGlobalUsers(V, Init); |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 365 | return true; |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 366 | } |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 367 | } |
| 368 | } |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 369 | return Changed; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 370 | } |
| 371 | |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 372 | /// SRAGlobal - Perform scalar replacement of aggregates on the specified global |
| 373 | /// variable. This opens the door for other optimizations by exposing the |
| 374 | /// behavior of the program in a more fine-grained way. We have determined that |
| 375 | /// this transformation is safe already. We return the first global variable we |
| 376 | /// insert so that the caller can reprocess it. |
| 377 | static GlobalVariable *SRAGlobal(GlobalVariable *GV) { |
| 378 | assert(GV->hasInternalLinkage() && !GV->isConstant()); |
| 379 | Constant *Init = GV->getInitializer(); |
| 380 | const Type *Ty = Init->getType(); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 381 | |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 382 | std::vector<GlobalVariable*> NewGlobals; |
| 383 | Module::GlobalListType &Globals = GV->getParent()->getGlobalList(); |
| 384 | |
| 385 | if (const StructType *STy = dyn_cast<StructType>(Ty)) { |
| 386 | NewGlobals.reserve(STy->getNumElements()); |
| 387 | for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { |
| 388 | Constant *In = getAggregateConstantElement(Init, |
| 389 | ConstantUInt::get(Type::UIntTy, i)); |
| 390 | assert(In && "Couldn't get element of initializer?"); |
| 391 | GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false, |
| 392 | GlobalVariable::InternalLinkage, |
| 393 | In, GV->getName()+"."+utostr(i)); |
| 394 | Globals.insert(GV, NGV); |
| 395 | NewGlobals.push_back(NGV); |
| 396 | } |
| 397 | } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) { |
| 398 | unsigned NumElements = 0; |
| 399 | if (const ArrayType *ATy = dyn_cast<ArrayType>(STy)) |
| 400 | NumElements = ATy->getNumElements(); |
| 401 | else if (const PackedType *PTy = dyn_cast<PackedType>(STy)) |
| 402 | NumElements = PTy->getNumElements(); |
| 403 | else |
| 404 | assert(0 && "Unknown aggregate sequential type!"); |
| 405 | |
Chris Lattner | 25169ca | 2005-02-23 16:53:04 +0000 | [diff] [blame] | 406 | if (NumElements > 16 && GV->hasNUsesOrMore(16)) |
Chris Lattner | d6a4492 | 2005-02-01 01:23:31 +0000 | [diff] [blame] | 407 | return 0; // It's not worth it. |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 408 | NewGlobals.reserve(NumElements); |
| 409 | for (unsigned i = 0, e = NumElements; i != e; ++i) { |
| 410 | Constant *In = getAggregateConstantElement(Init, |
| 411 | ConstantUInt::get(Type::UIntTy, i)); |
| 412 | assert(In && "Couldn't get element of initializer?"); |
| 413 | |
| 414 | GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false, |
| 415 | GlobalVariable::InternalLinkage, |
| 416 | In, GV->getName()+"."+utostr(i)); |
| 417 | Globals.insert(GV, NGV); |
| 418 | NewGlobals.push_back(NGV); |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | if (NewGlobals.empty()) |
| 423 | return 0; |
| 424 | |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 425 | DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV); |
| 426 | |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 427 | Constant *NullInt = Constant::getNullValue(Type::IntTy); |
| 428 | |
| 429 | // Loop over all of the uses of the global, replacing the constantexpr geps, |
| 430 | // with smaller constantexpr geps or direct references. |
| 431 | while (!GV->use_empty()) { |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 432 | User *GEP = GV->use_back(); |
| 433 | assert(((isa<ConstantExpr>(GEP) && |
| 434 | cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)|| |
| 435 | isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!"); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 436 | |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 437 | // Ignore the 1th operand, which has to be zero or else the program is quite |
| 438 | // broken (undefined). Get the 2nd operand, which is the structure or array |
| 439 | // index. |
Chris Lattner | 46fa04b | 2005-01-08 19:45:31 +0000 | [diff] [blame] | 440 | unsigned Val = |
| 441 | (unsigned)cast<ConstantInt>(GEP->getOperand(2))->getRawValue(); |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 442 | if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access. |
| 443 | |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 444 | Value *NewPtr = NewGlobals[Val]; |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 445 | |
| 446 | // Form a shorter GEP if needed. |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 447 | if (GEP->getNumOperands() > 3) |
| 448 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) { |
| 449 | std::vector<Constant*> Idxs; |
| 450 | Idxs.push_back(NullInt); |
| 451 | for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i) |
| 452 | Idxs.push_back(CE->getOperand(i)); |
| 453 | NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs); |
| 454 | } else { |
| 455 | GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP); |
| 456 | std::vector<Value*> Idxs; |
| 457 | Idxs.push_back(NullInt); |
| 458 | for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) |
| 459 | Idxs.push_back(GEPI->getOperand(i)); |
| 460 | NewPtr = new GetElementPtrInst(NewPtr, Idxs, |
| 461 | GEPI->getName()+"."+utostr(Val), GEPI); |
| 462 | } |
| 463 | GEP->replaceAllUsesWith(NewPtr); |
| 464 | |
| 465 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP)) |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 466 | GEPI->eraseFromParent(); |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 467 | else |
| 468 | cast<ConstantExpr>(GEP)->destroyConstant(); |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 469 | } |
| 470 | |
Chris Lattner | 73ad73e | 2004-10-08 20:25:55 +0000 | [diff] [blame] | 471 | // Delete the old global, now that it is dead. |
| 472 | Globals.erase(GV); |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 473 | ++NumSRA; |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 474 | |
| 475 | // Loop over the new globals array deleting any globals that are obviously |
| 476 | // dead. This can arise due to scalarization of a structure or an array that |
| 477 | // has elements that are dead. |
| 478 | unsigned FirstGlobal = 0; |
| 479 | for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i) |
| 480 | if (NewGlobals[i]->use_empty()) { |
| 481 | Globals.erase(NewGlobals[i]); |
| 482 | if (FirstGlobal == i) ++FirstGlobal; |
| 483 | } |
| 484 | |
| 485 | return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0; |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 486 | } |
| 487 | |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 488 | /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified |
| 489 | /// value will trap if the value is dynamically null. |
| 490 | static bool AllUsesOfValueWillTrapIfNull(Value *V) { |
| 491 | for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI) |
| 492 | if (isa<LoadInst>(*UI)) { |
| 493 | // Will trap. |
| 494 | } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) { |
| 495 | if (SI->getOperand(0) == V) { |
| 496 | //std::cerr << "NONTRAPPING USE: " << **UI; |
| 497 | return false; // Storing the value. |
| 498 | } |
| 499 | } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) { |
| 500 | if (CI->getOperand(0) != V) { |
| 501 | //std::cerr << "NONTRAPPING USE: " << **UI; |
| 502 | return false; // Not calling the ptr |
| 503 | } |
| 504 | } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) { |
| 505 | if (II->getOperand(0) != V) { |
| 506 | //std::cerr << "NONTRAPPING USE: " << **UI; |
| 507 | return false; // Not calling the ptr |
| 508 | } |
| 509 | } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) { |
| 510 | if (!AllUsesOfValueWillTrapIfNull(CI)) return false; |
| 511 | } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) { |
| 512 | if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 513 | } else if (isa<SetCondInst>(*UI) && |
Chris Lattner | fe9abf9 | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 514 | isa<ConstantPointerNull>(UI->getOperand(1))) { |
| 515 | // Ignore setcc X, null |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 516 | } else { |
| 517 | //std::cerr << "NONTRAPPING USE: " << **UI; |
| 518 | return false; |
| 519 | } |
| 520 | return true; |
| 521 | } |
| 522 | |
| 523 | /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads |
Chris Lattner | fe9abf9 | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 524 | /// from GV will trap if the loaded value is null. Note that this also permits |
| 525 | /// comparisons of the loaded value against null, as a special case. |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 526 | static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) { |
| 527 | for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI) |
| 528 | if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) { |
| 529 | if (!AllUsesOfValueWillTrapIfNull(LI)) |
| 530 | return false; |
| 531 | } else if (isa<StoreInst>(*UI)) { |
| 532 | // Ignore stores to the global. |
| 533 | } else { |
| 534 | // We don't know or understand this user, bail out. |
| 535 | //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI; |
| 536 | return false; |
| 537 | } |
| 538 | |
| 539 | return true; |
| 540 | } |
| 541 | |
Chris Lattner | e42eb31 | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 542 | static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) { |
| 543 | bool Changed = false; |
| 544 | for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) { |
| 545 | Instruction *I = cast<Instruction>(*UI++); |
| 546 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 547 | LI->setOperand(0, NewV); |
| 548 | Changed = true; |
| 549 | } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
| 550 | if (SI->getOperand(1) == V) { |
| 551 | SI->setOperand(1, NewV); |
| 552 | Changed = true; |
| 553 | } |
| 554 | } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) { |
| 555 | if (I->getOperand(0) == V) { |
| 556 | // Calling through the pointer! Turn into a direct call, but be careful |
| 557 | // that the pointer is not also being passed as an argument. |
| 558 | I->setOperand(0, NewV); |
| 559 | Changed = true; |
| 560 | bool PassedAsArg = false; |
| 561 | for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i) |
| 562 | if (I->getOperand(i) == V) { |
| 563 | PassedAsArg = true; |
| 564 | I->setOperand(i, NewV); |
| 565 | } |
| 566 | |
| 567 | if (PassedAsArg) { |
| 568 | // Being passed as an argument also. Be careful to not invalidate UI! |
| 569 | UI = V->use_begin(); |
| 570 | } |
| 571 | } |
| 572 | } else if (CastInst *CI = dyn_cast<CastInst>(I)) { |
| 573 | Changed |= OptimizeAwayTrappingUsesOfValue(CI, |
| 574 | ConstantExpr::getCast(NewV, CI->getType())); |
| 575 | if (CI->use_empty()) { |
| 576 | Changed = true; |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 577 | CI->eraseFromParent(); |
Chris Lattner | e42eb31 | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 578 | } |
| 579 | } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
| 580 | // Should handle GEP here. |
| 581 | std::vector<Constant*> Indices; |
| 582 | Indices.reserve(GEPI->getNumOperands()-1); |
| 583 | for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i) |
| 584 | if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i))) |
| 585 | Indices.push_back(C); |
| 586 | else |
| 587 | break; |
| 588 | if (Indices.size() == GEPI->getNumOperands()-1) |
| 589 | Changed |= OptimizeAwayTrappingUsesOfValue(GEPI, |
| 590 | ConstantExpr::getGetElementPtr(NewV, Indices)); |
| 591 | if (GEPI->use_empty()) { |
| 592 | Changed = true; |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 593 | GEPI->eraseFromParent(); |
Chris Lattner | e42eb31 | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 594 | } |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | return Changed; |
| 599 | } |
| 600 | |
| 601 | |
| 602 | /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null |
| 603 | /// value stored into it. If there are uses of the loaded value that would trap |
| 604 | /// if the loaded value is dynamically null, then we know that they cannot be |
| 605 | /// reachable with a null optimize away the load. |
| 606 | static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) { |
| 607 | std::vector<LoadInst*> Loads; |
| 608 | bool Changed = false; |
| 609 | |
| 610 | // Replace all uses of loads with uses of uses of the stored value. |
| 611 | for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); |
| 612 | GUI != E; ++GUI) |
| 613 | if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) { |
| 614 | Loads.push_back(LI); |
| 615 | Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV); |
| 616 | } else { |
| 617 | assert(isa<StoreInst>(*GUI) && "Only expect load and stores!"); |
| 618 | } |
| 619 | |
| 620 | if (Changed) { |
| 621 | DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV); |
| 622 | ++NumGlobUses; |
| 623 | } |
| 624 | |
| 625 | // Delete all of the loads we can, keeping track of whether we nuked them all! |
| 626 | bool AllLoadsGone = true; |
| 627 | while (!Loads.empty()) { |
| 628 | LoadInst *L = Loads.back(); |
| 629 | if (L->use_empty()) { |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 630 | L->eraseFromParent(); |
Chris Lattner | e42eb31 | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 631 | Changed = true; |
| 632 | } else { |
| 633 | AllLoadsGone = false; |
| 634 | } |
| 635 | Loads.pop_back(); |
| 636 | } |
| 637 | |
| 638 | // If we nuked all of the loads, then none of the stores are needed either, |
| 639 | // nor is the global. |
| 640 | if (AllLoadsGone) { |
| 641 | DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n"); |
| 642 | CleanupConstantGlobalUsers(GV, 0); |
| 643 | if (GV->use_empty()) { |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 644 | GV->eraseFromParent(); |
Chris Lattner | e42eb31 | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 645 | ++NumDeleted; |
| 646 | } |
| 647 | Changed = true; |
| 648 | } |
| 649 | return Changed; |
| 650 | } |
| 651 | |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 652 | /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the |
| 653 | /// instructions that are foldable. |
| 654 | static void ConstantPropUsersOf(Value *V) { |
| 655 | for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) |
| 656 | if (Instruction *I = dyn_cast<Instruction>(*UI++)) |
| 657 | if (Constant *NewC = ConstantFoldInstruction(I)) { |
| 658 | I->replaceAllUsesWith(NewC); |
| 659 | |
Chris Lattner | d6a4492 | 2005-02-01 01:23:31 +0000 | [diff] [blame] | 660 | // Advance UI to the next non-I use to avoid invalidating it! |
| 661 | // Instructions could multiply use V. |
| 662 | while (UI != E && *UI == I) |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 663 | ++UI; |
Chris Lattner | d6a4492 | 2005-02-01 01:23:31 +0000 | [diff] [blame] | 664 | I->eraseFromParent(); |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 665 | } |
| 666 | } |
| 667 | |
| 668 | /// OptimizeGlobalAddressOfMalloc - This function takes the specified global |
| 669 | /// variable, and transforms the program as if it always contained the result of |
| 670 | /// the specified malloc. Because it is always the result of the specified |
| 671 | /// malloc, there is no reason to actually DO the malloc. Instead, turn the |
| 672 | /// malloc into a global, and any laods of GV as uses of the new global. |
| 673 | static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, |
| 674 | MallocInst *MI) { |
| 675 | DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI); |
| 676 | ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize()); |
| 677 | |
| 678 | if (NElements->getRawValue() != 1) { |
| 679 | // If we have an array allocation, transform it to a single element |
| 680 | // allocation to make the code below simpler. |
| 681 | Type *NewTy = ArrayType::get(MI->getAllocatedType(), |
Chris Lattner | 46fa04b | 2005-01-08 19:45:31 +0000 | [diff] [blame] | 682 | (unsigned)NElements->getRawValue()); |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 683 | MallocInst *NewMI = |
| 684 | new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy), |
| 685 | MI->getName(), MI); |
| 686 | std::vector<Value*> Indices; |
| 687 | Indices.push_back(Constant::getNullValue(Type::IntTy)); |
| 688 | Indices.push_back(Indices[0]); |
| 689 | Value *NewGEP = new GetElementPtrInst(NewMI, Indices, |
| 690 | NewMI->getName()+".el0", MI); |
| 691 | MI->replaceAllUsesWith(NewGEP); |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 692 | MI->eraseFromParent(); |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 693 | MI = NewMI; |
| 694 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 695 | |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 696 | // Create the new global variable. The contents of the malloc'd memory is |
| 697 | // undefined, so initialize with an undef value. |
| 698 | Constant *Init = UndefValue::get(MI->getAllocatedType()); |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 699 | GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false, |
| 700 | GlobalValue::InternalLinkage, Init, |
| 701 | GV->getName()+".body"); |
| 702 | GV->getParent()->getGlobalList().insert(GV, NewGV); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 703 | |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 704 | // Anything that used the malloc now uses the global directly. |
| 705 | MI->replaceAllUsesWith(NewGV); |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 706 | |
| 707 | Constant *RepValue = NewGV; |
| 708 | if (NewGV->getType() != GV->getType()->getElementType()) |
| 709 | RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType()); |
| 710 | |
Chris Lattner | fe9abf9 | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 711 | // If there is a comparison against null, we will insert a global bool to |
| 712 | // keep track of whether the global was initialized yet or not. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 713 | GlobalVariable *InitBool = |
| 714 | new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage, |
Chris Lattner | 3b18139 | 2004-12-02 06:25:58 +0000 | [diff] [blame] | 715 | ConstantBool::False, GV->getName()+".init"); |
| 716 | bool InitBoolUsed = false; |
Chris Lattner | fe9abf9 | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 717 | |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 718 | // Loop over all uses of GV, processing them in turn. |
Chris Lattner | 3b18139 | 2004-12-02 06:25:58 +0000 | [diff] [blame] | 719 | std::vector<StoreInst*> Stores; |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 720 | while (!GV->use_empty()) |
| 721 | if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) { |
Chris Lattner | fe9abf9 | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 722 | while (!LI->use_empty()) { |
Chris Lattner | d6a4492 | 2005-02-01 01:23:31 +0000 | [diff] [blame] | 723 | Use &LoadUse = LI->use_begin().getUse(); |
Chris Lattner | fe9abf9 | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 724 | if (!isa<SetCondInst>(LoadUse.getUser())) |
| 725 | LoadUse = RepValue; |
| 726 | else { |
Chris Lattner | fe9abf9 | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 727 | // Replace the setcc X, 0 with a use of the bool value. |
| 728 | SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser()); |
| 729 | Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI); |
Chris Lattner | 3b18139 | 2004-12-02 06:25:58 +0000 | [diff] [blame] | 730 | InitBoolUsed = true; |
Chris Lattner | fe9abf9 | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 731 | switch (SCI->getOpcode()) { |
| 732 | default: assert(0 && "Unknown opcode!"); |
| 733 | case Instruction::SetLT: |
| 734 | LV = ConstantBool::False; // X < null -> always false |
| 735 | break; |
| 736 | case Instruction::SetEQ: |
| 737 | case Instruction::SetLE: |
| 738 | LV = BinaryOperator::createNot(LV, "notinit", SCI); |
| 739 | break; |
| 740 | case Instruction::SetNE: |
| 741 | case Instruction::SetGE: |
| 742 | case Instruction::SetGT: |
| 743 | break; // no change. |
| 744 | } |
| 745 | SCI->replaceAllUsesWith(LV); |
| 746 | SCI->eraseFromParent(); |
| 747 | } |
| 748 | } |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 749 | LI->eraseFromParent(); |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 750 | } else { |
| 751 | StoreInst *SI = cast<StoreInst>(GV->use_back()); |
Chris Lattner | 3b18139 | 2004-12-02 06:25:58 +0000 | [diff] [blame] | 752 | // The global is initialized when the store to it occurs. |
| 753 | new StoreInst(ConstantBool::True, InitBool, SI); |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 754 | SI->eraseFromParent(); |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 755 | } |
| 756 | |
Chris Lattner | 3b18139 | 2004-12-02 06:25:58 +0000 | [diff] [blame] | 757 | // If the initialization boolean was used, insert it, otherwise delete it. |
| 758 | if (!InitBoolUsed) { |
| 759 | while (!InitBool->use_empty()) // Delete initializations |
| 760 | cast<Instruction>(InitBool->use_back())->eraseFromParent(); |
| 761 | delete InitBool; |
| 762 | } else |
| 763 | GV->getParent()->getGlobalList().insert(GV, InitBool); |
| 764 | |
| 765 | |
Chris Lattner | fe9abf9 | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 766 | // Now the GV is dead, nuke it and the malloc. |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 767 | GV->eraseFromParent(); |
Chris Lattner | fe9abf9 | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 768 | MI->eraseFromParent(); |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 769 | |
| 770 | // To further other optimizations, loop over all users of NewGV and try to |
| 771 | // constant prop them. This will promote GEP instructions with constant |
| 772 | // indices into GEP constant-exprs, which will allow global-opt to hack on it. |
| 773 | ConstantPropUsersOf(NewGV); |
| 774 | if (RepValue != NewGV) |
| 775 | ConstantPropUsersOf(RepValue); |
| 776 | |
| 777 | return NewGV; |
| 778 | } |
Chris Lattner | e42eb31 | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 779 | |
Chris Lattner | c0677c0 | 2004-12-02 07:11:07 +0000 | [diff] [blame] | 780 | /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking |
| 781 | /// to make sure that there are no complex uses of V. We permit simple things |
| 782 | /// like dereferencing the pointer, but not storing through the address, unless |
| 783 | /// it is to the specified global. |
| 784 | static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V, |
| 785 | GlobalVariable *GV) { |
| 786 | for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI) |
| 787 | if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) { |
| 788 | // Fine, ignore. |
| 789 | } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) { |
| 790 | if (SI->getOperand(0) == V && SI->getOperand(1) != GV) |
| 791 | return false; // Storing the pointer itself... bad. |
| 792 | // Otherwise, storing through it, or storing into GV... fine. |
| 793 | } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) { |
| 794 | if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV)) |
| 795 | return false; |
| 796 | } else { |
| 797 | return false; |
| 798 | } |
| 799 | return true; |
| 800 | |
| 801 | } |
| 802 | |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 803 | // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge |
| 804 | // that only one value (besides its initializer) is ever stored to the global. |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 805 | static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, |
Chris Lattner | 531f9e9 | 2005-03-15 04:54:21 +0000 | [diff] [blame] | 806 | Module::global_iterator &GVI, TargetData &TD) { |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 807 | if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal)) |
| 808 | StoredOnceVal = CI->getOperand(0); |
| 809 | else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){ |
Chris Lattner | e42eb31 | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 810 | // "getelementptr Ptr, 0, 0, 0" is really just a cast. |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 811 | bool IsJustACast = true; |
| 812 | for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i) |
| 813 | if (!isa<Constant>(GEPI->getOperand(i)) || |
| 814 | !cast<Constant>(GEPI->getOperand(i))->isNullValue()) { |
| 815 | IsJustACast = false; |
| 816 | break; |
| 817 | } |
| 818 | if (IsJustACast) |
| 819 | StoredOnceVal = GEPI->getOperand(0); |
| 820 | } |
| 821 | |
Chris Lattner | e42eb31 | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 822 | // If we are dealing with a pointer global that is initialized to null and |
| 823 | // only has one (non-null) value stored into it, then we can optimize any |
| 824 | // users of the loaded value (often calls and loads) that would trap if the |
| 825 | // value was null. |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 826 | if (isa<PointerType>(GV->getInitializer()->getType()) && |
| 827 | GV->getInitializer()->isNullValue()) { |
Chris Lattner | e42eb31 | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 828 | if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) { |
| 829 | if (GV->getInitializer()->getType() != SOVC->getType()) |
| 830 | SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType()); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 831 | |
Chris Lattner | e42eb31 | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 832 | // Optimize away any trapping uses of the loaded value. |
| 833 | if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC)) |
Chris Lattner | 604ed7a | 2004-10-10 17:07:12 +0000 | [diff] [blame] | 834 | return true; |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 835 | } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) { |
| 836 | // If we have a global that is only initialized with a fixed size malloc, |
| 837 | // and if all users of the malloc trap, and if the malloc'd address is not |
| 838 | // put anywhere else, transform the program to use global memory instead |
| 839 | // of malloc'd memory. This eliminates dynamic allocation (good) and |
| 840 | // exposes the resultant global to further GlobalOpt (even better). Note |
| 841 | // that we restrict this transformation to only working on small |
| 842 | // allocations (2048 bytes currently), as we don't want to introduce a 16M |
| 843 | // global or something. |
| 844 | if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) |
| 845 | if (MI->getAllocatedType()->isSized() && |
| 846 | NElements->getRawValue()* |
| 847 | TD.getTypeSize(MI->getAllocatedType()) < 2048 && |
Chris Lattner | c0677c0 | 2004-12-02 07:11:07 +0000 | [diff] [blame] | 848 | AllUsesOfLoadedValueWillTrapIfNull(GV) && |
| 849 | ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV)) { |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 850 | GVI = OptimizeGlobalAddressOfMalloc(GV, MI); |
| 851 | return true; |
| 852 | } |
Chris Lattner | e42eb31 | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 853 | } |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 854 | } |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 855 | |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 856 | return false; |
| 857 | } |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 858 | |
Chris Lattner | 40e4cec | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 859 | /// ShrinkGlobalToBoolean - At this point, we have learned that the only two |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 860 | /// values ever stored into GV are its initializer and OtherVal. |
Chris Lattner | 40e4cec | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 861 | static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) { |
| 862 | // Create the new global, initializing it to false. |
| 863 | GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false, |
| 864 | GlobalValue::InternalLinkage, ConstantBool::False, GV->getName()+".b"); |
| 865 | GV->getParent()->getGlobalList().insert(GV, NewGV); |
| 866 | |
| 867 | Constant *InitVal = GV->getInitializer(); |
| 868 | assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!"); |
| 869 | |
| 870 | // If initialized to zero and storing one into the global, we can use a cast |
| 871 | // instead of a select to synthesize the desired value. |
| 872 | bool IsOneZero = false; |
| 873 | if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) |
| 874 | IsOneZero = InitVal->isNullValue() && CI->equalsInt(1); |
| 875 | |
| 876 | while (!GV->use_empty()) { |
| 877 | Instruction *UI = cast<Instruction>(GV->use_back()); |
| 878 | if (StoreInst *SI = dyn_cast<StoreInst>(UI)) { |
| 879 | // Change the store into a boolean store. |
| 880 | bool StoringOther = SI->getOperand(0) == OtherVal; |
| 881 | // Only do this if we weren't storing a loaded value. |
Chris Lattner | 745196a | 2004-12-12 19:34:41 +0000 | [diff] [blame] | 882 | Value *StoreVal; |
Chris Lattner | 40e4cec | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 883 | if (StoringOther || SI->getOperand(0) == InitVal) |
Chris Lattner | 745196a | 2004-12-12 19:34:41 +0000 | [diff] [blame] | 884 | StoreVal = ConstantBool::get(StoringOther); |
| 885 | else { |
| 886 | // Otherwise, we are storing a previously loaded copy. To do this, |
| 887 | // change the copy from copying the original value to just copying the |
| 888 | // bool. |
| 889 | Instruction *StoredVal = cast<Instruction>(SI->getOperand(0)); |
| 890 | |
| 891 | // If we're already replaced the input, StoredVal will be a cast or |
| 892 | // select instruction. If not, it will be a load of the original |
| 893 | // global. |
| 894 | if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) { |
| 895 | assert(LI->getOperand(0) == GV && "Not a copy!"); |
| 896 | // Insert a new load, to preserve the saved value. |
| 897 | StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI); |
| 898 | } else { |
| 899 | assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) && |
| 900 | "This is not a form that we understand!"); |
| 901 | StoreVal = StoredVal->getOperand(0); |
| 902 | assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!"); |
| 903 | } |
| 904 | } |
| 905 | new StoreInst(StoreVal, NewGV, SI); |
| 906 | } else if (!UI->use_empty()) { |
Chris Lattner | 40e4cec | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 907 | // Change the load into a load of bool then a select. |
| 908 | LoadInst *LI = cast<LoadInst>(UI); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 909 | |
Chris Lattner | 40e4cec | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 910 | std::string Name = LI->getName(); LI->setName(""); |
| 911 | LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI); |
| 912 | Value *NSI; |
| 913 | if (IsOneZero) |
| 914 | NSI = new CastInst(NLI, LI->getType(), Name, LI); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 915 | else |
Chris Lattner | 40e4cec | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 916 | NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI); |
| 917 | LI->replaceAllUsesWith(NSI); |
| 918 | } |
| 919 | UI->eraseFromParent(); |
| 920 | } |
| 921 | |
| 922 | GV->eraseFromParent(); |
| 923 | } |
| 924 | |
| 925 | |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 926 | /// ProcessInternalGlobal - Analyze the specified global variable and optimize |
| 927 | /// it if possible. If we make a change, return true. |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 928 | bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV, |
Chris Lattner | 531f9e9 | 2005-03-15 04:54:21 +0000 | [diff] [blame] | 929 | Module::global_iterator &GVI) { |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 930 | std::set<PHINode*> PHIUsers; |
| 931 | GlobalStatus GS; |
| 932 | PHIUsers.clear(); |
| 933 | GV->removeDeadConstantUsers(); |
| 934 | |
| 935 | if (GV->use_empty()) { |
| 936 | DEBUG(std::cerr << "GLOBAL DEAD: " << *GV); |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 937 | GV->eraseFromParent(); |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 938 | ++NumDeleted; |
| 939 | return true; |
| 940 | } |
| 941 | |
| 942 | if (!AnalyzeGlobal(GV, GS, PHIUsers)) { |
Alkis Evlogimenos | c4a44c6 | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 943 | // If this is a first class global and has only one accessing function |
| 944 | // and this function is main (which we know is not recursive we can make |
| 945 | // this global a local variable) we replace the global with a local alloca |
| 946 | // in this function. |
| 947 | // |
| 948 | // NOTE: It doesn't make sense to promote non first class types since we |
| 949 | // are just replacing static memory to stack memory. |
| 950 | if (!GS.HasMultipleAccessingFunctions && |
Chris Lattner | 50bdfcb | 2005-06-15 21:11:48 +0000 | [diff] [blame^] | 951 | GS.AccessingFunction && !GS.HasNonInstructionUser && |
Alkis Evlogimenos | c4a44c6 | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 952 | GV->getType()->getElementType()->isFirstClassType() && |
| 953 | GS.AccessingFunction->getName() == "main" && |
| 954 | GS.AccessingFunction->hasExternalLinkage()) { |
| 955 | DEBUG(std::cerr << "LOCALIZING GLOBAL: " << *GV); |
| 956 | Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin(); |
| 957 | const Type* ElemTy = GV->getType()->getElementType(); |
| 958 | AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI); |
| 959 | if (!isa<UndefValue>(GV->getInitializer())) |
| 960 | new StoreInst(GV->getInitializer(), Alloca, FirstI); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 961 | |
Alkis Evlogimenos | c4a44c6 | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 962 | GV->replaceAllUsesWith(Alloca); |
| 963 | GV->eraseFromParent(); |
| 964 | ++NumLocalized; |
| 965 | return true; |
| 966 | } |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 967 | // If the global is never loaded (but may be stored to), it is dead. |
| 968 | // Delete it now. |
| 969 | if (!GS.isLoaded) { |
| 970 | DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV); |
Chris Lattner | f369b38 | 2004-10-09 03:32:52 +0000 | [diff] [blame] | 971 | |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 972 | // Delete any stores we can find to the global. We may not be able to |
| 973 | // make it completely dead though. |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 974 | bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer()); |
Chris Lattner | f369b38 | 2004-10-09 03:32:52 +0000 | [diff] [blame] | 975 | |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 976 | // If the global is dead now, delete it. |
| 977 | if (GV->use_empty()) { |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 978 | GV->eraseFromParent(); |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 979 | ++NumDeleted; |
Chris Lattner | f369b38 | 2004-10-09 03:32:52 +0000 | [diff] [blame] | 980 | Changed = true; |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 981 | } |
Chris Lattner | f369b38 | 2004-10-09 03:32:52 +0000 | [diff] [blame] | 982 | return Changed; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 983 | |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 984 | } else if (GS.StoredType <= GlobalStatus::isInitializerStored) { |
| 985 | DEBUG(std::cerr << "MARKING CONSTANT: " << *GV); |
| 986 | GV->setConstant(true); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 987 | |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 988 | // Clean up any obviously simplifiable users now. |
| 989 | CleanupConstantGlobalUsers(GV, GV->getInitializer()); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 990 | |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 991 | // If the global is dead now, just nuke it. |
| 992 | if (GV->use_empty()) { |
| 993 | DEBUG(std::cerr << " *** Marking constant allowed us to simplify " |
| 994 | "all users and delete global!\n"); |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 995 | GV->eraseFromParent(); |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 996 | ++NumDeleted; |
| 997 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 998 | |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 999 | ++NumMarked; |
| 1000 | return true; |
| 1001 | } else if (!GS.isNotSuitableForSRA && |
| 1002 | !GV->getInitializer()->getType()->isFirstClassType()) { |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1003 | if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) { |
| 1004 | GVI = FirstNewGV; // Don't skip the newly produced globals! |
| 1005 | return true; |
| 1006 | } |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 1007 | } else if (GS.StoredType == GlobalStatus::isStoredOnce) { |
Chris Lattner | 40e4cec | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1008 | // If the initial value for the global was an undef value, and if only |
| 1009 | // one other value was stored into it, we can just change the |
| 1010 | // initializer to be an undef value, then delete all stores to the |
| 1011 | // global. This allows us to mark it constant. |
| 1012 | if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) |
| 1013 | if (isa<UndefValue>(GV->getInitializer())) { |
| 1014 | // Change the initial value here. |
| 1015 | GV->setInitializer(SOVConstant); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1016 | |
Chris Lattner | 40e4cec | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1017 | // Clean up any obviously simplifiable users now. |
| 1018 | CleanupConstantGlobalUsers(GV, GV->getInitializer()); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1019 | |
Chris Lattner | 40e4cec | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1020 | if (GV->use_empty()) { |
| 1021 | DEBUG(std::cerr << " *** Substituting initializer allowed us to " |
| 1022 | "simplify all users and delete global!\n"); |
| 1023 | GV->eraseFromParent(); |
| 1024 | ++NumDeleted; |
| 1025 | } else { |
| 1026 | GVI = GV; |
| 1027 | } |
| 1028 | ++NumSubstitute; |
| 1029 | return true; |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 1030 | } |
Chris Lattner | 8e71c6a | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 1031 | |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 1032 | // Try to optimize globals based on the knowledge that only one value |
| 1033 | // (besides its initializer) is ever stored to the global. |
Chris Lattner | 004e250 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 1034 | if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI, |
| 1035 | getAnalysis<TargetData>())) |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 1036 | return true; |
Chris Lattner | 40e4cec | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1037 | |
| 1038 | // Otherwise, if the global was not a boolean, we can shrink it to be a |
| 1039 | // boolean. |
| 1040 | if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) |
Chris Lattner | 1cbd5be | 2004-12-12 06:03:06 +0000 | [diff] [blame] | 1041 | if (GV->getType()->getElementType() != Type::BoolTy && |
| 1042 | !GV->getType()->getElementType()->isFloatingPoint()) { |
Chris Lattner | 40e4cec | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1043 | DEBUG(std::cerr << " *** SHRINKING TO BOOL: " << *GV); |
| 1044 | ShrinkGlobalToBoolean(GV, SOVConstant); |
| 1045 | ++NumShrunkToBool; |
| 1046 | return true; |
| 1047 | } |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1048 | } |
| 1049 | } |
| 1050 | return false; |
| 1051 | } |
| 1052 | |
Chris Lattner | a4c8022 | 2005-05-08 22:18:06 +0000 | [diff] [blame] | 1053 | /// OnlyCalledDirectly - Return true if the specified function is only called |
| 1054 | /// directly. In other words, its address is never taken. |
| 1055 | static bool OnlyCalledDirectly(Function *F) { |
| 1056 | for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){ |
| 1057 | Instruction *User = dyn_cast<Instruction>(*UI); |
| 1058 | if (!User) return false; |
| 1059 | if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false; |
| 1060 | |
| 1061 | // See if the function address is passed as an argument. |
| 1062 | for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i) |
| 1063 | if (User->getOperand(i) == F) return false; |
| 1064 | } |
| 1065 | return true; |
| 1066 | } |
| 1067 | |
| 1068 | /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified |
| 1069 | /// function, changing them to FastCC. |
| 1070 | static void ChangeCalleesToFastCall(Function *F) { |
| 1071 | for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){ |
| 1072 | Instruction *User = cast<Instruction>(*UI); |
| 1073 | if (CallInst *CI = dyn_cast<CallInst>(User)) |
| 1074 | CI->setCallingConv(CallingConv::Fast); |
| 1075 | else |
| 1076 | cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast); |
| 1077 | } |
| 1078 | } |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1079 | |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 1080 | bool GlobalOpt::runOnModule(Module &M) { |
| 1081 | bool Changed = false; |
| 1082 | |
| 1083 | // As a prepass, delete functions that are trivially dead. |
| 1084 | bool LocalChange = true; |
| 1085 | while (LocalChange) { |
| 1086 | LocalChange = false; |
| 1087 | for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) { |
| 1088 | Function *F = FI++; |
| 1089 | F->removeDeadConstantUsers(); |
Chris Lattner | 5d33e8e | 2004-10-14 19:53:50 +0000 | [diff] [blame] | 1090 | if (F->use_empty() && (F->hasInternalLinkage() || |
| 1091 | F->hasLinkOnceLinkage())) { |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 1092 | M.getFunctionList().erase(F); |
| 1093 | LocalChange = true; |
| 1094 | ++NumFnDeleted; |
Chris Lattner | a4c8022 | 2005-05-08 22:18:06 +0000 | [diff] [blame] | 1095 | } else if (F->hasInternalLinkage() && |
| 1096 | F->getCallingConv() == CallingConv::C && !F->isVarArg() && |
| 1097 | OnlyCalledDirectly(F)) { |
| 1098 | // If this function has C calling conventions, is not a varargs |
| 1099 | // function, and is only called directly, promote it to use the Fast |
| 1100 | // calling convention. |
| 1101 | F->setCallingConv(CallingConv::Fast); |
| 1102 | ChangeCalleesToFastCall(F); |
| 1103 | ++NumFastCallFns; |
| 1104 | LocalChange = true; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 1105 | } |
| 1106 | } |
| 1107 | Changed |= LocalChange; |
| 1108 | } |
| 1109 | |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1110 | LocalChange = true; |
| 1111 | while (LocalChange) { |
| 1112 | LocalChange = false; |
Chris Lattner | a4c8022 | 2005-05-08 22:18:06 +0000 | [diff] [blame] | 1113 | for (Module::global_iterator GVI = M.global_begin(), E = M.global_end(); |
| 1114 | GVI != E; ) { |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1115 | GlobalVariable *GV = GVI++; |
| 1116 | if (!GV->isConstant() && GV->hasInternalLinkage() && |
| 1117 | GV->hasInitializer()) |
| 1118 | LocalChange |= ProcessInternalGlobal(GV, GVI); |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 1119 | } |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1120 | Changed |= LocalChange; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 1121 | } |
| 1122 | return Changed; |
| 1123 | } |