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