Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 1 | //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===// |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +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 | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 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. |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 16 | #define DEBUG_TYPE "globalopt" |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 17 | #include "llvm/Transforms/IPO.h" |
Chris Lattner | fb217ad | 2005-05-08 22:18:06 +0000 | [diff] [blame] | 18 | #include "llvm/CallingConv.h" |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 19 | #include "llvm/Constants.h" |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 20 | #include "llvm/DerivedTypes.h" |
Chris Lattner | 7d90a27 | 2004-02-27 18:09:25 +0000 | [diff] [blame] | 21 | #include "llvm/Instructions.h" |
Chris Lattner | 35c81b0 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 22 | #include "llvm/IntrinsicInst.h" |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 23 | #include "llvm/Module.h" |
| 24 | #include "llvm/Pass.h" |
Chris Lattner | 79066fa | 2007-01-30 23:46:24 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/ConstantFolding.h" |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 26 | #include "llvm/Target/TargetData.h" |
Reid Spencer | 9133fe2 | 2007-02-05 23:32:05 +0000 | [diff] [blame] | 27 | #include "llvm/Support/Compiler.h" |
Chris Lattner | 79066fa | 2007-01-30 23:46:24 +0000 | [diff] [blame] | 28 | #include "llvm/Support/Debug.h" |
Chris Lattner | 55eb1c4 | 2007-01-31 04:40:53 +0000 | [diff] [blame] | 29 | #include "llvm/ADT/SmallVector.h" |
Reid Spencer | 551ccae | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 30 | #include "llvm/ADT/Statistic.h" |
Chris Lattner | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 31 | #include "llvm/ADT/StringExtras.h" |
Chris Lattner | e47ba74 | 2004-10-06 20:57:02 +0000 | [diff] [blame] | 32 | #include <algorithm> |
Chris Lattner | dac58ad | 2006-01-22 23:32:06 +0000 | [diff] [blame] | 33 | #include <set> |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 34 | using namespace llvm; |
| 35 | |
Chris Lattner | 86453c5 | 2006-12-19 22:09:18 +0000 | [diff] [blame] | 36 | STATISTIC(NumMarked , "Number of globals marked constant"); |
| 37 | STATISTIC(NumSRA , "Number of aggregate globals broken into scalars"); |
| 38 | STATISTIC(NumHeapSRA , "Number of heap objects SRA'd"); |
| 39 | STATISTIC(NumSubstitute,"Number of globals with initializers stored into them"); |
| 40 | STATISTIC(NumDeleted , "Number of globals deleted"); |
| 41 | STATISTIC(NumFnDeleted , "Number of functions deleted"); |
| 42 | STATISTIC(NumGlobUses , "Number of global uses devirtualized"); |
| 43 | STATISTIC(NumLocalized , "Number of globals localized"); |
| 44 | STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans"); |
| 45 | STATISTIC(NumFastCallFns , "Number of functions converted to fastcc"); |
| 46 | STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated"); |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 47 | |
Chris Lattner | 86453c5 | 2006-12-19 22:09:18 +0000 | [diff] [blame] | 48 | namespace { |
Reid Spencer | 9133fe2 | 2007-02-05 23:32:05 +0000 | [diff] [blame] | 49 | struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass { |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 50 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
| 51 | AU.addRequired<TargetData>(); |
| 52 | } |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 53 | |
Chris Lattner | b12914b | 2004-09-20 04:48:05 +0000 | [diff] [blame] | 54 | bool runOnModule(Module &M); |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 55 | |
| 56 | private: |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 57 | GlobalVariable *FindGlobalCtors(Module &M); |
| 58 | bool OptimizeFunctions(Module &M); |
| 59 | bool OptimizeGlobalVars(Module &M); |
| 60 | bool OptimizeGlobalCtorsList(GlobalVariable *&GCL); |
Chris Lattner | 7f8897f | 2006-08-27 22:42:52 +0000 | [diff] [blame] | 61 | bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI); |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 62 | }; |
| 63 | |
Chris Lattner | 7f8897f | 2006-08-27 22:42:52 +0000 | [diff] [blame] | 64 | RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer"); |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 65 | } |
| 66 | |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 67 | ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); } |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 68 | |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 69 | /// GlobalStatus - As we analyze each global, keep track of some information |
| 70 | /// about it. If we find out that the address of the global is taken, none of |
Chris Lattner | cf4d2a5 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 71 | /// this info will be accurate. |
Reid Spencer | 9133fe2 | 2007-02-05 23:32:05 +0000 | [diff] [blame] | 72 | struct VISIBILITY_HIDDEN GlobalStatus { |
Chris Lattner | cf4d2a5 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 73 | /// isLoaded - True if the global is ever loaded. If the global isn't ever |
| 74 | /// loaded it can be deleted. |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 75 | bool isLoaded; |
Chris Lattner | cf4d2a5 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 76 | |
| 77 | /// StoredType - Keep track of what stores to the global look like. |
| 78 | /// |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 79 | enum StoredType { |
Chris Lattner | cf4d2a5 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 80 | /// NotStored - There is no store to this global. It can thus be marked |
| 81 | /// constant. |
| 82 | NotStored, |
| 83 | |
| 84 | /// isInitializerStored - This global is stored to, but the only thing |
| 85 | /// stored is the constant it was initialized with. This is only tracked |
| 86 | /// for scalar globals. |
| 87 | isInitializerStored, |
| 88 | |
| 89 | /// isStoredOnce - This global is stored to, but only its initializer and |
| 90 | /// one other value is ever stored to it. If this global isStoredOnce, we |
| 91 | /// track the value stored to it in StoredOnceValue below. This is only |
| 92 | /// tracked for scalar globals. |
| 93 | isStoredOnce, |
| 94 | |
| 95 | /// isStored - This global is stored to by multiple values or something else |
| 96 | /// that we cannot track. |
| 97 | isStored |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 98 | } StoredType; |
Chris Lattner | cf4d2a5 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 99 | |
| 100 | /// StoredOnceValue - If only one value (besides the initializer constant) is |
| 101 | /// ever stored to this global, keep track of what value it is. |
| 102 | Value *StoredOnceValue; |
| 103 | |
Chris Lattner | 25de4e5 | 2006-11-01 18:03:33 +0000 | [diff] [blame] | 104 | /// AccessingFunction/HasMultipleAccessingFunctions - These start out |
| 105 | /// null/false. When the first accessing function is noticed, it is recorded. |
| 106 | /// When a second different accessing function is noticed, |
| 107 | /// HasMultipleAccessingFunctions is set to true. |
Alkis Evlogimenos | f64ea9d | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 108 | Function *AccessingFunction; |
| 109 | bool HasMultipleAccessingFunctions; |
| 110 | |
Chris Lattner | 25de4e5 | 2006-11-01 18:03:33 +0000 | [diff] [blame] | 111 | /// HasNonInstructionUser - Set to true if this global has a user that is not |
| 112 | /// an instruction (e.g. a constant expr or GV initializer). |
Chris Lattner | 553ca52 | 2005-06-15 21:11:48 +0000 | [diff] [blame] | 113 | bool HasNonInstructionUser; |
| 114 | |
Chris Lattner | 25de4e5 | 2006-11-01 18:03:33 +0000 | [diff] [blame] | 115 | /// HasPHIUser - Set to true if this global has a user that is a PHI node. |
| 116 | bool HasPHIUser; |
| 117 | |
Chris Lattner | cf4d2a5 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 118 | /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of |
| 119 | /// the global exist. Such users include GEP instruction with variable |
| 120 | /// indexes, and non-gep/load/store users like constant expr casts. |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 121 | bool isNotSuitableForSRA; |
Chris Lattner | 9ce3000 | 2004-07-20 03:58:07 +0000 | [diff] [blame] | 122 | |
Chris Lattner | cf4d2a5 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 123 | GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0), |
Alkis Evlogimenos | f64ea9d | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 124 | AccessingFunction(0), HasMultipleAccessingFunctions(false), |
Chris Lattner | 25de4e5 | 2006-11-01 18:03:33 +0000 | [diff] [blame] | 125 | HasNonInstructionUser(false), HasPHIUser(false), |
| 126 | isNotSuitableForSRA(false) {} |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 127 | }; |
Chris Lattner | e47ba74 | 2004-10-06 20:57:02 +0000 | [diff] [blame] | 128 | |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 129 | |
| 130 | |
| 131 | /// ConstantIsDead - Return true if the specified constant is (transitively) |
| 132 | /// dead. The constant may be used by other constants (e.g. constant arrays and |
| 133 | /// constant exprs) as long as they are dead, but it cannot be used by anything |
| 134 | /// else. |
| 135 | static bool ConstantIsDead(Constant *C) { |
| 136 | if (isa<GlobalValue>(C)) return false; |
| 137 | |
| 138 | for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI) |
| 139 | if (Constant *CU = dyn_cast<Constant>(*UI)) { |
| 140 | if (!ConstantIsDead(CU)) return false; |
| 141 | } else |
| 142 | return false; |
| 143 | return true; |
| 144 | } |
| 145 | |
| 146 | |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 147 | /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus |
| 148 | /// structure. If the global has its address taken, return true to indicate we |
| 149 | /// can't do anything with it. |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 150 | /// |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 151 | static bool AnalyzeGlobal(Value *V, GlobalStatus &GS, |
| 152 | std::set<PHINode*> &PHIUsers) { |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 153 | for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI) |
Chris Lattner | 96940cb | 2004-07-18 19:56:20 +0000 | [diff] [blame] | 154 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) { |
Chris Lattner | 553ca52 | 2005-06-15 21:11:48 +0000 | [diff] [blame] | 155 | GS.HasNonInstructionUser = true; |
| 156 | |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 157 | if (AnalyzeGlobal(CE, GS, PHIUsers)) return true; |
| 158 | if (CE->getOpcode() != Instruction::GetElementPtr) |
| 159 | GS.isNotSuitableForSRA = true; |
Chris Lattner | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 160 | else if (!GS.isNotSuitableForSRA) { |
| 161 | // Check to see if this ConstantExpr GEP is SRA'able. In particular, we |
| 162 | // don't like < 3 operand CE's, and we don't like non-constant integer |
| 163 | // indices. |
| 164 | if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue()) |
| 165 | GS.isNotSuitableForSRA = true; |
| 166 | else { |
| 167 | for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i) |
| 168 | if (!isa<ConstantInt>(CE->getOperand(i))) { |
| 169 | GS.isNotSuitableForSRA = true; |
| 170 | break; |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 175 | } else if (Instruction *I = dyn_cast<Instruction>(*UI)) { |
Alkis Evlogimenos | f64ea9d | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 176 | if (!GS.HasMultipleAccessingFunctions) { |
| 177 | Function *F = I->getParent()->getParent(); |
| 178 | if (GS.AccessingFunction == 0) |
| 179 | GS.AccessingFunction = F; |
| 180 | else if (GS.AccessingFunction != F) |
| 181 | GS.HasMultipleAccessingFunctions = true; |
| 182 | } |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 183 | if (isa<LoadInst>(I)) { |
| 184 | GS.isLoaded = true; |
| 185 | } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Chris Lattner | 3602549 | 2004-10-07 06:01:25 +0000 | [diff] [blame] | 186 | // Don't allow a store OF the address, only stores TO the address. |
| 187 | if (SI->getOperand(0) == V) return true; |
| 188 | |
Chris Lattner | cf4d2a5 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 189 | // If this is a direct store to the global (i.e., the global is a scalar |
| 190 | // value, not an aggregate), keep more specific information about |
| 191 | // stores. |
| 192 | if (GS.StoredType != GlobalStatus::isStored) |
| 193 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){ |
Chris Lattner | bd38edf | 2004-11-14 20:50:30 +0000 | [diff] [blame] | 194 | Value *StoredVal = SI->getOperand(0); |
| 195 | if (StoredVal == GV->getInitializer()) { |
| 196 | if (GS.StoredType < GlobalStatus::isInitializerStored) |
| 197 | GS.StoredType = GlobalStatus::isInitializerStored; |
| 198 | } else if (isa<LoadInst>(StoredVal) && |
| 199 | cast<LoadInst>(StoredVal)->getOperand(0) == GV) { |
| 200 | // G = G |
Chris Lattner | cf4d2a5 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 201 | if (GS.StoredType < GlobalStatus::isInitializerStored) |
| 202 | GS.StoredType = GlobalStatus::isInitializerStored; |
| 203 | } else if (GS.StoredType < GlobalStatus::isStoredOnce) { |
| 204 | GS.StoredType = GlobalStatus::isStoredOnce; |
Chris Lattner | bd38edf | 2004-11-14 20:50:30 +0000 | [diff] [blame] | 205 | GS.StoredOnceValue = StoredVal; |
Chris Lattner | cf4d2a5 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 206 | } else if (GS.StoredType == GlobalStatus::isStoredOnce && |
Chris Lattner | bd38edf | 2004-11-14 20:50:30 +0000 | [diff] [blame] | 207 | GS.StoredOnceValue == StoredVal) { |
Chris Lattner | cf4d2a5 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 208 | // noop. |
| 209 | } else { |
| 210 | GS.StoredType = GlobalStatus::isStored; |
| 211 | } |
| 212 | } else { |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 213 | GS.StoredType = GlobalStatus::isStored; |
Chris Lattner | cf4d2a5 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 214 | } |
Chris Lattner | 35c81b0 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 215 | } else if (isa<GetElementPtrInst>(I)) { |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 216 | if (AnalyzeGlobal(I, GS, PHIUsers)) return true; |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 217 | |
| 218 | // If the first two indices are constants, this can be SRA'd. |
| 219 | if (isa<GlobalVariable>(I->getOperand(0))) { |
| 220 | if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) || |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 221 | !cast<Constant>(I->getOperand(1))->isNullValue() || |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 222 | !isa<ConstantInt>(I->getOperand(2))) |
| 223 | GS.isNotSuitableForSRA = true; |
| 224 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){ |
| 225 | if (CE->getOpcode() != Instruction::GetElementPtr || |
| 226 | CE->getNumOperands() < 3 || I->getNumOperands() < 2 || |
| 227 | !isa<Constant>(I->getOperand(0)) || |
| 228 | !cast<Constant>(I->getOperand(0))->isNullValue()) |
| 229 | GS.isNotSuitableForSRA = true; |
| 230 | } else { |
| 231 | GS.isNotSuitableForSRA = true; |
| 232 | } |
Chris Lattner | 35c81b0 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 233 | } else if (isa<SelectInst>(I)) { |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 234 | if (AnalyzeGlobal(I, GS, PHIUsers)) return true; |
| 235 | GS.isNotSuitableForSRA = true; |
| 236 | } else if (PHINode *PN = dyn_cast<PHINode>(I)) { |
| 237 | // PHI nodes we can check just like select or GEP instructions, but we |
| 238 | // have to be careful about infinite recursion. |
| 239 | if (PHIUsers.insert(PN).second) // Not already visited. |
| 240 | if (AnalyzeGlobal(I, GS, PHIUsers)) return true; |
| 241 | GS.isNotSuitableForSRA = true; |
Chris Lattner | 25de4e5 | 2006-11-01 18:03:33 +0000 | [diff] [blame] | 242 | GS.HasPHIUser = true; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 243 | } else if (isa<CmpInst>(I)) { |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 244 | GS.isNotSuitableForSRA = true; |
Chris Lattner | 35c81b0 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 245 | } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) { |
| 246 | if (I->getOperand(1) == V) |
| 247 | GS.StoredType = GlobalStatus::isStored; |
| 248 | if (I->getOperand(2) == V) |
| 249 | GS.isLoaded = true; |
| 250 | GS.isNotSuitableForSRA = true; |
| 251 | } else if (isa<MemSetInst>(I)) { |
| 252 | assert(I->getOperand(1) == V && "Memset only takes one pointer!"); |
| 253 | GS.StoredType = GlobalStatus::isStored; |
| 254 | GS.isNotSuitableForSRA = true; |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 255 | } else { |
| 256 | return true; // Any other non-load instruction might take address! |
Chris Lattner | 9ce3000 | 2004-07-20 03:58:07 +0000 | [diff] [blame] | 257 | } |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 258 | } else if (Constant *C = dyn_cast<Constant>(*UI)) { |
Chris Lattner | 553ca52 | 2005-06-15 21:11:48 +0000 | [diff] [blame] | 259 | GS.HasNonInstructionUser = true; |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 260 | // We might have a dead and dangling constant hanging off of here. |
| 261 | if (!ConstantIsDead(C)) |
| 262 | return true; |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 263 | } else { |
Chris Lattner | 553ca52 | 2005-06-15 21:11:48 +0000 | [diff] [blame] | 264 | GS.HasNonInstructionUser = true; |
| 265 | // Otherwise must be some other user. |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 266 | return true; |
| 267 | } |
| 268 | |
| 269 | return false; |
| 270 | } |
| 271 | |
Chris Lattner | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 272 | static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) { |
| 273 | ConstantInt *CI = dyn_cast<ConstantInt>(Idx); |
| 274 | if (!CI) return 0; |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 275 | unsigned IdxV = CI->getZExtValue(); |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 276 | |
Chris Lattner | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 277 | if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) { |
| 278 | if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV); |
| 279 | } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) { |
| 280 | if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV); |
Reid Spencer | 9d6565a | 2007-02-15 02:26:10 +0000 | [diff] [blame^] | 281 | } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) { |
Chris Lattner | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 282 | if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV); |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 283 | } else if (isa<ConstantAggregateZero>(Agg)) { |
Chris Lattner | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 284 | if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) { |
| 285 | if (IdxV < STy->getNumElements()) |
| 286 | return Constant::getNullValue(STy->getElementType(IdxV)); |
| 287 | } else if (const SequentialType *STy = |
| 288 | dyn_cast<SequentialType>(Agg->getType())) { |
| 289 | return Constant::getNullValue(STy->getElementType()); |
| 290 | } |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 291 | } else if (isa<UndefValue>(Agg)) { |
| 292 | if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) { |
| 293 | if (IdxV < STy->getNumElements()) |
| 294 | return UndefValue::get(STy->getElementType(IdxV)); |
| 295 | } else if (const SequentialType *STy = |
| 296 | dyn_cast<SequentialType>(Agg->getType())) { |
| 297 | return UndefValue::get(STy->getElementType()); |
| 298 | } |
Chris Lattner | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 299 | } |
| 300 | return 0; |
| 301 | } |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 302 | |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 303 | |
Chris Lattner | e47ba74 | 2004-10-06 20:57:02 +0000 | [diff] [blame] | 304 | /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all |
| 305 | /// users of the global, cleaning up the obvious ones. This is largely just a |
Chris Lattner | 031955d | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 306 | /// quick scan over the use list to clean up the easy and obvious cruft. This |
| 307 | /// returns true if it made a change. |
| 308 | static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) { |
| 309 | bool Changed = false; |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 310 | for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) { |
| 311 | User *U = *UI++; |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 312 | |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 313 | if (LoadInst *LI = dyn_cast<LoadInst>(U)) { |
Chris Lattner | 35c81b0 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 314 | if (Init) { |
| 315 | // Replace the load with the initializer. |
| 316 | LI->replaceAllUsesWith(Init); |
| 317 | LI->eraseFromParent(); |
| 318 | Changed = true; |
| 319 | } |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 320 | } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) { |
Chris Lattner | e47ba74 | 2004-10-06 20:57:02 +0000 | [diff] [blame] | 321 | // Store must be unreachable or storing Init into the global. |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 322 | SI->eraseFromParent(); |
Chris Lattner | 031955d | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 323 | Changed = true; |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 324 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) { |
| 325 | if (CE->getOpcode() == Instruction::GetElementPtr) { |
Chris Lattner | aae4a1c | 2005-09-26 07:34:35 +0000 | [diff] [blame] | 326 | Constant *SubInit = 0; |
| 327 | if (Init) |
| 328 | SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE); |
Chris Lattner | 35c81b0 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 329 | Changed |= CleanupConstantGlobalUsers(CE, SubInit); |
Reid Spencer | 3da59db | 2006-11-27 01:05:10 +0000 | [diff] [blame] | 330 | } else if (CE->getOpcode() == Instruction::BitCast && |
Chris Lattner | 35c81b0 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 331 | isa<PointerType>(CE->getType())) { |
| 332 | // Pointer cast, delete any stores and memsets to the global. |
| 333 | Changed |= CleanupConstantGlobalUsers(CE, 0); |
| 334 | } |
| 335 | |
| 336 | if (CE->use_empty()) { |
| 337 | CE->destroyConstant(); |
| 338 | Changed = true; |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 339 | } |
| 340 | } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) { |
Chris Lattner | 0b142e3 | 2005-09-26 05:34:07 +0000 | [diff] [blame] | 341 | Constant *SubInit = 0; |
Chris Lattner | 798b4d5 | 2005-09-26 06:52:44 +0000 | [diff] [blame] | 342 | ConstantExpr *CE = |
| 343 | dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP)); |
Chris Lattner | 9a5582f | 2005-09-27 22:28:11 +0000 | [diff] [blame] | 344 | if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr) |
Chris Lattner | 0b142e3 | 2005-09-26 05:34:07 +0000 | [diff] [blame] | 345 | SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE); |
Chris Lattner | 35c81b0 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 346 | Changed |= CleanupConstantGlobalUsers(GEP, SubInit); |
Chris Lattner | c4d81b0 | 2004-10-10 16:47:33 +0000 | [diff] [blame] | 347 | |
Chris Lattner | 031955d | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 348 | if (GEP->use_empty()) { |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 349 | GEP->eraseFromParent(); |
Chris Lattner | 031955d | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 350 | Changed = true; |
| 351 | } |
Chris Lattner | 35c81b0 | 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 | a4be1dc | 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 | 35c81b0 | 2005-02-27 18:58:52 +0000 | [diff] [blame] | 363 | // This could have invalidated UI, start over from scratch. |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 364 | CleanupConstantGlobalUsers(V, Init); |
Chris Lattner | 031955d | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 365 | return true; |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 366 | } |
Chris Lattner | e47ba74 | 2004-10-06 20:57:02 +0000 | [diff] [blame] | 367 | } |
| 368 | } |
Chris Lattner | 031955d | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 369 | return Changed; |
Chris Lattner | e47ba74 | 2004-10-06 20:57:02 +0000 | [diff] [blame] | 370 | } |
| 371 | |
Chris Lattner | 670c889 | 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 | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 381 | |
Chris Lattner | 670c889 | 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, |
Reid Spencer | c5b206b | 2006-12-31 05:48:39 +0000 | [diff] [blame] | 389 | ConstantInt::get(Type::Int32Ty, i)); |
Chris Lattner | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 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(); |
Reid Spencer | 9d6565a | 2007-02-15 02:26:10 +0000 | [diff] [blame^] | 401 | else if (const VectorType *PTy = dyn_cast<VectorType>(STy)) |
Chris Lattner | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 402 | NumElements = PTy->getNumElements(); |
| 403 | else |
| 404 | assert(0 && "Unknown aggregate sequential type!"); |
| 405 | |
Chris Lattner | 1f21ef1 | 2005-02-23 16:53:04 +0000 | [diff] [blame] | 406 | if (NumElements > 16 && GV->hasNUsesOrMore(16)) |
Chris Lattner | d514d82 | 2005-02-01 01:23:31 +0000 | [diff] [blame] | 407 | return 0; // It's not worth it. |
Chris Lattner | 670c889 | 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, |
Reid Spencer | c5b206b | 2006-12-31 05:48:39 +0000 | [diff] [blame] | 411 | ConstantInt::get(Type::Int32Ty, i)); |
Chris Lattner | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 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 | |
Bill Wendling | 0a81aac | 2006-11-26 10:02:32 +0000 | [diff] [blame] | 425 | DOUT << "PERFORMING GLOBAL SRA ON: " << *GV; |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 426 | |
Reid Spencer | c5b206b | 2006-12-31 05:48:39 +0000 | [diff] [blame] | 427 | Constant *NullInt = Constant::getNullValue(Type::Int32Ty); |
Chris Lattner | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 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 | 30ba569 | 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 | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 436 | |
Chris Lattner | 670c889 | 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. |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 440 | unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue(); |
Chris Lattner | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 441 | if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access. |
| 442 | |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 443 | Value *NewPtr = NewGlobals[Val]; |
Chris Lattner | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 444 | |
| 445 | // Form a shorter GEP if needed. |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 446 | if (GEP->getNumOperands() > 3) |
| 447 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) { |
Chris Lattner | 55eb1c4 | 2007-01-31 04:40:53 +0000 | [diff] [blame] | 448 | SmallVector<Constant*, 8> Idxs; |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 449 | Idxs.push_back(NullInt); |
| 450 | for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i) |
| 451 | Idxs.push_back(CE->getOperand(i)); |
Chris Lattner | 55eb1c4 | 2007-01-31 04:40:53 +0000 | [diff] [blame] | 452 | NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), |
| 453 | &Idxs[0], Idxs.size()); |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 454 | } else { |
| 455 | GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP); |
Chris Lattner | 699d144 | 2007-01-31 19:59:55 +0000 | [diff] [blame] | 456 | SmallVector<Value*, 8> Idxs; |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 457 | Idxs.push_back(NullInt); |
| 458 | for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) |
| 459 | Idxs.push_back(GEPI->getOperand(i)); |
Chris Lattner | 699d144 | 2007-01-31 19:59:55 +0000 | [diff] [blame] | 460 | NewPtr = new GetElementPtrInst(NewPtr, &Idxs[0], Idxs.size(), |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 461 | GEPI->getName()+"."+utostr(Val), GEPI); |
| 462 | } |
| 463 | GEP->replaceAllUsesWith(NewPtr); |
| 464 | |
| 465 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP)) |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 466 | GEPI->eraseFromParent(); |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 467 | else |
| 468 | cast<ConstantExpr>(GEP)->destroyConstant(); |
Chris Lattner | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 469 | } |
| 470 | |
Chris Lattner | e40e2d1 | 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 | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 473 | ++NumSRA; |
Chris Lattner | 30ba569 | 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 | 670c889 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 486 | } |
| 487 | |
Chris Lattner | 9b34a61 | 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) { |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 496 | //cerr << "NONTRAPPING USE: " << **UI; |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 497 | return false; // Storing the value. |
| 498 | } |
| 499 | } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) { |
| 500 | if (CI->getOperand(0) != V) { |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 501 | //cerr << "NONTRAPPING USE: " << **UI; |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 502 | return false; // Not calling the ptr |
| 503 | } |
| 504 | } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) { |
| 505 | if (II->getOperand(0) != V) { |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 506 | //cerr << "NONTRAPPING USE: " << **UI; |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 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; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 513 | } else if (isa<ICmpInst>(*UI) && |
Chris Lattner | e9ece2a | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 514 | isa<ConstantPointerNull>(UI->getOperand(1))) { |
| 515 | // Ignore setcc X, null |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 516 | } else { |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 517 | //cerr << "NONTRAPPING USE: " << **UI; |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 518 | return false; |
| 519 | } |
| 520 | return true; |
| 521 | } |
| 522 | |
| 523 | /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads |
Chris Lattner | e9ece2a | 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 | 9b34a61 | 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. |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 535 | //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI; |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 536 | return false; |
| 537 | } |
| 538 | |
| 539 | return true; |
| 540 | } |
| 541 | |
Chris Lattner | 708148e | 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, |
Chris Lattner | 6e8fbad | 2006-11-30 17:32:29 +0000 | [diff] [blame] | 574 | ConstantExpr::getCast(CI->getOpcode(), |
| 575 | NewV, CI->getType())); |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 576 | if (CI->use_empty()) { |
| 577 | Changed = true; |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 578 | CI->eraseFromParent(); |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 579 | } |
| 580 | } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
| 581 | // Should handle GEP here. |
Chris Lattner | 55eb1c4 | 2007-01-31 04:40:53 +0000 | [diff] [blame] | 582 | SmallVector<Constant*, 8> Idxs; |
| 583 | Idxs.reserve(GEPI->getNumOperands()-1); |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 584 | for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i) |
| 585 | if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i))) |
Chris Lattner | 55eb1c4 | 2007-01-31 04:40:53 +0000 | [diff] [blame] | 586 | Idxs.push_back(C); |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 587 | else |
| 588 | break; |
Chris Lattner | 55eb1c4 | 2007-01-31 04:40:53 +0000 | [diff] [blame] | 589 | if (Idxs.size() == GEPI->getNumOperands()-1) |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 590 | Changed |= OptimizeAwayTrappingUsesOfValue(GEPI, |
Chris Lattner | 55eb1c4 | 2007-01-31 04:40:53 +0000 | [diff] [blame] | 591 | ConstantExpr::getGetElementPtr(NewV, &Idxs[0], |
| 592 | Idxs.size())); |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 593 | if (GEPI->use_empty()) { |
| 594 | Changed = true; |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 595 | GEPI->eraseFromParent(); |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 596 | } |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | return Changed; |
| 601 | } |
| 602 | |
| 603 | |
| 604 | /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null |
| 605 | /// value stored into it. If there are uses of the loaded value that would trap |
| 606 | /// if the loaded value is dynamically null, then we know that they cannot be |
| 607 | /// reachable with a null optimize away the load. |
| 608 | static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) { |
| 609 | std::vector<LoadInst*> Loads; |
| 610 | bool Changed = false; |
| 611 | |
| 612 | // Replace all uses of loads with uses of uses of the stored value. |
| 613 | for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); |
| 614 | GUI != E; ++GUI) |
| 615 | if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) { |
| 616 | Loads.push_back(LI); |
| 617 | Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV); |
| 618 | } else { |
| 619 | assert(isa<StoreInst>(*GUI) && "Only expect load and stores!"); |
| 620 | } |
| 621 | |
| 622 | if (Changed) { |
Bill Wendling | 0a81aac | 2006-11-26 10:02:32 +0000 | [diff] [blame] | 623 | DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV; |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 624 | ++NumGlobUses; |
| 625 | } |
| 626 | |
| 627 | // Delete all of the loads we can, keeping track of whether we nuked them all! |
| 628 | bool AllLoadsGone = true; |
| 629 | while (!Loads.empty()) { |
| 630 | LoadInst *L = Loads.back(); |
| 631 | if (L->use_empty()) { |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 632 | L->eraseFromParent(); |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 633 | Changed = true; |
| 634 | } else { |
| 635 | AllLoadsGone = false; |
| 636 | } |
| 637 | Loads.pop_back(); |
| 638 | } |
| 639 | |
| 640 | // If we nuked all of the loads, then none of the stores are needed either, |
| 641 | // nor is the global. |
| 642 | if (AllLoadsGone) { |
Bill Wendling | 0a81aac | 2006-11-26 10:02:32 +0000 | [diff] [blame] | 643 | DOUT << " *** GLOBAL NOW DEAD!\n"; |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 644 | CleanupConstantGlobalUsers(GV, 0); |
| 645 | if (GV->use_empty()) { |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 646 | GV->eraseFromParent(); |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 647 | ++NumDeleted; |
| 648 | } |
| 649 | Changed = true; |
| 650 | } |
| 651 | return Changed; |
| 652 | } |
| 653 | |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 654 | /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the |
| 655 | /// instructions that are foldable. |
| 656 | static void ConstantPropUsersOf(Value *V) { |
| 657 | for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) |
| 658 | if (Instruction *I = dyn_cast<Instruction>(*UI++)) |
| 659 | if (Constant *NewC = ConstantFoldInstruction(I)) { |
| 660 | I->replaceAllUsesWith(NewC); |
| 661 | |
Chris Lattner | d514d82 | 2005-02-01 01:23:31 +0000 | [diff] [blame] | 662 | // Advance UI to the next non-I use to avoid invalidating it! |
| 663 | // Instructions could multiply use V. |
| 664 | while (UI != E && *UI == I) |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 665 | ++UI; |
Chris Lattner | d514d82 | 2005-02-01 01:23:31 +0000 | [diff] [blame] | 666 | I->eraseFromParent(); |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 667 | } |
| 668 | } |
| 669 | |
| 670 | /// OptimizeGlobalAddressOfMalloc - This function takes the specified global |
| 671 | /// variable, and transforms the program as if it always contained the result of |
| 672 | /// the specified malloc. Because it is always the result of the specified |
| 673 | /// malloc, there is no reason to actually DO the malloc. Instead, turn the |
Chris Lattner | 6e8fbad | 2006-11-30 17:32:29 +0000 | [diff] [blame] | 674 | /// malloc into a global, and any loads of GV as uses of the new global. |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 675 | static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, |
| 676 | MallocInst *MI) { |
Bill Wendling | 0a81aac | 2006-11-26 10:02:32 +0000 | [diff] [blame] | 677 | DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI; |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 678 | ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize()); |
| 679 | |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 680 | if (NElements->getZExtValue() != 1) { |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 681 | // If we have an array allocation, transform it to a single element |
| 682 | // allocation to make the code below simpler. |
| 683 | Type *NewTy = ArrayType::get(MI->getAllocatedType(), |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 684 | NElements->getZExtValue()); |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 685 | MallocInst *NewMI = |
Reid Spencer | c5b206b | 2006-12-31 05:48:39 +0000 | [diff] [blame] | 686 | new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty), |
Nate Begeman | 14b0529 | 2005-11-05 09:21:28 +0000 | [diff] [blame] | 687 | MI->getAlignment(), MI->getName(), MI); |
Chris Lattner | 699d144 | 2007-01-31 19:59:55 +0000 | [diff] [blame] | 688 | Value* Indices[2]; |
| 689 | Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty); |
| 690 | Value *NewGEP = new GetElementPtrInst(NewMI, Indices, 2, |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 691 | NewMI->getName()+".el0", MI); |
| 692 | MI->replaceAllUsesWith(NewGEP); |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 693 | MI->eraseFromParent(); |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 694 | MI = NewMI; |
| 695 | } |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 696 | |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 697 | // Create the new global variable. The contents of the malloc'd memory is |
| 698 | // undefined, so initialize with an undef value. |
| 699 | Constant *Init = UndefValue::get(MI->getAllocatedType()); |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 700 | GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false, |
| 701 | GlobalValue::InternalLinkage, Init, |
| 702 | GV->getName()+".body"); |
| 703 | GV->getParent()->getGlobalList().insert(GV, NewGV); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 704 | |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 705 | // Anything that used the malloc now uses the global directly. |
| 706 | MI->replaceAllUsesWith(NewGV); |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 707 | |
| 708 | Constant *RepValue = NewGV; |
| 709 | if (NewGV->getType() != GV->getType()->getElementType()) |
Reid Spencer | d977d86 | 2006-12-12 23:36:14 +0000 | [diff] [blame] | 710 | RepValue = ConstantExpr::getBitCast(RepValue, |
| 711 | GV->getType()->getElementType()); |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 712 | |
Chris Lattner | e9ece2a | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 713 | // If there is a comparison against null, we will insert a global bool to |
| 714 | // keep track of whether the global was initialized yet or not. |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 715 | GlobalVariable *InitBool = |
Reid Spencer | 4fe16d6 | 2007-01-11 18:21:29 +0000 | [diff] [blame] | 716 | new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage, |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 717 | ConstantInt::getFalse(), GV->getName()+".init"); |
Chris Lattner | bc965b9 | 2004-12-02 06:25:58 +0000 | [diff] [blame] | 718 | bool InitBoolUsed = false; |
Chris Lattner | e9ece2a | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 719 | |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 720 | // Loop over all uses of GV, processing them in turn. |
Chris Lattner | bc965b9 | 2004-12-02 06:25:58 +0000 | [diff] [blame] | 721 | std::vector<StoreInst*> Stores; |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 722 | while (!GV->use_empty()) |
| 723 | if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) { |
Chris Lattner | e9ece2a | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 724 | while (!LI->use_empty()) { |
Chris Lattner | d514d82 | 2005-02-01 01:23:31 +0000 | [diff] [blame] | 725 | Use &LoadUse = LI->use_begin().getUse(); |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 726 | if (!isa<ICmpInst>(LoadUse.getUser())) |
Chris Lattner | e9ece2a | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 727 | LoadUse = RepValue; |
| 728 | else { |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 729 | ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser()); |
| 730 | // Replace the cmp X, 0 with a use of the bool value. |
| 731 | Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI); |
Chris Lattner | bc965b9 | 2004-12-02 06:25:58 +0000 | [diff] [blame] | 732 | InitBoolUsed = true; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 733 | switch (CI->getPredicate()) { |
| 734 | default: assert(0 && "Unknown ICmp Predicate!"); |
| 735 | case ICmpInst::ICMP_ULT: |
| 736 | case ICmpInst::ICMP_SLT: |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 737 | LV = ConstantInt::getFalse(); // X < null -> always false |
Chris Lattner | e9ece2a | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 738 | break; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 739 | case ICmpInst::ICMP_ULE: |
| 740 | case ICmpInst::ICMP_SLE: |
| 741 | case ICmpInst::ICMP_EQ: |
| 742 | LV = BinaryOperator::createNot(LV, "notinit", CI); |
Chris Lattner | e9ece2a | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 743 | break; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 744 | case ICmpInst::ICMP_NE: |
| 745 | case ICmpInst::ICMP_UGE: |
| 746 | case ICmpInst::ICMP_SGE: |
| 747 | case ICmpInst::ICMP_UGT: |
| 748 | case ICmpInst::ICMP_SGT: |
Chris Lattner | e9ece2a | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 749 | break; // no change. |
| 750 | } |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 751 | CI->replaceAllUsesWith(LV); |
| 752 | CI->eraseFromParent(); |
Chris Lattner | e9ece2a | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 753 | } |
| 754 | } |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 755 | LI->eraseFromParent(); |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 756 | } else { |
| 757 | StoreInst *SI = cast<StoreInst>(GV->use_back()); |
Chris Lattner | bc965b9 | 2004-12-02 06:25:58 +0000 | [diff] [blame] | 758 | // The global is initialized when the store to it occurs. |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 759 | new StoreInst(ConstantInt::getTrue(), InitBool, SI); |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 760 | SI->eraseFromParent(); |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 761 | } |
| 762 | |
Chris Lattner | bc965b9 | 2004-12-02 06:25:58 +0000 | [diff] [blame] | 763 | // If the initialization boolean was used, insert it, otherwise delete it. |
| 764 | if (!InitBoolUsed) { |
| 765 | while (!InitBool->use_empty()) // Delete initializations |
| 766 | cast<Instruction>(InitBool->use_back())->eraseFromParent(); |
| 767 | delete InitBool; |
| 768 | } else |
| 769 | GV->getParent()->getGlobalList().insert(GV, InitBool); |
| 770 | |
| 771 | |
Chris Lattner | e9ece2a | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 772 | // Now the GV is dead, nuke it and the malloc. |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 773 | GV->eraseFromParent(); |
Chris Lattner | e9ece2a | 2004-10-22 06:43:28 +0000 | [diff] [blame] | 774 | MI->eraseFromParent(); |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 775 | |
| 776 | // To further other optimizations, loop over all users of NewGV and try to |
| 777 | // constant prop them. This will promote GEP instructions with constant |
| 778 | // indices into GEP constant-exprs, which will allow global-opt to hack on it. |
| 779 | ConstantPropUsersOf(NewGV); |
| 780 | if (RepValue != NewGV) |
| 781 | ConstantPropUsersOf(RepValue); |
| 782 | |
| 783 | return NewGV; |
| 784 | } |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 785 | |
Chris Lattner | fa07e4f | 2004-12-02 07:11:07 +0000 | [diff] [blame] | 786 | /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking |
| 787 | /// to make sure that there are no complex uses of V. We permit simple things |
| 788 | /// like dereferencing the pointer, but not storing through the address, unless |
| 789 | /// it is to the specified global. |
| 790 | static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V, |
| 791 | GlobalVariable *GV) { |
| 792 | for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI) |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 793 | if (isa<LoadInst>(*UI) || isa<CmpInst>(*UI)) { |
Chris Lattner | fa07e4f | 2004-12-02 07:11:07 +0000 | [diff] [blame] | 794 | // Fine, ignore. |
| 795 | } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) { |
| 796 | if (SI->getOperand(0) == V && SI->getOperand(1) != GV) |
| 797 | return false; // Storing the pointer itself... bad. |
| 798 | // Otherwise, storing through it, or storing into GV... fine. |
| 799 | } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) { |
| 800 | if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV)) |
| 801 | return false; |
| 802 | } else { |
| 803 | return false; |
| 804 | } |
| 805 | return true; |
Chris Lattner | fa07e4f | 2004-12-02 07:11:07 +0000 | [diff] [blame] | 806 | } |
| 807 | |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 808 | /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV |
| 809 | /// somewhere. Transform all uses of the allocation into loads from the |
| 810 | /// global and uses of the resultant pointer. Further, delete the store into |
| 811 | /// GV. This assumes that these value pass the |
| 812 | /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate. |
| 813 | static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc, |
| 814 | GlobalVariable *GV) { |
| 815 | while (!Alloc->use_empty()) { |
| 816 | Instruction *U = Alloc->use_back(); |
| 817 | if (StoreInst *SI = dyn_cast<StoreInst>(U)) { |
| 818 | // If this is the store of the allocation into the global, remove it. |
| 819 | if (SI->getOperand(1) == GV) { |
| 820 | SI->eraseFromParent(); |
| 821 | continue; |
| 822 | } |
| 823 | } |
| 824 | |
| 825 | // Insert a load from the global, and use it instead of the malloc. |
| 826 | Value *NL = new LoadInst(GV, GV->getName()+".val", U); |
| 827 | U->replaceUsesOfWith(Alloc, NL); |
| 828 | } |
| 829 | } |
| 830 | |
| 831 | /// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from |
| 832 | /// GV are simple enough to perform HeapSRA, return true. |
| 833 | static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV) { |
| 834 | for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E; |
| 835 | ++UI) |
| 836 | if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) { |
| 837 | // We permit two users of the load: setcc comparing against the null |
| 838 | // pointer, and a getelementptr of a specific form. |
| 839 | for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E; |
| 840 | ++UI) { |
| 841 | // Comparison against null is ok. |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 842 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) { |
| 843 | if (!isa<ConstantPointerNull>(ICI->getOperand(1))) |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 844 | return false; |
| 845 | continue; |
| 846 | } |
| 847 | |
| 848 | // getelementptr is also ok, but only a simple form. |
| 849 | GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI); |
| 850 | if (!GEPI) return false; |
| 851 | |
| 852 | // Must index into the array and into the struct. |
| 853 | if (GEPI->getNumOperands() < 3) |
| 854 | return false; |
| 855 | |
| 856 | // Otherwise the GEP is ok. |
| 857 | continue; |
| 858 | } |
| 859 | } |
| 860 | return true; |
| 861 | } |
| 862 | |
| 863 | /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr |
| 864 | /// is a value loaded from the global. Eliminate all uses of Ptr, making them |
| 865 | /// use FieldGlobals instead. All uses of loaded values satisfy |
| 866 | /// GlobalLoadUsesSimpleEnoughForHeapSRA. |
| 867 | static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Ptr, |
| 868 | const std::vector<GlobalVariable*> &FieldGlobals) { |
| 869 | std::vector<Value *> InsertedLoadsForPtr; |
| 870 | //InsertedLoadsForPtr.resize(FieldGlobals.size()); |
| 871 | while (!Ptr->use_empty()) { |
| 872 | Instruction *User = Ptr->use_back(); |
| 873 | |
| 874 | // If this is a comparison against null, handle it. |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 875 | if (ICmpInst *SCI = dyn_cast<ICmpInst>(User)) { |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 876 | assert(isa<ConstantPointerNull>(SCI->getOperand(1))); |
| 877 | // If we have a setcc of the loaded pointer, we can use a setcc of any |
| 878 | // field. |
| 879 | Value *NPtr; |
| 880 | if (InsertedLoadsForPtr.empty()) { |
| 881 | NPtr = new LoadInst(FieldGlobals[0], Ptr->getName()+".f0", Ptr); |
| 882 | InsertedLoadsForPtr.push_back(Ptr); |
| 883 | } else { |
| 884 | NPtr = InsertedLoadsForPtr.back(); |
| 885 | } |
| 886 | |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 887 | Value *New = new ICmpInst(SCI->getPredicate(), NPtr, |
| 888 | Constant::getNullValue(NPtr->getType()), |
| 889 | SCI->getName(), SCI); |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 890 | SCI->replaceAllUsesWith(New); |
| 891 | SCI->eraseFromParent(); |
| 892 | continue; |
| 893 | } |
| 894 | |
| 895 | // Otherwise, this should be: 'getelementptr Ptr, Idx, uint FieldNo ...' |
| 896 | GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User); |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 897 | assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2)) |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 898 | && "Unexpected GEPI!"); |
| 899 | |
| 900 | // Load the pointer for this field. |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 901 | unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue(); |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 902 | if (InsertedLoadsForPtr.size() <= FieldNo) |
| 903 | InsertedLoadsForPtr.resize(FieldNo+1); |
| 904 | if (InsertedLoadsForPtr[FieldNo] == 0) |
| 905 | InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo], |
| 906 | Ptr->getName()+".f" + |
| 907 | utostr(FieldNo), Ptr); |
| 908 | Value *NewPtr = InsertedLoadsForPtr[FieldNo]; |
| 909 | |
| 910 | // Create the new GEP idx vector. |
Chris Lattner | 1ccd185 | 2007-02-12 22:56:41 +0000 | [diff] [blame] | 911 | SmallVector<Value*, 8> GEPIdx; |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 912 | GEPIdx.push_back(GEPI->getOperand(1)); |
Chris Lattner | 1ccd185 | 2007-02-12 22:56:41 +0000 | [diff] [blame] | 913 | GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end()); |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 914 | |
Chris Lattner | 1ccd185 | 2007-02-12 22:56:41 +0000 | [diff] [blame] | 915 | Value *NGEPI = new GetElementPtrInst(NewPtr, &GEPIdx[0], GEPIdx.size(), |
| 916 | GEPI->getName(), GEPI); |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 917 | GEPI->replaceAllUsesWith(NGEPI); |
| 918 | GEPI->eraseFromParent(); |
| 919 | } |
| 920 | } |
| 921 | |
| 922 | /// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break |
| 923 | /// it up into multiple allocations of arrays of the fields. |
| 924 | static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){ |
Bill Wendling | 0a81aac | 2006-11-26 10:02:32 +0000 | [diff] [blame] | 925 | DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI; |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 926 | const StructType *STy = cast<StructType>(MI->getAllocatedType()); |
| 927 | |
| 928 | // There is guaranteed to be at least one use of the malloc (storing |
| 929 | // it into GV). If there are other uses, change them to be uses of |
| 930 | // the global to simplify later code. This also deletes the store |
| 931 | // into GV. |
| 932 | ReplaceUsesOfMallocWithGlobal(MI, GV); |
| 933 | |
| 934 | // Okay, at this point, there are no users of the malloc. Insert N |
| 935 | // new mallocs at the same place as MI, and N globals. |
| 936 | std::vector<GlobalVariable*> FieldGlobals; |
| 937 | std::vector<MallocInst*> FieldMallocs; |
| 938 | |
| 939 | for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){ |
| 940 | const Type *FieldTy = STy->getElementType(FieldNo); |
| 941 | const Type *PFieldTy = PointerType::get(FieldTy); |
| 942 | |
| 943 | GlobalVariable *NGV = |
| 944 | new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage, |
| 945 | Constant::getNullValue(PFieldTy), |
| 946 | GV->getName() + ".f" + utostr(FieldNo), GV); |
| 947 | FieldGlobals.push_back(NGV); |
| 948 | |
| 949 | MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(), |
| 950 | MI->getName() + ".f" + utostr(FieldNo),MI); |
| 951 | FieldMallocs.push_back(NMI); |
| 952 | new StoreInst(NMI, NGV, MI); |
| 953 | } |
| 954 | |
| 955 | // The tricky aspect of this transformation is handling the case when malloc |
| 956 | // fails. In the original code, malloc failing would set the result pointer |
| 957 | // of malloc to null. In this case, some mallocs could succeed and others |
| 958 | // could fail. As such, we emit code that looks like this: |
| 959 | // F0 = malloc(field0) |
| 960 | // F1 = malloc(field1) |
| 961 | // F2 = malloc(field2) |
| 962 | // if (F0 == 0 || F1 == 0 || F2 == 0) { |
| 963 | // if (F0) { free(F0); F0 = 0; } |
| 964 | // if (F1) { free(F1); F1 = 0; } |
| 965 | // if (F2) { free(F2); F2 = 0; } |
| 966 | // } |
| 967 | Value *RunningOr = 0; |
| 968 | for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) { |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 969 | Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i], |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 970 | Constant::getNullValue(FieldMallocs[i]->getType()), |
| 971 | "isnull", MI); |
| 972 | if (!RunningOr) |
| 973 | RunningOr = Cond; // First seteq |
| 974 | else |
| 975 | RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI); |
| 976 | } |
| 977 | |
| 978 | // Split the basic block at the old malloc. |
| 979 | BasicBlock *OrigBB = MI->getParent(); |
| 980 | BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont"); |
| 981 | |
| 982 | // Create the block to check the first condition. Put all these blocks at the |
| 983 | // end of the function as they are unlikely to be executed. |
| 984 | BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null", |
| 985 | OrigBB->getParent()); |
| 986 | |
| 987 | // Remove the uncond branch from OrigBB to ContBB, turning it into a cond |
| 988 | // branch on RunningOr. |
| 989 | OrigBB->getTerminator()->eraseFromParent(); |
| 990 | new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB); |
| 991 | |
| 992 | // Within the NullPtrBlock, we need to emit a comparison and branch for each |
| 993 | // pointer, because some may be null while others are not. |
| 994 | for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) { |
| 995 | Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock); |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 996 | Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal, |
| 997 | Constant::getNullValue(GVVal->getType()), |
| 998 | "tmp", NullPtrBlock); |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 999 | BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent()); |
| 1000 | BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent()); |
| 1001 | new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock); |
| 1002 | |
| 1003 | // Fill in FreeBlock. |
| 1004 | new FreeInst(GVVal, FreeBlock); |
| 1005 | new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i], |
| 1006 | FreeBlock); |
| 1007 | new BranchInst(NextBlock, FreeBlock); |
| 1008 | |
| 1009 | NullPtrBlock = NextBlock; |
| 1010 | } |
| 1011 | |
| 1012 | new BranchInst(ContBB, NullPtrBlock); |
| 1013 | |
| 1014 | |
| 1015 | // MI is no longer needed, remove it. |
| 1016 | MI->eraseFromParent(); |
| 1017 | |
| 1018 | |
| 1019 | // Okay, the malloc site is completely handled. All of the uses of GV are now |
| 1020 | // loads, and all uses of those loads are simple. Rewrite them to use loads |
| 1021 | // of the per-field globals instead. |
| 1022 | while (!GV->use_empty()) { |
Chris Lattner | 39ff1e2 | 2007-01-09 23:29:37 +0000 | [diff] [blame] | 1023 | if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) { |
| 1024 | RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals); |
| 1025 | LI->eraseFromParent(); |
| 1026 | } else { |
| 1027 | // Must be a store of null. |
| 1028 | StoreInst *SI = cast<StoreInst>(GV->use_back()); |
| 1029 | assert(isa<Constant>(SI->getOperand(0)) && |
| 1030 | cast<Constant>(SI->getOperand(0))->isNullValue() && |
| 1031 | "Unexpected heap-sra user!"); |
| 1032 | |
| 1033 | // Insert a store of null into each global. |
| 1034 | for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) { |
| 1035 | Constant *Null = |
| 1036 | Constant::getNullValue(FieldGlobals[i]->getType()->getElementType()); |
| 1037 | new StoreInst(Null, FieldGlobals[i], SI); |
| 1038 | } |
| 1039 | // Erase the original store. |
| 1040 | SI->eraseFromParent(); |
| 1041 | } |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 1042 | } |
| 1043 | |
| 1044 | // The old global is now dead, remove it. |
| 1045 | GV->eraseFromParent(); |
| 1046 | |
| 1047 | ++NumHeapSRA; |
| 1048 | return FieldGlobals[0]; |
| 1049 | } |
| 1050 | |
| 1051 | |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 1052 | // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge |
| 1053 | // that only one value (besides its initializer) is ever stored to the global. |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 1054 | static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, |
Chris Lattner | 7f8897f | 2006-08-27 22:42:52 +0000 | [diff] [blame] | 1055 | Module::global_iterator &GVI, |
| 1056 | TargetData &TD) { |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 1057 | if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal)) |
| 1058 | StoredOnceVal = CI->getOperand(0); |
| 1059 | else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){ |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 1060 | // "getelementptr Ptr, 0, 0, 0" is really just a cast. |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 1061 | bool IsJustACast = true; |
| 1062 | for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i) |
| 1063 | if (!isa<Constant>(GEPI->getOperand(i)) || |
| 1064 | !cast<Constant>(GEPI->getOperand(i))->isNullValue()) { |
| 1065 | IsJustACast = false; |
| 1066 | break; |
| 1067 | } |
| 1068 | if (IsJustACast) |
| 1069 | StoredOnceVal = GEPI->getOperand(0); |
| 1070 | } |
| 1071 | |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 1072 | // If we are dealing with a pointer global that is initialized to null and |
| 1073 | // only has one (non-null) value stored into it, then we can optimize any |
| 1074 | // users of the loaded value (often calls and loads) that would trap if the |
| 1075 | // value was null. |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 1076 | if (isa<PointerType>(GV->getInitializer()->getType()) && |
| 1077 | GV->getInitializer()->isNullValue()) { |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 1078 | if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) { |
| 1079 | if (GV->getInitializer()->getType() != SOVC->getType()) |
Reid Spencer | d977d86 | 2006-12-12 23:36:14 +0000 | [diff] [blame] | 1080 | SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType()); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1081 | |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 1082 | // Optimize away any trapping uses of the loaded value. |
| 1083 | if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC)) |
Chris Lattner | 8be8012 | 2004-10-10 17:07:12 +0000 | [diff] [blame] | 1084 | return true; |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 1085 | } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) { |
Chris Lattner | cff1673 | 2006-09-30 19:40:30 +0000 | [diff] [blame] | 1086 | // If this is a malloc of an abstract type, don't touch it. |
| 1087 | if (!MI->getAllocatedType()->isSized()) |
| 1088 | return false; |
| 1089 | |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 1090 | // We can't optimize this global unless all uses of it are *known* to be |
| 1091 | // of the malloc value, not of the null initializer value (consider a use |
| 1092 | // that compares the global's value against zero to see if the malloc has |
| 1093 | // been reached). To do this, we check to see if all uses of the global |
| 1094 | // would trap if the global were null: this proves that they must all |
| 1095 | // happen after the malloc. |
| 1096 | if (!AllUsesOfLoadedValueWillTrapIfNull(GV)) |
| 1097 | return false; |
| 1098 | |
| 1099 | // We can't optimize this if the malloc itself is used in a complex way, |
| 1100 | // for example, being stored into multiple globals. This allows the |
| 1101 | // malloc to be stored into the specified global, loaded setcc'd, and |
| 1102 | // GEP'd. These are all things we could transform to using the global |
| 1103 | // for. |
| 1104 | if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV)) |
| 1105 | return false; |
| 1106 | |
| 1107 | |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 1108 | // If we have a global that is only initialized with a fixed size malloc, |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 1109 | // transform the program to use global memory instead of malloc'd memory. |
| 1110 | // This eliminates dynamic allocation, avoids an indirection accessing the |
| 1111 | // data, and exposes the resultant global to further GlobalOpt. |
Chris Lattner | cff1673 | 2006-09-30 19:40:30 +0000 | [diff] [blame] | 1112 | if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) { |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 1113 | // Restrict this transformation to only working on small allocations |
| 1114 | // (2048 bytes currently), as we don't want to introduce a 16M global or |
| 1115 | // something. |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 1116 | if (NElements->getZExtValue()* |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 1117 | TD.getTypeSize(MI->getAllocatedType()) < 2048) { |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 1118 | GVI = OptimizeGlobalAddressOfMalloc(GV, MI); |
| 1119 | return true; |
| 1120 | } |
Chris Lattner | cff1673 | 2006-09-30 19:40:30 +0000 | [diff] [blame] | 1121 | } |
Chris Lattner | 8639503 | 2006-09-30 23:32:09 +0000 | [diff] [blame] | 1122 | |
| 1123 | // If the allocation is an array of structures, consider transforming this |
| 1124 | // into multiple malloc'd arrays, one for each field. This is basically |
| 1125 | // SRoA for malloc'd memory. |
| 1126 | if (const StructType *AllocTy = |
| 1127 | dyn_cast<StructType>(MI->getAllocatedType())) { |
| 1128 | // This the structure has an unreasonable number of fields, leave it |
| 1129 | // alone. |
| 1130 | if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 && |
| 1131 | GlobalLoadUsesSimpleEnoughForHeapSRA(GV)) { |
| 1132 | GVI = PerformHeapAllocSRoA(GV, MI); |
| 1133 | return true; |
| 1134 | } |
| 1135 | } |
Chris Lattner | 708148e | 2004-10-10 23:14:11 +0000 | [diff] [blame] | 1136 | } |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 1137 | } |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 1138 | |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 1139 | return false; |
| 1140 | } |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1141 | |
Chris Lattner | 96a86b2 | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1142 | /// ShrinkGlobalToBoolean - At this point, we have learned that the only two |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1143 | /// values ever stored into GV are its initializer and OtherVal. |
Chris Lattner | 96a86b2 | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1144 | static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) { |
| 1145 | // Create the new global, initializing it to false. |
Reid Spencer | 4fe16d6 | 2007-01-11 18:21:29 +0000 | [diff] [blame] | 1146 | GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false, |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1147 | GlobalValue::InternalLinkage, ConstantInt::getFalse(), |
Chris Lattner | 47811b7 | 2006-09-28 23:35:22 +0000 | [diff] [blame] | 1148 | GV->getName()+".b"); |
Chris Lattner | 96a86b2 | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1149 | GV->getParent()->getGlobalList().insert(GV, NewGV); |
| 1150 | |
| 1151 | Constant *InitVal = GV->getInitializer(); |
Reid Spencer | 4fe16d6 | 2007-01-11 18:21:29 +0000 | [diff] [blame] | 1152 | assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!"); |
Chris Lattner | 96a86b2 | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1153 | |
| 1154 | // If initialized to zero and storing one into the global, we can use a cast |
| 1155 | // instead of a select to synthesize the desired value. |
| 1156 | bool IsOneZero = false; |
| 1157 | if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) |
| 1158 | IsOneZero = InitVal->isNullValue() && CI->equalsInt(1); |
| 1159 | |
| 1160 | while (!GV->use_empty()) { |
| 1161 | Instruction *UI = cast<Instruction>(GV->use_back()); |
| 1162 | if (StoreInst *SI = dyn_cast<StoreInst>(UI)) { |
| 1163 | // Change the store into a boolean store. |
| 1164 | bool StoringOther = SI->getOperand(0) == OtherVal; |
| 1165 | // Only do this if we weren't storing a loaded value. |
Chris Lattner | 38c2556 | 2004-12-12 19:34:41 +0000 | [diff] [blame] | 1166 | Value *StoreVal; |
Chris Lattner | 96a86b2 | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1167 | if (StoringOther || SI->getOperand(0) == InitVal) |
Reid Spencer | 579dca1 | 2007-01-12 04:24:46 +0000 | [diff] [blame] | 1168 | StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther); |
Chris Lattner | 38c2556 | 2004-12-12 19:34:41 +0000 | [diff] [blame] | 1169 | else { |
| 1170 | // Otherwise, we are storing a previously loaded copy. To do this, |
| 1171 | // change the copy from copying the original value to just copying the |
| 1172 | // bool. |
| 1173 | Instruction *StoredVal = cast<Instruction>(SI->getOperand(0)); |
| 1174 | |
| 1175 | // If we're already replaced the input, StoredVal will be a cast or |
| 1176 | // select instruction. If not, it will be a load of the original |
| 1177 | // global. |
| 1178 | if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) { |
| 1179 | assert(LI->getOperand(0) == GV && "Not a copy!"); |
| 1180 | // Insert a new load, to preserve the saved value. |
| 1181 | StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI); |
| 1182 | } else { |
| 1183 | assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) && |
| 1184 | "This is not a form that we understand!"); |
| 1185 | StoreVal = StoredVal->getOperand(0); |
| 1186 | assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!"); |
| 1187 | } |
| 1188 | } |
| 1189 | new StoreInst(StoreVal, NewGV, SI); |
| 1190 | } else if (!UI->use_empty()) { |
Chris Lattner | 96a86b2 | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1191 | // Change the load into a load of bool then a select. |
| 1192 | LoadInst *LI = cast<LoadInst>(UI); |
Chris Lattner | 046800a | 2007-02-11 01:08:35 +0000 | [diff] [blame] | 1193 | LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI); |
Chris Lattner | 96a86b2 | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1194 | Value *NSI; |
| 1195 | if (IsOneZero) |
Chris Lattner | 046800a | 2007-02-11 01:08:35 +0000 | [diff] [blame] | 1196 | NSI = new ZExtInst(NLI, LI->getType(), "", LI); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1197 | else |
Chris Lattner | 046800a | 2007-02-11 01:08:35 +0000 | [diff] [blame] | 1198 | NSI = new SelectInst(NLI, OtherVal, InitVal, "", LI); |
| 1199 | NSI->takeName(LI); |
Chris Lattner | 96a86b2 | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1200 | LI->replaceAllUsesWith(NSI); |
| 1201 | } |
| 1202 | UI->eraseFromParent(); |
| 1203 | } |
| 1204 | |
| 1205 | GV->eraseFromParent(); |
| 1206 | } |
| 1207 | |
| 1208 | |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1209 | /// ProcessInternalGlobal - Analyze the specified global variable and optimize |
| 1210 | /// it if possible. If we make a change, return true. |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 1211 | bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV, |
Chris Lattner | e4d5c44 | 2005-03-15 04:54:21 +0000 | [diff] [blame] | 1212 | Module::global_iterator &GVI) { |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1213 | std::set<PHINode*> PHIUsers; |
| 1214 | GlobalStatus GS; |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1215 | GV->removeDeadConstantUsers(); |
| 1216 | |
| 1217 | if (GV->use_empty()) { |
Bill Wendling | 0a81aac | 2006-11-26 10:02:32 +0000 | [diff] [blame] | 1218 | DOUT << "GLOBAL DEAD: " << *GV; |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 1219 | GV->eraseFromParent(); |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1220 | ++NumDeleted; |
| 1221 | return true; |
| 1222 | } |
| 1223 | |
| 1224 | if (!AnalyzeGlobal(GV, GS, PHIUsers)) { |
Chris Lattner | cff1673 | 2006-09-30 19:40:30 +0000 | [diff] [blame] | 1225 | #if 0 |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 1226 | cerr << "Global: " << *GV; |
| 1227 | cerr << " isLoaded = " << GS.isLoaded << "\n"; |
| 1228 | cerr << " StoredType = "; |
Chris Lattner | cff1673 | 2006-09-30 19:40:30 +0000 | [diff] [blame] | 1229 | switch (GS.StoredType) { |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 1230 | case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break; |
| 1231 | case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break; |
| 1232 | case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break; |
| 1233 | case GlobalStatus::isStored: cerr << "stored\n"; break; |
Chris Lattner | cff1673 | 2006-09-30 19:40:30 +0000 | [diff] [blame] | 1234 | } |
| 1235 | if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue) |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 1236 | cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n"; |
Chris Lattner | cff1673 | 2006-09-30 19:40:30 +0000 | [diff] [blame] | 1237 | if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions) |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 1238 | cerr << " AccessingFunction = " << GS.AccessingFunction->getName() |
Chris Lattner | cff1673 | 2006-09-30 19:40:30 +0000 | [diff] [blame] | 1239 | << "\n"; |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 1240 | cerr << " HasMultipleAccessingFunctions = " |
Chris Lattner | cff1673 | 2006-09-30 19:40:30 +0000 | [diff] [blame] | 1241 | << GS.HasMultipleAccessingFunctions << "\n"; |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 1242 | cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n"; |
| 1243 | cerr << " isNotSuitableForSRA = " << GS.isNotSuitableForSRA << "\n"; |
| 1244 | cerr << "\n"; |
Chris Lattner | cff1673 | 2006-09-30 19:40:30 +0000 | [diff] [blame] | 1245 | #endif |
| 1246 | |
Alkis Evlogimenos | f64ea9d | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 1247 | // If this is a first class global and has only one accessing function |
| 1248 | // and this function is main (which we know is not recursive we can make |
| 1249 | // this global a local variable) we replace the global with a local alloca |
| 1250 | // in this function. |
| 1251 | // |
| 1252 | // NOTE: It doesn't make sense to promote non first class types since we |
| 1253 | // are just replacing static memory to stack memory. |
| 1254 | if (!GS.HasMultipleAccessingFunctions && |
Chris Lattner | 553ca52 | 2005-06-15 21:11:48 +0000 | [diff] [blame] | 1255 | GS.AccessingFunction && !GS.HasNonInstructionUser && |
Alkis Evlogimenos | f64ea9d | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 1256 | GV->getType()->getElementType()->isFirstClassType() && |
| 1257 | GS.AccessingFunction->getName() == "main" && |
| 1258 | GS.AccessingFunction->hasExternalLinkage()) { |
Bill Wendling | 0a81aac | 2006-11-26 10:02:32 +0000 | [diff] [blame] | 1259 | DOUT << "LOCALIZING GLOBAL: " << *GV; |
Alkis Evlogimenos | f64ea9d | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 1260 | Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin(); |
| 1261 | const Type* ElemTy = GV->getType()->getElementType(); |
Nate Begeman | 14b0529 | 2005-11-05 09:21:28 +0000 | [diff] [blame] | 1262 | // FIXME: Pass Global's alignment when globals have alignment |
Alkis Evlogimenos | f64ea9d | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 1263 | AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI); |
| 1264 | if (!isa<UndefValue>(GV->getInitializer())) |
| 1265 | new StoreInst(GV->getInitializer(), Alloca, FirstI); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1266 | |
Alkis Evlogimenos | f64ea9d | 2005-02-10 18:36:30 +0000 | [diff] [blame] | 1267 | GV->replaceAllUsesWith(Alloca); |
| 1268 | GV->eraseFromParent(); |
| 1269 | ++NumLocalized; |
| 1270 | return true; |
| 1271 | } |
Chris Lattner | cff1673 | 2006-09-30 19:40:30 +0000 | [diff] [blame] | 1272 | |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1273 | // If the global is never loaded (but may be stored to), it is dead. |
| 1274 | // Delete it now. |
| 1275 | if (!GS.isLoaded) { |
Bill Wendling | 0a81aac | 2006-11-26 10:02:32 +0000 | [diff] [blame] | 1276 | DOUT << "GLOBAL NEVER LOADED: " << *GV; |
Chris Lattner | 930f475 | 2004-10-09 03:32:52 +0000 | [diff] [blame] | 1277 | |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1278 | // Delete any stores we can find to the global. We may not be able to |
| 1279 | // make it completely dead though. |
Chris Lattner | 031955d | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 1280 | bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer()); |
Chris Lattner | 930f475 | 2004-10-09 03:32:52 +0000 | [diff] [blame] | 1281 | |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1282 | // If the global is dead now, delete it. |
| 1283 | if (GV->use_empty()) { |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 1284 | GV->eraseFromParent(); |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1285 | ++NumDeleted; |
Chris Lattner | 930f475 | 2004-10-09 03:32:52 +0000 | [diff] [blame] | 1286 | Changed = true; |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1287 | } |
Chris Lattner | 930f475 | 2004-10-09 03:32:52 +0000 | [diff] [blame] | 1288 | return Changed; |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1289 | |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1290 | } else if (GS.StoredType <= GlobalStatus::isInitializerStored) { |
Bill Wendling | 0a81aac | 2006-11-26 10:02:32 +0000 | [diff] [blame] | 1291 | DOUT << "MARKING CONSTANT: " << *GV; |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1292 | GV->setConstant(true); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1293 | |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1294 | // Clean up any obviously simplifiable users now. |
| 1295 | CleanupConstantGlobalUsers(GV, GV->getInitializer()); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1296 | |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1297 | // If the global is dead now, just nuke it. |
| 1298 | if (GV->use_empty()) { |
Bill Wendling | 0a81aac | 2006-11-26 10:02:32 +0000 | [diff] [blame] | 1299 | DOUT << " *** Marking constant allowed us to simplify " |
| 1300 | << "all users and delete global!\n"; |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 1301 | GV->eraseFromParent(); |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1302 | ++NumDeleted; |
| 1303 | } |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1304 | |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1305 | ++NumMarked; |
| 1306 | return true; |
| 1307 | } else if (!GS.isNotSuitableForSRA && |
| 1308 | !GV->getInitializer()->getType()->isFirstClassType()) { |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1309 | if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) { |
| 1310 | GVI = FirstNewGV; // Don't skip the newly produced globals! |
| 1311 | return true; |
| 1312 | } |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 1313 | } else if (GS.StoredType == GlobalStatus::isStoredOnce) { |
Chris Lattner | 96a86b2 | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1314 | // If the initial value for the global was an undef value, and if only |
| 1315 | // one other value was stored into it, we can just change the |
| 1316 | // initializer to be an undef value, then delete all stores to the |
| 1317 | // global. This allows us to mark it constant. |
| 1318 | if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) |
| 1319 | if (isa<UndefValue>(GV->getInitializer())) { |
| 1320 | // Change the initial value here. |
| 1321 | GV->setInitializer(SOVConstant); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1322 | |
Chris Lattner | 96a86b2 | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1323 | // Clean up any obviously simplifiable users now. |
| 1324 | CleanupConstantGlobalUsers(GV, GV->getInitializer()); |
Misha Brukman | fd93908 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1325 | |
Chris Lattner | 96a86b2 | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1326 | if (GV->use_empty()) { |
Bill Wendling | 0a81aac | 2006-11-26 10:02:32 +0000 | [diff] [blame] | 1327 | DOUT << " *** Substituting initializer allowed us to " |
| 1328 | << "simplify all users and delete global!\n"; |
Chris Lattner | 96a86b2 | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1329 | GV->eraseFromParent(); |
| 1330 | ++NumDeleted; |
| 1331 | } else { |
| 1332 | GVI = GV; |
| 1333 | } |
| 1334 | ++NumSubstitute; |
| 1335 | return true; |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 1336 | } |
Chris Lattner | 7a7ed02 | 2004-10-16 18:09:00 +0000 | [diff] [blame] | 1337 | |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 1338 | // Try to optimize globals based on the knowledge that only one value |
| 1339 | // (besides its initializer) is ever stored to the global. |
Chris Lattner | 30ba569 | 2004-10-11 05:54:41 +0000 | [diff] [blame] | 1340 | if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI, |
| 1341 | getAnalysis<TargetData>())) |
Chris Lattner | 9b34a61 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 1342 | return true; |
Chris Lattner | 96a86b2 | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1343 | |
| 1344 | // Otherwise, if the global was not a boolean, we can shrink it to be a |
| 1345 | // boolean. |
| 1346 | if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) |
Reid Spencer | 4fe16d6 | 2007-01-11 18:21:29 +0000 | [diff] [blame] | 1347 | if (GV->getType()->getElementType() != Type::Int1Ty && |
Chris Lattner | 25de4e5 | 2006-11-01 18:03:33 +0000 | [diff] [blame] | 1348 | !GV->getType()->getElementType()->isFloatingPoint() && |
Reid Spencer | 9d6565a | 2007-02-15 02:26:10 +0000 | [diff] [blame^] | 1349 | !isa<VectorType>(GV->getType()->getElementType()) && |
Chris Lattner | 25de4e5 | 2006-11-01 18:03:33 +0000 | [diff] [blame] | 1350 | !GS.HasPHIUser) { |
Bill Wendling | 0a81aac | 2006-11-26 10:02:32 +0000 | [diff] [blame] | 1351 | DOUT << " *** SHRINKING TO BOOL: " << *GV; |
Chris Lattner | 96a86b2 | 2004-12-12 05:53:50 +0000 | [diff] [blame] | 1352 | ShrinkGlobalToBoolean(GV, SOVConstant); |
| 1353 | ++NumShrunkToBool; |
| 1354 | return true; |
| 1355 | } |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1356 | } |
| 1357 | } |
| 1358 | return false; |
| 1359 | } |
| 1360 | |
Chris Lattner | fb217ad | 2005-05-08 22:18:06 +0000 | [diff] [blame] | 1361 | /// OnlyCalledDirectly - Return true if the specified function is only called |
| 1362 | /// directly. In other words, its address is never taken. |
| 1363 | static bool OnlyCalledDirectly(Function *F) { |
| 1364 | for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){ |
| 1365 | Instruction *User = dyn_cast<Instruction>(*UI); |
| 1366 | if (!User) return false; |
| 1367 | if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false; |
| 1368 | |
| 1369 | // See if the function address is passed as an argument. |
| 1370 | for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i) |
| 1371 | if (User->getOperand(i) == F) return false; |
| 1372 | } |
| 1373 | return true; |
| 1374 | } |
| 1375 | |
| 1376 | /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified |
| 1377 | /// function, changing them to FastCC. |
| 1378 | static void ChangeCalleesToFastCall(Function *F) { |
| 1379 | for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){ |
| 1380 | Instruction *User = cast<Instruction>(*UI); |
| 1381 | if (CallInst *CI = dyn_cast<CallInst>(User)) |
| 1382 | CI->setCallingConv(CallingConv::Fast); |
| 1383 | else |
| 1384 | cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast); |
| 1385 | } |
| 1386 | } |
Chris Lattner | a4be1dc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 1387 | |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 1388 | bool GlobalOpt::OptimizeFunctions(Module &M) { |
| 1389 | bool Changed = false; |
| 1390 | // Optimize functions. |
| 1391 | for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) { |
| 1392 | Function *F = FI++; |
| 1393 | F->removeDeadConstantUsers(); |
| 1394 | if (F->use_empty() && (F->hasInternalLinkage() || |
| 1395 | F->hasLinkOnceLinkage())) { |
| 1396 | M.getFunctionList().erase(F); |
| 1397 | Changed = true; |
| 1398 | ++NumFnDeleted; |
| 1399 | } else if (F->hasInternalLinkage() && |
| 1400 | F->getCallingConv() == CallingConv::C && !F->isVarArg() && |
| 1401 | OnlyCalledDirectly(F)) { |
| 1402 | // If this function has C calling conventions, is not a varargs |
| 1403 | // function, and is only called directly, promote it to use the Fast |
| 1404 | // calling convention. |
| 1405 | F->setCallingConv(CallingConv::Fast); |
| 1406 | ChangeCalleesToFastCall(F); |
| 1407 | ++NumFastCallFns; |
| 1408 | Changed = true; |
| 1409 | } |
| 1410 | } |
| 1411 | return Changed; |
| 1412 | } |
| 1413 | |
| 1414 | bool GlobalOpt::OptimizeGlobalVars(Module &M) { |
| 1415 | bool Changed = false; |
| 1416 | for (Module::global_iterator GVI = M.global_begin(), E = M.global_end(); |
| 1417 | GVI != E; ) { |
| 1418 | GlobalVariable *GV = GVI++; |
| 1419 | if (!GV->isConstant() && GV->hasInternalLinkage() && |
| 1420 | GV->hasInitializer()) |
| 1421 | Changed |= ProcessInternalGlobal(GV, GVI); |
| 1422 | } |
| 1423 | return Changed; |
| 1424 | } |
| 1425 | |
| 1426 | /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all |
| 1427 | /// initializers have an init priority of 65535. |
| 1428 | GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) { |
Alkis Evlogimenos | e9c6d36 | 2005-10-25 11:18:06 +0000 | [diff] [blame] | 1429 | for (Module::global_iterator I = M.global_begin(), E = M.global_end(); |
| 1430 | I != E; ++I) |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 1431 | if (I->getName() == "llvm.global_ctors") { |
| 1432 | // Found it, verify it's an array of { int, void()* }. |
| 1433 | const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType()); |
| 1434 | if (!ATy) return 0; |
| 1435 | const StructType *STy = dyn_cast<StructType>(ATy->getElementType()); |
| 1436 | if (!STy || STy->getNumElements() != 2 || |
Reid Spencer | c5b206b | 2006-12-31 05:48:39 +0000 | [diff] [blame] | 1437 | STy->getElementType(0) != Type::Int32Ty) return 0; |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 1438 | const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1)); |
| 1439 | if (!PFTy) return 0; |
| 1440 | const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType()); |
| 1441 | if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() || |
| 1442 | FTy->getNumParams() != 0) |
| 1443 | return 0; |
| 1444 | |
| 1445 | // Verify that the initializer is simple enough for us to handle. |
| 1446 | if (!I->hasInitializer()) return 0; |
| 1447 | ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer()); |
| 1448 | if (!CA) return 0; |
| 1449 | for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) |
| 1450 | if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) { |
Chris Lattner | 7d8e58f | 2005-09-26 02:19:27 +0000 | [diff] [blame] | 1451 | if (isa<ConstantPointerNull>(CS->getOperand(1))) |
| 1452 | continue; |
| 1453 | |
| 1454 | // Must have a function or null ptr. |
| 1455 | if (!isa<Function>(CS->getOperand(1))) |
| 1456 | return 0; |
| 1457 | |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 1458 | // Init priority must be standard. |
| 1459 | ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0)); |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 1460 | if (!CI || CI->getZExtValue() != 65535) |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 1461 | return 0; |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 1462 | } else { |
| 1463 | return 0; |
| 1464 | } |
| 1465 | |
| 1466 | return I; |
| 1467 | } |
| 1468 | return 0; |
| 1469 | } |
| 1470 | |
Chris Lattner | db973e6 | 2005-09-26 02:31:18 +0000 | [diff] [blame] | 1471 | /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand, |
| 1472 | /// return a list of the functions and null terminator as a vector. |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 1473 | static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) { |
| 1474 | ConstantArray *CA = cast<ConstantArray>(GV->getInitializer()); |
| 1475 | std::vector<Function*> Result; |
| 1476 | Result.reserve(CA->getNumOperands()); |
| 1477 | for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) { |
| 1478 | ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i)); |
| 1479 | Result.push_back(dyn_cast<Function>(CS->getOperand(1))); |
| 1480 | } |
| 1481 | return Result; |
| 1482 | } |
| 1483 | |
Chris Lattner | db973e6 | 2005-09-26 02:31:18 +0000 | [diff] [blame] | 1484 | /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the |
| 1485 | /// specified array, returning the new global to use. |
| 1486 | static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL, |
| 1487 | const std::vector<Function*> &Ctors) { |
| 1488 | // If we made a change, reassemble the initializer list. |
| 1489 | std::vector<Constant*> CSVals; |
Reid Spencer | c5b206b | 2006-12-31 05:48:39 +0000 | [diff] [blame] | 1490 | CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535)); |
Chris Lattner | db973e6 | 2005-09-26 02:31:18 +0000 | [diff] [blame] | 1491 | CSVals.push_back(0); |
| 1492 | |
| 1493 | // Create the new init list. |
| 1494 | std::vector<Constant*> CAList; |
| 1495 | for (unsigned i = 0, e = Ctors.size(); i != e; ++i) { |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1496 | if (Ctors[i]) { |
Chris Lattner | db973e6 | 2005-09-26 02:31:18 +0000 | [diff] [blame] | 1497 | CSVals[1] = Ctors[i]; |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1498 | } else { |
Chris Lattner | db973e6 | 2005-09-26 02:31:18 +0000 | [diff] [blame] | 1499 | const Type *FTy = FunctionType::get(Type::VoidTy, |
| 1500 | std::vector<const Type*>(), false); |
| 1501 | const PointerType *PFTy = PointerType::get(FTy); |
| 1502 | CSVals[1] = Constant::getNullValue(PFTy); |
Reid Spencer | c5b206b | 2006-12-31 05:48:39 +0000 | [diff] [blame] | 1503 | CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647); |
Chris Lattner | db973e6 | 2005-09-26 02:31:18 +0000 | [diff] [blame] | 1504 | } |
| 1505 | CAList.push_back(ConstantStruct::get(CSVals)); |
| 1506 | } |
| 1507 | |
| 1508 | // Create the array initializer. |
| 1509 | const Type *StructTy = |
| 1510 | cast<ArrayType>(GCL->getType()->getElementType())->getElementType(); |
| 1511 | Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()), |
| 1512 | CAList); |
| 1513 | |
| 1514 | // If we didn't change the number of elements, don't create a new GV. |
| 1515 | if (CA->getType() == GCL->getInitializer()->getType()) { |
| 1516 | GCL->setInitializer(CA); |
| 1517 | return GCL; |
| 1518 | } |
| 1519 | |
| 1520 | // Create the new global and insert it next to the existing list. |
| 1521 | GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(), |
Chris Lattner | 046800a | 2007-02-11 01:08:35 +0000 | [diff] [blame] | 1522 | GCL->getLinkage(), CA); |
Chris Lattner | db973e6 | 2005-09-26 02:31:18 +0000 | [diff] [blame] | 1523 | GCL->getParent()->getGlobalList().insert(GCL, NGV); |
Chris Lattner | 046800a | 2007-02-11 01:08:35 +0000 | [diff] [blame] | 1524 | NGV->takeName(GCL); |
Chris Lattner | db973e6 | 2005-09-26 02:31:18 +0000 | [diff] [blame] | 1525 | |
| 1526 | // Nuke the old list, replacing any uses with the new one. |
| 1527 | if (!GCL->use_empty()) { |
| 1528 | Constant *V = NGV; |
| 1529 | if (V->getType() != GCL->getType()) |
Reid Spencer | d977d86 | 2006-12-12 23:36:14 +0000 | [diff] [blame] | 1530 | V = ConstantExpr::getBitCast(V, GCL->getType()); |
Chris Lattner | db973e6 | 2005-09-26 02:31:18 +0000 | [diff] [blame] | 1531 | GCL->replaceAllUsesWith(V); |
| 1532 | } |
| 1533 | GCL->eraseFromParent(); |
| 1534 | |
| 1535 | if (Ctors.size()) |
| 1536 | return NGV; |
| 1537 | else |
| 1538 | return 0; |
| 1539 | } |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1540 | |
| 1541 | |
| 1542 | static Constant *getVal(std::map<Value*, Constant*> &ComputedValues, |
| 1543 | Value *V) { |
| 1544 | if (Constant *CV = dyn_cast<Constant>(V)) return CV; |
| 1545 | Constant *R = ComputedValues[V]; |
| 1546 | assert(R && "Reference to an uncomputed value!"); |
| 1547 | return R; |
| 1548 | } |
| 1549 | |
| 1550 | /// isSimpleEnoughPointerToCommit - Return true if this constant is simple |
| 1551 | /// enough for us to understand. In particular, if it is a cast of something, |
| 1552 | /// we punt. We basically just support direct accesses to globals and GEP's of |
| 1553 | /// globals. This should be kept up to date with CommitValueTo. |
| 1554 | static bool isSimpleEnoughPointerToCommit(Constant *C) { |
Chris Lattner | 231308c | 2005-09-27 04:50:03 +0000 | [diff] [blame] | 1555 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) { |
| 1556 | if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage()) |
Anton Korobeynikov | b74ed07 | 2006-09-14 18:23:27 +0000 | [diff] [blame] | 1557 | return false; // do not allow weak/linkonce/dllimport/dllexport linkage. |
Reid Spencer | 5cbf985 | 2007-01-30 20:08:39 +0000 | [diff] [blame] | 1558 | return !GV->isDeclaration(); // reject external globals. |
Chris Lattner | 231308c | 2005-09-27 04:50:03 +0000 | [diff] [blame] | 1559 | } |
Chris Lattner | 798b4d5 | 2005-09-26 06:52:44 +0000 | [diff] [blame] | 1560 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) |
| 1561 | // Handle a constantexpr gep. |
| 1562 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 1563 | isa<GlobalVariable>(CE->getOperand(0))) { |
| 1564 | GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0)); |
Chris Lattner | 231308c | 2005-09-27 04:50:03 +0000 | [diff] [blame] | 1565 | if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage()) |
Anton Korobeynikov | b74ed07 | 2006-09-14 18:23:27 +0000 | [diff] [blame] | 1566 | return false; // do not allow weak/linkonce/dllimport/dllexport linkage. |
Chris Lattner | 798b4d5 | 2005-09-26 06:52:44 +0000 | [diff] [blame] | 1567 | return GV->hasInitializer() && |
| 1568 | ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE); |
| 1569 | } |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1570 | return false; |
| 1571 | } |
| 1572 | |
Chris Lattner | 798b4d5 | 2005-09-26 06:52:44 +0000 | [diff] [blame] | 1573 | /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global |
| 1574 | /// initializer. This returns 'Init' modified to reflect 'Val' stored into it. |
| 1575 | /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into. |
| 1576 | static Constant *EvaluateStoreInto(Constant *Init, Constant *Val, |
| 1577 | ConstantExpr *Addr, unsigned OpNo) { |
| 1578 | // Base case of the recursion. |
| 1579 | if (OpNo == Addr->getNumOperands()) { |
| 1580 | assert(Val->getType() == Init->getType() && "Type mismatch!"); |
| 1581 | return Val; |
| 1582 | } |
| 1583 | |
| 1584 | if (const StructType *STy = dyn_cast<StructType>(Init->getType())) { |
| 1585 | std::vector<Constant*> Elts; |
| 1586 | |
| 1587 | // Break up the constant into its elements. |
| 1588 | if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) { |
| 1589 | for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) |
| 1590 | Elts.push_back(CS->getOperand(i)); |
| 1591 | } else if (isa<ConstantAggregateZero>(Init)) { |
| 1592 | for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) |
| 1593 | Elts.push_back(Constant::getNullValue(STy->getElementType(i))); |
| 1594 | } else if (isa<UndefValue>(Init)) { |
| 1595 | for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) |
| 1596 | Elts.push_back(UndefValue::get(STy->getElementType(i))); |
| 1597 | } else { |
| 1598 | assert(0 && "This code is out of sync with " |
| 1599 | " ConstantFoldLoadThroughGEPConstantExpr"); |
| 1600 | } |
| 1601 | |
| 1602 | // Replace the element that we are supposed to. |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 1603 | ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo)); |
| 1604 | unsigned Idx = CU->getZExtValue(); |
| 1605 | assert(Idx < STy->getNumElements() && "Struct index out of range!"); |
Chris Lattner | 798b4d5 | 2005-09-26 06:52:44 +0000 | [diff] [blame] | 1606 | Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1); |
| 1607 | |
| 1608 | // Return the modified struct. |
| 1609 | return ConstantStruct::get(Elts); |
| 1610 | } else { |
| 1611 | ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo)); |
| 1612 | const ArrayType *ATy = cast<ArrayType>(Init->getType()); |
| 1613 | |
| 1614 | // Break up the array into elements. |
| 1615 | std::vector<Constant*> Elts; |
| 1616 | if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) { |
| 1617 | for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) |
| 1618 | Elts.push_back(CA->getOperand(i)); |
| 1619 | } else if (isa<ConstantAggregateZero>(Init)) { |
| 1620 | Constant *Elt = Constant::getNullValue(ATy->getElementType()); |
| 1621 | Elts.assign(ATy->getNumElements(), Elt); |
| 1622 | } else if (isa<UndefValue>(Init)) { |
| 1623 | Constant *Elt = UndefValue::get(ATy->getElementType()); |
| 1624 | Elts.assign(ATy->getNumElements(), Elt); |
| 1625 | } else { |
| 1626 | assert(0 && "This code is out of sync with " |
| 1627 | " ConstantFoldLoadThroughGEPConstantExpr"); |
| 1628 | } |
| 1629 | |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 1630 | assert(CI->getZExtValue() < ATy->getNumElements()); |
| 1631 | Elts[CI->getZExtValue()] = |
| 1632 | EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1); |
Chris Lattner | 798b4d5 | 2005-09-26 06:52:44 +0000 | [diff] [blame] | 1633 | return ConstantArray::get(ATy, Elts); |
| 1634 | } |
| 1635 | } |
| 1636 | |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1637 | /// CommitValueTo - We have decided that Addr (which satisfies the predicate |
| 1638 | /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen. |
| 1639 | static void CommitValueTo(Constant *Val, Constant *Addr) { |
Chris Lattner | 798b4d5 | 2005-09-26 06:52:44 +0000 | [diff] [blame] | 1640 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) { |
| 1641 | assert(GV->hasInitializer()); |
| 1642 | GV->setInitializer(Val); |
| 1643 | return; |
| 1644 | } |
| 1645 | |
| 1646 | ConstantExpr *CE = cast<ConstantExpr>(Addr); |
| 1647 | GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0)); |
| 1648 | |
| 1649 | Constant *Init = GV->getInitializer(); |
| 1650 | Init = EvaluateStoreInto(Init, Val, CE, 2); |
| 1651 | GV->setInitializer(Init); |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1652 | } |
| 1653 | |
Chris Lattner | 562a055 | 2005-09-26 05:16:34 +0000 | [diff] [blame] | 1654 | /// ComputeLoadResult - Return the value that would be computed by a load from |
| 1655 | /// P after the stores reflected by 'memory' have been performed. If we can't |
| 1656 | /// decide, return null. |
Chris Lattner | 04de1cf | 2005-09-26 05:15:37 +0000 | [diff] [blame] | 1657 | static Constant *ComputeLoadResult(Constant *P, |
| 1658 | const std::map<Constant*, Constant*> &Memory) { |
| 1659 | // If this memory location has been recently stored, use the stored value: it |
| 1660 | // is the most up-to-date. |
| 1661 | std::map<Constant*, Constant*>::const_iterator I = Memory.find(P); |
| 1662 | if (I != Memory.end()) return I->second; |
| 1663 | |
| 1664 | // Access it. |
| 1665 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) { |
| 1666 | if (GV->hasInitializer()) |
| 1667 | return GV->getInitializer(); |
| 1668 | return 0; |
Chris Lattner | 04de1cf | 2005-09-26 05:15:37 +0000 | [diff] [blame] | 1669 | } |
Chris Lattner | 798b4d5 | 2005-09-26 06:52:44 +0000 | [diff] [blame] | 1670 | |
| 1671 | // Handle a constantexpr getelementptr. |
| 1672 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P)) |
| 1673 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 1674 | isa<GlobalVariable>(CE->getOperand(0))) { |
| 1675 | GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0)); |
| 1676 | if (GV->hasInitializer()) |
| 1677 | return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE); |
| 1678 | } |
| 1679 | |
| 1680 | return 0; // don't know how to evaluate. |
Chris Lattner | 04de1cf | 2005-09-26 05:15:37 +0000 | [diff] [blame] | 1681 | } |
| 1682 | |
Chris Lattner | 8a7cc6e | 2005-09-27 04:27:01 +0000 | [diff] [blame] | 1683 | /// EvaluateFunction - Evaluate a call to function F, returning true if |
| 1684 | /// successful, false if we can't evaluate it. ActualArgs contains the formal |
| 1685 | /// arguments for the function. |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1686 | static bool EvaluateFunction(Function *F, Constant *&RetVal, |
Chris Lattner | 8a7cc6e | 2005-09-27 04:27:01 +0000 | [diff] [blame] | 1687 | const std::vector<Constant*> &ActualArgs, |
| 1688 | std::vector<Function*> &CallStack, |
| 1689 | std::map<Constant*, Constant*> &MutatedMemory, |
| 1690 | std::vector<GlobalVariable*> &AllocaTmps) { |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1691 | // Check to see if this function is already executing (recursion). If so, |
| 1692 | // bail out. TODO: we might want to accept limited recursion. |
| 1693 | if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end()) |
| 1694 | return false; |
| 1695 | |
| 1696 | CallStack.push_back(F); |
| 1697 | |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1698 | /// Values - As we compute SSA register values, we store their contents here. |
| 1699 | std::map<Value*, Constant*> Values; |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1700 | |
| 1701 | // Initialize arguments to the incoming values specified. |
| 1702 | unsigned ArgNo = 0; |
| 1703 | for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E; |
| 1704 | ++AI, ++ArgNo) |
| 1705 | Values[AI] = ActualArgs[ArgNo]; |
Chris Lattner | 8a7cc6e | 2005-09-27 04:27:01 +0000 | [diff] [blame] | 1706 | |
Chris Lattner | cdf98be | 2005-09-26 04:57:38 +0000 | [diff] [blame] | 1707 | /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such, |
| 1708 | /// we can only evaluate any one basic block at most once. This set keeps |
| 1709 | /// track of what we have executed so we can detect recursive cases etc. |
| 1710 | std::set<BasicBlock*> ExecutedBlocks; |
Chris Lattner | a22fdb0 | 2005-09-26 17:07:09 +0000 | [diff] [blame] | 1711 | |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1712 | // CurInst - The current instruction we're evaluating. |
| 1713 | BasicBlock::iterator CurInst = F->begin()->begin(); |
| 1714 | |
| 1715 | // This is the main evaluation loop. |
| 1716 | while (1) { |
| 1717 | Constant *InstResult = 0; |
| 1718 | |
| 1719 | if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) { |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1720 | if (SI->isVolatile()) return false; // no volatile accesses. |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1721 | Constant *Ptr = getVal(Values, SI->getOperand(1)); |
| 1722 | if (!isSimpleEnoughPointerToCommit(Ptr)) |
| 1723 | // If this is too complex for us to commit, reject it. |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1724 | return false; |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1725 | Constant *Val = getVal(Values, SI->getOperand(0)); |
| 1726 | MutatedMemory[Ptr] = Val; |
| 1727 | } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) { |
| 1728 | InstResult = ConstantExpr::get(BO->getOpcode(), |
| 1729 | getVal(Values, BO->getOperand(0)), |
| 1730 | getVal(Values, BO->getOperand(1))); |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1731 | } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) { |
| 1732 | InstResult = ConstantExpr::getCompare(CI->getPredicate(), |
| 1733 | getVal(Values, CI->getOperand(0)), |
| 1734 | getVal(Values, CI->getOperand(1))); |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1735 | } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) { |
Chris Lattner | 9a989f0 | 2006-11-30 17:26:08 +0000 | [diff] [blame] | 1736 | InstResult = ConstantExpr::getCast(CI->getOpcode(), |
| 1737 | getVal(Values, CI->getOperand(0)), |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1738 | CI->getType()); |
| 1739 | } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) { |
| 1740 | InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)), |
| 1741 | getVal(Values, SI->getOperand(1)), |
| 1742 | getVal(Values, SI->getOperand(2))); |
Chris Lattner | 04de1cf | 2005-09-26 05:15:37 +0000 | [diff] [blame] | 1743 | } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) { |
| 1744 | Constant *P = getVal(Values, GEP->getOperand(0)); |
Chris Lattner | 55eb1c4 | 2007-01-31 04:40:53 +0000 | [diff] [blame] | 1745 | SmallVector<Constant*, 8> GEPOps; |
Chris Lattner | 04de1cf | 2005-09-26 05:15:37 +0000 | [diff] [blame] | 1746 | for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i) |
| 1747 | GEPOps.push_back(getVal(Values, GEP->getOperand(i))); |
Chris Lattner | 55eb1c4 | 2007-01-31 04:40:53 +0000 | [diff] [blame] | 1748 | InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size()); |
Chris Lattner | 04de1cf | 2005-09-26 05:15:37 +0000 | [diff] [blame] | 1749 | } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) { |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1750 | if (LI->isVolatile()) return false; // no volatile accesses. |
Chris Lattner | 04de1cf | 2005-09-26 05:15:37 +0000 | [diff] [blame] | 1751 | InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)), |
| 1752 | MutatedMemory); |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1753 | if (InstResult == 0) return false; // Could not evaluate load. |
Chris Lattner | a22fdb0 | 2005-09-26 17:07:09 +0000 | [diff] [blame] | 1754 | } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) { |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1755 | if (AI->isArrayAllocation()) return false; // Cannot handle array allocs. |
Chris Lattner | a22fdb0 | 2005-09-26 17:07:09 +0000 | [diff] [blame] | 1756 | const Type *Ty = AI->getType()->getElementType(); |
| 1757 | AllocaTmps.push_back(new GlobalVariable(Ty, false, |
| 1758 | GlobalValue::InternalLinkage, |
| 1759 | UndefValue::get(Ty), |
| 1760 | AI->getName())); |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1761 | InstResult = AllocaTmps.back(); |
| 1762 | } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) { |
Chris Lattner | 7cd580f | 2006-07-07 21:37:01 +0000 | [diff] [blame] | 1763 | // Cannot handle inline asm. |
| 1764 | if (isa<InlineAsm>(CI->getOperand(0))) return false; |
| 1765 | |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1766 | // Resolve function pointers. |
| 1767 | Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0))); |
| 1768 | if (!Callee) return false; // Cannot resolve. |
Chris Lattner | a9ec8ab | 2005-09-27 05:02:43 +0000 | [diff] [blame] | 1769 | |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1770 | std::vector<Constant*> Formals; |
| 1771 | for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i) |
| 1772 | Formals.push_back(getVal(Values, CI->getOperand(i))); |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1773 | |
Reid Spencer | 5cbf985 | 2007-01-30 20:08:39 +0000 | [diff] [blame] | 1774 | if (Callee->isDeclaration()) { |
Chris Lattner | a9ec8ab | 2005-09-27 05:02:43 +0000 | [diff] [blame] | 1775 | // If this is a function we can constant fold, do it. |
Chris Lattner | 6c1f565 | 2007-01-30 23:14:52 +0000 | [diff] [blame] | 1776 | if (Constant *C = ConstantFoldCall(Callee, &Formals[0], |
| 1777 | Formals.size())) { |
Chris Lattner | a9ec8ab | 2005-09-27 05:02:43 +0000 | [diff] [blame] | 1778 | InstResult = C; |
| 1779 | } else { |
| 1780 | return false; |
| 1781 | } |
| 1782 | } else { |
| 1783 | if (Callee->getFunctionType()->isVarArg()) |
| 1784 | return false; |
| 1785 | |
| 1786 | Constant *RetVal; |
| 1787 | |
| 1788 | // Execute the call, if successful, use the return value. |
| 1789 | if (!EvaluateFunction(Callee, RetVal, Formals, CallStack, |
| 1790 | MutatedMemory, AllocaTmps)) |
| 1791 | return false; |
| 1792 | InstResult = RetVal; |
| 1793 | } |
Reid Spencer | 3ed469c | 2006-11-02 20:25:50 +0000 | [diff] [blame] | 1794 | } else if (isa<TerminatorInst>(CurInst)) { |
Chris Lattner | cdf98be | 2005-09-26 04:57:38 +0000 | [diff] [blame] | 1795 | BasicBlock *NewBB = 0; |
| 1796 | if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) { |
| 1797 | if (BI->isUnconditional()) { |
| 1798 | NewBB = BI->getSuccessor(0); |
| 1799 | } else { |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1800 | ConstantInt *Cond = |
| 1801 | dyn_cast<ConstantInt>(getVal(Values, BI->getCondition())); |
Chris Lattner | 97d1fad | 2007-01-12 18:30:11 +0000 | [diff] [blame] | 1802 | if (!Cond) return false; // Cannot determine. |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 1803 | |
Reid Spencer | 579dca1 | 2007-01-12 04:24:46 +0000 | [diff] [blame] | 1804 | NewBB = BI->getSuccessor(!Cond->getZExtValue()); |
Chris Lattner | cdf98be | 2005-09-26 04:57:38 +0000 | [diff] [blame] | 1805 | } |
| 1806 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) { |
| 1807 | ConstantInt *Val = |
| 1808 | dyn_cast<ConstantInt>(getVal(Values, SI->getCondition())); |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1809 | if (!Val) return false; // Cannot determine. |
Chris Lattner | cdf98be | 2005-09-26 04:57:38 +0000 | [diff] [blame] | 1810 | NewBB = SI->getSuccessor(SI->findCaseValue(Val)); |
| 1811 | } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) { |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1812 | if (RI->getNumOperands()) |
| 1813 | RetVal = getVal(Values, RI->getOperand(0)); |
| 1814 | |
| 1815 | CallStack.pop_back(); // return from fn. |
Chris Lattner | 8a7cc6e | 2005-09-27 04:27:01 +0000 | [diff] [blame] | 1816 | return true; // We succeeded at evaluating this ctor! |
Chris Lattner | cdf98be | 2005-09-26 04:57:38 +0000 | [diff] [blame] | 1817 | } else { |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1818 | // invoke, unwind, unreachable. |
| 1819 | return false; // Cannot handle this terminator. |
Chris Lattner | cdf98be | 2005-09-26 04:57:38 +0000 | [diff] [blame] | 1820 | } |
| 1821 | |
| 1822 | // Okay, we succeeded in evaluating this control flow. See if we have |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1823 | // executed the new block before. If so, we have a looping function, |
| 1824 | // which we cannot evaluate in reasonable time. |
Chris Lattner | cdf98be | 2005-09-26 04:57:38 +0000 | [diff] [blame] | 1825 | if (!ExecutedBlocks.insert(NewBB).second) |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1826 | return false; // looped! |
Chris Lattner | cdf98be | 2005-09-26 04:57:38 +0000 | [diff] [blame] | 1827 | |
| 1828 | // Okay, we have never been in this block before. Check to see if there |
| 1829 | // are any PHI nodes. If so, evaluate them with information about where |
| 1830 | // we came from. |
| 1831 | BasicBlock *OldBB = CurInst->getParent(); |
| 1832 | CurInst = NewBB->begin(); |
| 1833 | PHINode *PN; |
| 1834 | for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst) |
| 1835 | Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB)); |
| 1836 | |
| 1837 | // Do NOT increment CurInst. We know that the terminator had no value. |
| 1838 | continue; |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1839 | } else { |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1840 | // Did not know how to evaluate this! |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1841 | return false; |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1842 | } |
| 1843 | |
| 1844 | if (!CurInst->use_empty()) |
| 1845 | Values[CurInst] = InstResult; |
| 1846 | |
| 1847 | // Advance program counter. |
| 1848 | ++CurInst; |
| 1849 | } |
Chris Lattner | 8a7cc6e | 2005-09-27 04:27:01 +0000 | [diff] [blame] | 1850 | } |
| 1851 | |
| 1852 | /// EvaluateStaticConstructor - Evaluate static constructors in the function, if |
| 1853 | /// we can. Return true if we can, false otherwise. |
| 1854 | static bool EvaluateStaticConstructor(Function *F) { |
| 1855 | /// MutatedMemory - For each store we execute, we update this map. Loads |
| 1856 | /// check this to get the most up-to-date value. If evaluation is successful, |
| 1857 | /// this state is committed to the process. |
| 1858 | std::map<Constant*, Constant*> MutatedMemory; |
| 1859 | |
| 1860 | /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable |
| 1861 | /// to represent its body. This vector is needed so we can delete the |
| 1862 | /// temporary globals when we are done. |
| 1863 | std::vector<GlobalVariable*> AllocaTmps; |
| 1864 | |
| 1865 | /// CallStack - This is used to detect recursion. In pathological situations |
| 1866 | /// we could hit exponential behavior, but at least there is nothing |
| 1867 | /// unbounded. |
| 1868 | std::vector<Function*> CallStack; |
| 1869 | |
| 1870 | // Call the function. |
Chris Lattner | cd27142 | 2005-09-27 04:45:34 +0000 | [diff] [blame] | 1871 | Constant *RetValDummy; |
| 1872 | bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(), |
| 1873 | CallStack, MutatedMemory, AllocaTmps); |
Chris Lattner | 8a7cc6e | 2005-09-27 04:27:01 +0000 | [diff] [blame] | 1874 | if (EvalSuccess) { |
Chris Lattner | a22fdb0 | 2005-09-26 17:07:09 +0000 | [diff] [blame] | 1875 | // We succeeded at evaluation: commit the result. |
Bill Wendling | 0a81aac | 2006-11-26 10:02:32 +0000 | [diff] [blame] | 1876 | DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '" |
| 1877 | << F->getName() << "' to " << MutatedMemory.size() |
| 1878 | << " stores.\n"; |
Chris Lattner | a22fdb0 | 2005-09-26 17:07:09 +0000 | [diff] [blame] | 1879 | for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(), |
| 1880 | E = MutatedMemory.end(); I != E; ++I) |
| 1881 | CommitValueTo(I->second, I->first); |
| 1882 | } |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1883 | |
Chris Lattner | a22fdb0 | 2005-09-26 17:07:09 +0000 | [diff] [blame] | 1884 | // At this point, we are done interpreting. If we created any 'alloca' |
| 1885 | // temporaries, release them now. |
| 1886 | while (!AllocaTmps.empty()) { |
| 1887 | GlobalVariable *Tmp = AllocaTmps.back(); |
| 1888 | AllocaTmps.pop_back(); |
Chris Lattner | 8a7cc6e | 2005-09-27 04:27:01 +0000 | [diff] [blame] | 1889 | |
Chris Lattner | a22fdb0 | 2005-09-26 17:07:09 +0000 | [diff] [blame] | 1890 | // If there are still users of the alloca, the program is doing something |
| 1891 | // silly, e.g. storing the address of the alloca somewhere and using it |
| 1892 | // later. Since this is undefined, we'll just make it be null. |
| 1893 | if (!Tmp->use_empty()) |
| 1894 | Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType())); |
| 1895 | delete Tmp; |
| 1896 | } |
Chris Lattner | aae4a1c | 2005-09-26 07:34:35 +0000 | [diff] [blame] | 1897 | |
Chris Lattner | 8a7cc6e | 2005-09-27 04:27:01 +0000 | [diff] [blame] | 1898 | return EvalSuccess; |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1899 | } |
| 1900 | |
Chris Lattner | db973e6 | 2005-09-26 02:31:18 +0000 | [diff] [blame] | 1901 | |
Chris Lattner | 8a7cc6e | 2005-09-27 04:27:01 +0000 | [diff] [blame] | 1902 | |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 1903 | /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible. |
| 1904 | /// Return true if anything changed. |
| 1905 | bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) { |
| 1906 | std::vector<Function*> Ctors = ParseGlobalCtors(GCL); |
| 1907 | bool MadeChange = false; |
| 1908 | if (Ctors.empty()) return false; |
| 1909 | |
| 1910 | // Loop over global ctors, optimizing them when we can. |
| 1911 | for (unsigned i = 0; i != Ctors.size(); ++i) { |
| 1912 | Function *F = Ctors[i]; |
| 1913 | // Found a null terminator in the middle of the list, prune off the rest of |
| 1914 | // the list. |
Chris Lattner | 7d8e58f | 2005-09-26 02:19:27 +0000 | [diff] [blame] | 1915 | if (F == 0) { |
| 1916 | if (i != Ctors.size()-1) { |
| 1917 | Ctors.resize(i+1); |
| 1918 | MadeChange = true; |
| 1919 | } |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 1920 | break; |
| 1921 | } |
| 1922 | |
Chris Lattner | 79c1101 | 2005-09-26 04:44:35 +0000 | [diff] [blame] | 1923 | // We cannot simplify external ctor functions. |
| 1924 | if (F->empty()) continue; |
| 1925 | |
| 1926 | // If we can evaluate the ctor at compile time, do. |
| 1927 | if (EvaluateStaticConstructor(F)) { |
| 1928 | Ctors.erase(Ctors.begin()+i); |
| 1929 | MadeChange = true; |
| 1930 | --i; |
| 1931 | ++NumCtorsEvaluated; |
| 1932 | continue; |
| 1933 | } |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 1934 | } |
| 1935 | |
| 1936 | if (!MadeChange) return false; |
| 1937 | |
Chris Lattner | db973e6 | 2005-09-26 02:31:18 +0000 | [diff] [blame] | 1938 | GCL = InstallGlobalCtors(GCL, Ctors); |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 1939 | return true; |
| 1940 | } |
| 1941 | |
| 1942 | |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 1943 | bool GlobalOpt::runOnModule(Module &M) { |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 1944 | bool Changed = false; |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 1945 | |
| 1946 | // Try to find the llvm.globalctors list. |
| 1947 | GlobalVariable *GlobalCtors = FindGlobalCtors(M); |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 1948 | |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 1949 | bool LocalChange = true; |
| 1950 | while (LocalChange) { |
| 1951 | LocalChange = false; |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 1952 | |
| 1953 | // Delete functions that are trivially dead, ccc -> fastcc |
| 1954 | LocalChange |= OptimizeFunctions(M); |
| 1955 | |
| 1956 | // Optimize global_ctors list. |
| 1957 | if (GlobalCtors) |
| 1958 | LocalChange |= OptimizeGlobalCtorsList(GlobalCtors); |
| 1959 | |
| 1960 | // Optimize non-address-taken globals. |
| 1961 | LocalChange |= OptimizeGlobalVars(M); |
Chris Lattner | 7a90b68 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 1962 | Changed |= LocalChange; |
| 1963 | } |
Chris Lattner | b1ab458 | 2005-09-26 01:43:45 +0000 | [diff] [blame] | 1964 | |
| 1965 | // TODO: Move all global ctors functions to the end of the module for code |
| 1966 | // layout. |
| 1967 | |
Chris Lattner | 079236d | 2004-02-25 21:34:36 +0000 | [diff] [blame] | 1968 | return Changed; |
| 1969 | } |