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