Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 1 | //===- ConstantHoisting.cpp - Prepare code for expensive constants --------===// |
| 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This pass identifies expensive constants to hoist and coalesces them to |
| 10 | // better prepare it for SelectionDAG-based code generation. This works around |
| 11 | // the limitations of the basic-block-at-a-time approach. |
| 12 | // |
| 13 | // First it scans all instructions for integer constants and calculates its |
| 14 | // cost. If the constant can be folded into the instruction (the cost is |
| 15 | // TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't |
| 16 | // consider it expensive and leave it alone. This is the default behavior and |
| 17 | // the default implementation of getIntImmCost will always return TCC_Free. |
| 18 | // |
| 19 | // If the cost is more than TCC_BASIC, then the integer constant can't be folded |
| 20 | // into the instruction and it might be beneficial to hoist the constant. |
| 21 | // Similar constants are coalesced to reduce register pressure and |
| 22 | // materialization code. |
| 23 | // |
| 24 | // When a constant is hoisted, it is also hidden behind a bitcast to force it to |
| 25 | // be live-out of the basic block. Otherwise the constant would be just |
| 26 | // duplicated and each basic block would have its own copy in the SelectionDAG. |
| 27 | // The SelectionDAG recognizes such constants as opaque and doesn't perform |
| 28 | // certain transformations on them, which would create a new expensive constant. |
| 29 | // |
| 30 | // This optimization is only applied to integer constants in instructions and |
Juergen Ributzka | f0dff49 | 2014-03-21 06:04:45 +0000 | [diff] [blame] | 31 | // simple (this means not nested) constant cast expressions. For example: |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 32 | // %0 = load i64* inttoptr (i64 big_constant to i64*) |
| 33 | //===----------------------------------------------------------------------===// |
| 34 | |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 35 | #include "llvm/Transforms/Scalar/ConstantHoisting.h" |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 36 | #include "llvm/ADT/APInt.h" |
| 37 | #include "llvm/ADT/DenseMap.h" |
| 38 | #include "llvm/ADT/None.h" |
| 39 | #include "llvm/ADT/Optional.h" |
| 40 | #include "llvm/ADT/SmallPtrSet.h" |
Juergen Ributzka | a29a5b8 | 2014-03-21 06:04:30 +0000 | [diff] [blame] | 41 | #include "llvm/ADT/SmallVector.h" |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 42 | #include "llvm/ADT/Statistic.h" |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 43 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 44 | #include "llvm/Analysis/TargetTransformInfo.h" |
David Blaikie | 31b98d2 | 2018-06-04 21:23:21 +0000 | [diff] [blame] | 45 | #include "llvm/Transforms/Utils/Local.h" |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 46 | #include "llvm/IR/BasicBlock.h" |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 47 | #include "llvm/IR/Constants.h" |
David Blaikie | 2be3922 | 2018-03-21 22:34:23 +0000 | [diff] [blame] | 48 | #include "llvm/IR/DebugInfoMetadata.h" |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 49 | #include "llvm/IR/Dominators.h" |
| 50 | #include "llvm/IR/Function.h" |
| 51 | #include "llvm/IR/InstrTypes.h" |
| 52 | #include "llvm/IR/Instruction.h" |
| 53 | #include "llvm/IR/Instructions.h" |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 54 | #include "llvm/IR/IntrinsicInst.h" |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 55 | #include "llvm/IR/Value.h" |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 56 | #include "llvm/Pass.h" |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 57 | #include "llvm/Support/BlockFrequency.h" |
| 58 | #include "llvm/Support/Casting.h" |
| 59 | #include "llvm/Support/CommandLine.h" |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 60 | #include "llvm/Support/Debug.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 61 | #include "llvm/Support/raw_ostream.h" |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 62 | #include "llvm/Transforms/Scalar.h" |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 63 | #include <algorithm> |
| 64 | #include <cassert> |
| 65 | #include <cstdint> |
| 66 | #include <iterator> |
NAKAMURA Takumi | 99aa6e1 | 2014-04-30 06:44:50 +0000 | [diff] [blame] | 67 | #include <tuple> |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 68 | #include <utility> |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 69 | |
| 70 | using namespace llvm; |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 71 | using namespace consthoist; |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 72 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 73 | #define DEBUG_TYPE "consthoist" |
| 74 | |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 75 | STATISTIC(NumConstantsHoisted, "Number of constants hoisted"); |
| 76 | STATISTIC(NumConstantsRebased, "Number of constants rebased"); |
| 77 | |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 78 | static cl::opt<bool> ConstHoistWithBlockFrequency( |
Wei Mi | 7586755 | 2017-07-07 00:11:05 +0000 | [diff] [blame] | 79 | "consthoist-with-block-frequency", cl::init(true), cl::Hidden, |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 80 | cl::desc("Enable the use of the block frequency analysis to reduce the " |
| 81 | "chance to execute const materialization more frequently than " |
| 82 | "without hoisting.")); |
| 83 | |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 84 | static cl::opt<bool> ConstHoistGEP( |
| 85 | "consthoist-gep", cl::init(false), cl::Hidden, |
| 86 | cl::desc("Try hoisting constant gep expressions")); |
| 87 | |
Zhaoshi Zheng | 9571033 | 2018-09-26 00:59:09 +0000 | [diff] [blame] | 88 | static cl::opt<unsigned> |
| 89 | MinNumOfDependentToRebase("consthoist-min-num-to-rebase", |
| 90 | cl::desc("Do not rebase if number of dependent constants of a Base is less " |
| 91 | "than this number."), |
| 92 | cl::init(0), cl::Hidden); |
| 93 | |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 94 | namespace { |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 95 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 96 | /// The constant hoisting pass. |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 97 | class ConstantHoistingLegacyPass : public FunctionPass { |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 98 | public: |
| 99 | static char ID; // Pass identification, replacement for typeid |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 100 | |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 101 | ConstantHoistingLegacyPass() : FunctionPass(ID) { |
| 102 | initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry()); |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 103 | } |
| 104 | |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 105 | bool runOnFunction(Function &Fn) override; |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 106 | |
Mehdi Amini | 117296c | 2016-10-01 02:56:57 +0000 | [diff] [blame] | 107 | StringRef getPassName() const override { return "Constant Hoisting"; } |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 108 | |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 109 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 110 | AU.setPreservesCFG(); |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 111 | if (ConstHoistWithBlockFrequency) |
| 112 | AU.addRequired<BlockFrequencyInfoWrapperPass>(); |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 113 | AU.addRequired<DominatorTreeWrapperPass>(); |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 114 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 115 | } |
| 116 | |
| 117 | private: |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 118 | ConstantHoistingPass Impl; |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 119 | }; |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 120 | |
| 121 | } // end anonymous namespace |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 122 | |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 123 | char ConstantHoistingLegacyPass::ID = 0; |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 124 | |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 125 | INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist", |
| 126 | "Constant Hoisting", false, false) |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 127 | INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 128 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 129 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 130 | INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist", |
| 131 | "Constant Hoisting", false, false) |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 132 | |
| 133 | FunctionPass *llvm::createConstantHoistingPass() { |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 134 | return new ConstantHoistingLegacyPass(); |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 135 | } |
| 136 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 137 | /// Perform the constant hoisting optimization for the given function. |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 138 | bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 139 | if (skipFunction(Fn)) |
Andrea Di Biagio | f5443238 | 2015-02-14 15:11:48 +0000 | [diff] [blame] | 140 | return false; |
| 141 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 142 | LLVM_DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n"); |
| 143 | LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n'); |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 144 | |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 145 | bool MadeChange = |
| 146 | Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn), |
| 147 | getAnalysis<DominatorTreeWrapperPass>().getDomTree(), |
| 148 | ConstHoistWithBlockFrequency |
| 149 | ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI() |
| 150 | : nullptr, |
| 151 | Fn.getEntryBlock()); |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 152 | |
| 153 | if (MadeChange) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 154 | LLVM_DEBUG(dbgs() << "********** Function after Constant Hoisting: " |
| 155 | << Fn.getName() << '\n'); |
| 156 | LLVM_DEBUG(dbgs() << Fn); |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 157 | } |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 158 | LLVM_DEBUG(dbgs() << "********** End Constant Hoisting **********\n"); |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 159 | |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 160 | return MadeChange; |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 161 | } |
| 162 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 163 | /// Find the constant materialization insertion point. |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 164 | Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst, |
| 165 | unsigned Idx) const { |
Juergen Ributzka | 575bcb7 | 2014-04-22 18:06:58 +0000 | [diff] [blame] | 166 | // If the operand is a cast instruction, then we have to materialize the |
| 167 | // constant before the cast instruction. |
| 168 | if (Idx != ~0U) { |
| 169 | Value *Opnd = Inst->getOperand(Idx); |
| 170 | if (auto CastInst = dyn_cast<Instruction>(Opnd)) |
| 171 | if (CastInst->isCast()) |
| 172 | return CastInst; |
| 173 | } |
| 174 | |
| 175 | // The simple and common case. This also includes constant expressions. |
David Majnemer | ba275f9 | 2015-08-19 19:54:02 +0000 | [diff] [blame] | 176 | if (!isa<PHINode>(Inst) && !Inst->isEHPad()) |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 177 | return Inst; |
| 178 | |
David Majnemer | ba275f9 | 2015-08-19 19:54:02 +0000 | [diff] [blame] | 179 | // We can't insert directly before a phi node or an eh pad. Insert before |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 180 | // the terminator of the incoming or dominating block. |
| 181 | assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!"); |
| 182 | if (Idx != ~0U && isa<PHINode>(Inst)) |
| 183 | return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator(); |
| 184 | |
Reid Kleckner | d80b69f | 2017-03-01 22:41:12 +0000 | [diff] [blame] | 185 | // This must be an EH pad. Iterate over immediate dominators until we find a |
| 186 | // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads |
| 187 | // and terminators. |
| 188 | auto IDom = DT->getNode(Inst->getParent())->getIDom(); |
| 189 | while (IDom->getBlock()->isEHPad()) { |
| 190 | assert(Entry != IDom->getBlock() && "eh pad in entry block"); |
| 191 | IDom = IDom->getIDom(); |
| 192 | } |
| 193 | |
| 194 | return IDom->getBlock()->getTerminator(); |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 195 | } |
| 196 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 197 | /// Given \p BBs as input, find another set of BBs which collectively |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 198 | /// dominates \p BBs and have the minimal sum of frequencies. Return the BB |
| 199 | /// set found in \p BBs. |
Benjamin Kramer | debb3c3 | 2017-05-26 20:09:00 +0000 | [diff] [blame] | 200 | static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI, |
| 201 | BasicBlock *Entry, |
| 202 | SmallPtrSet<BasicBlock *, 8> &BBs) { |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 203 | assert(!BBs.count(Entry) && "Assume Entry is not in BBs"); |
| 204 | // Nodes on the current path to the root. |
| 205 | SmallPtrSet<BasicBlock *, 8> Path; |
| 206 | // Candidates includes any block 'BB' in set 'BBs' that is not strictly |
| 207 | // dominated by any other blocks in set 'BBs', and all nodes in the path |
| 208 | // in the dominator tree from Entry to 'BB'. |
| 209 | SmallPtrSet<BasicBlock *, 16> Candidates; |
| 210 | for (auto BB : BBs) { |
| 211 | Path.clear(); |
| 212 | // Walk up the dominator tree until Entry or another BB in BBs |
| 213 | // is reached. Insert the nodes on the way to the Path. |
| 214 | BasicBlock *Node = BB; |
| 215 | // The "Path" is a candidate path to be added into Candidates set. |
| 216 | bool isCandidate = false; |
| 217 | do { |
| 218 | Path.insert(Node); |
| 219 | if (Node == Entry || Candidates.count(Node)) { |
| 220 | isCandidate = true; |
| 221 | break; |
| 222 | } |
| 223 | assert(DT.getNode(Node)->getIDom() && |
| 224 | "Entry doens't dominate current Node"); |
| 225 | Node = DT.getNode(Node)->getIDom()->getBlock(); |
| 226 | } while (!BBs.count(Node)); |
| 227 | |
| 228 | // If isCandidate is false, Node is another Block in BBs dominating |
| 229 | // current 'BB'. Drop the nodes on the Path. |
| 230 | if (!isCandidate) |
| 231 | continue; |
| 232 | |
| 233 | // Add nodes on the Path into Candidates. |
| 234 | Candidates.insert(Path.begin(), Path.end()); |
| 235 | } |
| 236 | |
| 237 | // Sort the nodes in Candidates in top-down order and save the nodes |
| 238 | // in Orders. |
| 239 | unsigned Idx = 0; |
| 240 | SmallVector<BasicBlock *, 16> Orders; |
| 241 | Orders.push_back(Entry); |
| 242 | while (Idx != Orders.size()) { |
| 243 | BasicBlock *Node = Orders[Idx++]; |
| 244 | for (auto ChildDomNode : DT.getNode(Node)->getChildren()) { |
| 245 | if (Candidates.count(ChildDomNode->getBlock())) |
| 246 | Orders.push_back(ChildDomNode->getBlock()); |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | // Visit Orders in bottom-up order. |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 251 | using InsertPtsCostPair = |
| 252 | std::pair<SmallPtrSet<BasicBlock *, 16>, BlockFrequency>; |
| 253 | |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 254 | // InsertPtsMap is a map from a BB to the best insertion points for the |
| 255 | // subtree of BB (subtree not including the BB itself). |
| 256 | DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap; |
| 257 | InsertPtsMap.reserve(Orders.size() + 1); |
| 258 | for (auto RIt = Orders.rbegin(); RIt != Orders.rend(); RIt++) { |
| 259 | BasicBlock *Node = *RIt; |
| 260 | bool NodeInBBs = BBs.count(Node); |
| 261 | SmallPtrSet<BasicBlock *, 16> &InsertPts = InsertPtsMap[Node].first; |
| 262 | BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second; |
| 263 | |
| 264 | // Return the optimal insert points in BBs. |
| 265 | if (Node == Entry) { |
| 266 | BBs.clear(); |
Wei Mi | 20526b2 | 2017-07-06 22:32:27 +0000 | [diff] [blame] | 267 | if (InsertPtsFreq > BFI.getBlockFreq(Node) || |
| 268 | (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)) |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 269 | BBs.insert(Entry); |
| 270 | else |
| 271 | BBs.insert(InsertPts.begin(), InsertPts.end()); |
| 272 | break; |
| 273 | } |
| 274 | |
| 275 | BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock(); |
| 276 | // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child |
| 277 | // will update its parent's ParentInsertPts and ParentPtsFreq. |
| 278 | SmallPtrSet<BasicBlock *, 16> &ParentInsertPts = InsertPtsMap[Parent].first; |
| 279 | BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second; |
| 280 | // Choose to insert in Node or in subtree of Node. |
Wei Mi | 20526b2 | 2017-07-06 22:32:27 +0000 | [diff] [blame] | 281 | // Don't hoist to EHPad because we may not find a proper place to insert |
| 282 | // in EHPad. |
| 283 | // If the total frequency of InsertPts is the same as the frequency of the |
| 284 | // target Node, and InsertPts contains more than one nodes, choose hoisting |
| 285 | // to reduce code size. |
| 286 | if (NodeInBBs || |
| 287 | (!Node->isEHPad() && |
| 288 | (InsertPtsFreq > BFI.getBlockFreq(Node) || |
| 289 | (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) { |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 290 | ParentInsertPts.insert(Node); |
| 291 | ParentPtsFreq += BFI.getBlockFreq(Node); |
| 292 | } else { |
| 293 | ParentInsertPts.insert(InsertPts.begin(), InsertPts.end()); |
| 294 | ParentPtsFreq += InsertPtsFreq; |
| 295 | } |
| 296 | } |
| 297 | } |
| 298 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 299 | /// Find an insertion point that dominates all uses. |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 300 | SmallPtrSet<Instruction *, 8> ConstantHoistingPass::findConstantInsertionPoint( |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 301 | const ConstantInfo &ConstInfo) const { |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 302 | assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry."); |
Juergen Ributzka | c81000b | 2014-04-03 01:38:47 +0000 | [diff] [blame] | 303 | // Collect all basic blocks. |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 304 | SmallPtrSet<BasicBlock *, 8> BBs; |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 305 | SmallPtrSet<Instruction *, 8> InsertPts; |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 306 | for (auto const &RCI : ConstInfo.RebasedConstants) |
Juergen Ributzka | c81000b | 2014-04-03 01:38:47 +0000 | [diff] [blame] | 307 | for (auto const &U : RCI.Uses) |
Juergen Ributzka | 575bcb7 | 2014-04-22 18:06:58 +0000 | [diff] [blame] | 308 | BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent()); |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 309 | |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 310 | if (BBs.count(Entry)) { |
| 311 | InsertPts.insert(&Entry->front()); |
| 312 | return InsertPts; |
| 313 | } |
| 314 | |
| 315 | if (BFI) { |
| 316 | findBestInsertionSet(*DT, *BFI, Entry, BBs); |
| 317 | for (auto BB : BBs) { |
| 318 | BasicBlock::iterator InsertPt = BB->begin(); |
| 319 | for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt) |
| 320 | ; |
| 321 | InsertPts.insert(&*InsertPt); |
| 322 | } |
| 323 | return InsertPts; |
| 324 | } |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 325 | |
| 326 | while (BBs.size() >= 2) { |
| 327 | BasicBlock *BB, *BB1, *BB2; |
| 328 | BB1 = *BBs.begin(); |
| 329 | BB2 = *std::next(BBs.begin()); |
| 330 | BB = DT->findNearestCommonDominator(BB1, BB2); |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 331 | if (BB == Entry) { |
| 332 | InsertPts.insert(&Entry->front()); |
| 333 | return InsertPts; |
| 334 | } |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 335 | BBs.erase(BB1); |
| 336 | BBs.erase(BB2); |
| 337 | BBs.insert(BB); |
| 338 | } |
| 339 | assert((BBs.size() == 1) && "Expected only one element."); |
| 340 | Instruction &FirstInst = (*BBs.begin())->front(); |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 341 | InsertPts.insert(findMatInsertPt(&FirstInst)); |
| 342 | return InsertPts; |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 343 | } |
| 344 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 345 | /// Record constant integer ConstInt for instruction Inst at operand |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 346 | /// index Idx. |
| 347 | /// |
Juergen Ributzka | f0dff49 | 2014-03-21 06:04:45 +0000 | [diff] [blame] | 348 | /// The operand at index Idx is not necessarily the constant integer itself. It |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 349 | /// could also be a cast instruction or a constant expression that uses the |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 350 | /// constant integer. |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 351 | void ConstantHoistingPass::collectConstantCandidates( |
| 352 | ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx, |
| 353 | ConstantInt *ConstInt) { |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 354 | unsigned Cost; |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 355 | // Ask the target about the cost of materializing the constant for the given |
Juergen Ributzka | f0dff49 | 2014-03-21 06:04:45 +0000 | [diff] [blame] | 356 | // instruction and operand index. |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 357 | if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst)) |
Juergen Ributzka | f0dff49 | 2014-03-21 06:04:45 +0000 | [diff] [blame] | 358 | Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx, |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 359 | ConstInt->getValue(), ConstInt->getType()); |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 360 | else |
Juergen Ributzka | f0dff49 | 2014-03-21 06:04:45 +0000 | [diff] [blame] | 361 | Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(), |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 362 | ConstInt->getType()); |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 363 | |
Juergen Ributzka | a29a5b8 | 2014-03-21 06:04:30 +0000 | [diff] [blame] | 364 | // Ignore cheap integer constants. |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 365 | if (Cost > TargetTransformInfo::TCC_Basic) { |
Juergen Ributzka | a29a5b8 | 2014-03-21 06:04:30 +0000 | [diff] [blame] | 366 | ConstCandMapType::iterator Itr; |
| 367 | bool Inserted; |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 368 | ConstPtrUnionType Cand = ConstInt; |
| 369 | std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0)); |
Juergen Ributzka | a29a5b8 | 2014-03-21 06:04:30 +0000 | [diff] [blame] | 370 | if (Inserted) { |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 371 | ConstIntCandVec.push_back(ConstantCandidate(ConstInt)); |
| 372 | Itr->second = ConstIntCandVec.size() - 1; |
Juergen Ributzka | a29a5b8 | 2014-03-21 06:04:30 +0000 | [diff] [blame] | 373 | } |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 374 | ConstIntCandVec[Itr->second].addUser(Inst, Idx, Cost); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 375 | LLVM_DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx))) dbgs() |
| 376 | << "Collect constant " << *ConstInt << " from " << *Inst |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 377 | << " with cost " << Cost << '\n'; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 378 | else dbgs() << "Collect constant " << *ConstInt |
| 379 | << " indirectly from " << *Inst << " via " |
| 380 | << *Inst->getOperand(Idx) << " with cost " << Cost |
| 381 | << '\n';); |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 382 | } |
| 383 | } |
| 384 | |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 385 | /// Record constant GEP expression for instruction Inst at operand index Idx. |
| 386 | void ConstantHoistingPass::collectConstantCandidates( |
| 387 | ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx, |
| 388 | ConstantExpr *ConstExpr) { |
| 389 | // TODO: Handle vector GEPs |
| 390 | if (ConstExpr->getType()->isVectorTy()) |
| 391 | return; |
| 392 | |
| 393 | GlobalVariable *BaseGV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0)); |
| 394 | if (!BaseGV) |
| 395 | return; |
| 396 | |
| 397 | // Get offset from the base GV. |
| 398 | PointerType *GVPtrTy = dyn_cast<PointerType>(BaseGV->getType()); |
| 399 | IntegerType *PtrIntTy = DL->getIntPtrType(*Ctx, GVPtrTy->getAddressSpace()); |
| 400 | APInt Offset(DL->getTypeSizeInBits(PtrIntTy), /*val*/0, /*isSigned*/true); |
| 401 | auto *GEPO = cast<GEPOperator>(ConstExpr); |
| 402 | if (!GEPO->accumulateConstantOffset(*DL, Offset)) |
| 403 | return; |
| 404 | |
| 405 | if (!Offset.isIntN(32)) |
| 406 | return; |
| 407 | |
| 408 | // A constant GEP expression that has a GlobalVariable as base pointer is |
| 409 | // usually lowered to a load from constant pool. Such operation is unlikely |
| 410 | // to be cheaper than compute it by <Base + Offset>, which can be lowered to |
| 411 | // an ADD instruction or folded into Load/Store instruction. |
| 412 | int Cost = TTI->getIntImmCost(Instruction::Add, 1, Offset, PtrIntTy); |
| 413 | ConstCandVecType &ExprCandVec = ConstGEPCandMap[BaseGV]; |
| 414 | ConstCandMapType::iterator Itr; |
| 415 | bool Inserted; |
| 416 | ConstPtrUnionType Cand = ConstExpr; |
| 417 | std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0)); |
| 418 | if (Inserted) { |
| 419 | ExprCandVec.push_back(ConstantCandidate( |
| 420 | ConstantInt::get(Type::getInt32Ty(*Ctx), Offset.getLimitedValue()), |
| 421 | ConstExpr)); |
| 422 | Itr->second = ExprCandVec.size() - 1; |
| 423 | } |
| 424 | ExprCandVec[Itr->second].addUser(Inst, Idx, Cost); |
| 425 | } |
| 426 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 427 | /// Check the operand for instruction Inst at index Idx. |
Leo Li | 20fbad9 | 2017-06-29 17:03:34 +0000 | [diff] [blame] | 428 | void ConstantHoistingPass::collectConstantCandidates( |
| 429 | ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) { |
| 430 | Value *Opnd = Inst->getOperand(Idx); |
| 431 | |
| 432 | // Visit constant integers. |
| 433 | if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) { |
| 434 | collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt); |
| 435 | return; |
| 436 | } |
| 437 | |
| 438 | // Visit cast instructions that have constant integers. |
| 439 | if (auto CastInst = dyn_cast<Instruction>(Opnd)) { |
| 440 | // Only visit cast instructions, which have been skipped. All other |
| 441 | // instructions should have already been visited. |
| 442 | if (!CastInst->isCast()) |
| 443 | return; |
| 444 | |
| 445 | if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) { |
| 446 | // Pretend the constant is directly used by the instruction and ignore |
| 447 | // the cast instruction. |
| 448 | collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt); |
| 449 | return; |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | // Visit constant expressions that have constant integers. |
| 454 | if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) { |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 455 | // Handle constant gep expressions. |
| 456 | if (ConstHoistGEP && ConstExpr->isGEPWithNoNotionalOverIndexing()) |
| 457 | collectConstantCandidates(ConstCandMap, Inst, Idx, ConstExpr); |
| 458 | |
Leo Li | 20fbad9 | 2017-06-29 17:03:34 +0000 | [diff] [blame] | 459 | // Only visit constant cast expressions. |
| 460 | if (!ConstExpr->isCast()) |
| 461 | return; |
| 462 | |
| 463 | if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) { |
| 464 | // Pretend the constant is directly used by the instruction and ignore |
| 465 | // the constant expression. |
| 466 | collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt); |
| 467 | return; |
| 468 | } |
| 469 | } |
| 470 | } |
| 471 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 472 | /// Scan the instruction for expensive integer constants and record them |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 473 | /// in the constant candidate vector. |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 474 | void ConstantHoistingPass::collectConstantCandidates( |
| 475 | ConstCandMapType &ConstCandMap, Instruction *Inst) { |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 476 | // Skip all cast instructions. They are visited indirectly later on. |
| 477 | if (Inst->isCast()) |
| 478 | return; |
| 479 | |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 480 | // Scan all operands. |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 481 | for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) { |
Leo Li | 93abd7d | 2017-07-10 20:45:34 +0000 | [diff] [blame] | 482 | // The cost of materializing the constants (defined in |
| 483 | // `TargetTransformInfo::getIntImmCost`) for instructions which only take |
| 484 | // constant variables is lower than `TargetTransformInfo::TCC_Basic`. So |
| 485 | // it's safe for us to collect constant candidates from all IntrinsicInsts. |
| 486 | if (canReplaceOperandWithVariable(Inst, Idx) || isa<IntrinsicInst>(Inst)) { |
| 487 | collectConstantCandidates(ConstCandMap, Inst, Idx); |
| 488 | } |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 489 | } // end of for all operands |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 490 | } |
| 491 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 492 | /// Collect all integer constants in the function that cannot be folded |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 493 | /// into an instruction itself. |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 494 | void ConstantHoistingPass::collectConstantCandidates(Function &Fn) { |
Juergen Ributzka | 7be410f | 2014-03-25 21:21:10 +0000 | [diff] [blame] | 495 | ConstCandMapType ConstCandMap; |
Duncan P. N. Exon Smith | 3a9c9e3 | 2015-10-13 18:26:00 +0000 | [diff] [blame] | 496 | for (BasicBlock &BB : Fn) |
| 497 | for (Instruction &Inst : BB) |
| 498 | collectConstantCandidates(ConstCandMap, &Inst); |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 499 | } |
| 500 | |
Sjoerd Meijer | 38c2cd0 | 2016-07-14 07:44:20 +0000 | [diff] [blame] | 501 | // This helper function is necessary to deal with values that have different |
| 502 | // bit widths (APInt Operator- does not like that). If the value cannot be |
| 503 | // represented in uint64 we return an "empty" APInt. This is then interpreted |
| 504 | // as the value is not in range. |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 505 | static Optional<APInt> calculateOffsetDiff(const APInt &V1, const APInt &V2) { |
| 506 | Optional<APInt> Res = None; |
Sjoerd Meijer | 38c2cd0 | 2016-07-14 07:44:20 +0000 | [diff] [blame] | 507 | unsigned BW = V1.getBitWidth() > V2.getBitWidth() ? |
| 508 | V1.getBitWidth() : V2.getBitWidth(); |
| 509 | uint64_t LimVal1 = V1.getLimitedValue(); |
| 510 | uint64_t LimVal2 = V2.getLimitedValue(); |
| 511 | |
| 512 | if (LimVal1 == ~0ULL || LimVal2 == ~0ULL) |
| 513 | return Res; |
| 514 | |
| 515 | uint64_t Diff = LimVal1 - LimVal2; |
| 516 | return APInt(BW, Diff, true); |
| 517 | } |
| 518 | |
| 519 | // From a list of constants, one needs to picked as the base and the other |
| 520 | // constants will be transformed into an offset from that base constant. The |
| 521 | // question is which we can pick best? For example, consider these constants |
| 522 | // and their number of uses: |
| 523 | // |
| 524 | // Constants| 2 | 4 | 12 | 42 | |
| 525 | // NumUses | 3 | 2 | 8 | 7 | |
| 526 | // |
| 527 | // Selecting constant 12 because it has the most uses will generate negative |
| 528 | // offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative |
| 529 | // offsets lead to less optimal code generation, then there might be better |
| 530 | // solutions. Suppose immediates in the range of 0..35 are most optimally |
| 531 | // supported by the architecture, then selecting constant 2 is most optimal |
| 532 | // because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in |
| 533 | // range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would |
| 534 | // have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in |
| 535 | // selecting the base constant the range of the offsets is a very important |
| 536 | // factor too that we take into account here. This algorithm calculates a total |
| 537 | // costs for selecting a constant as the base and substract the costs if |
| 538 | // immediates are out of range. It has quadratic complexity, so we call this |
| 539 | // function only when we're optimising for size and there are less than 100 |
| 540 | // constants, we fall back to the straightforward algorithm otherwise |
| 541 | // which does not do all the offset calculations. |
| 542 | unsigned |
| 543 | ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S, |
| 544 | ConstCandVecType::iterator E, |
| 545 | ConstCandVecType::iterator &MaxCostItr) { |
| 546 | unsigned NumUses = 0; |
| 547 | |
| 548 | if(!Entry->getParent()->optForSize() || std::distance(S,E) > 100) { |
| 549 | for (auto ConstCand = S; ConstCand != E; ++ConstCand) { |
| 550 | NumUses += ConstCand->Uses.size(); |
| 551 | if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost) |
| 552 | MaxCostItr = ConstCand; |
| 553 | } |
| 554 | return NumUses; |
| 555 | } |
| 556 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 557 | LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n"); |
Sjoerd Meijer | 38c2cd0 | 2016-07-14 07:44:20 +0000 | [diff] [blame] | 558 | int MaxCost = -1; |
| 559 | for (auto ConstCand = S; ConstCand != E; ++ConstCand) { |
| 560 | auto Value = ConstCand->ConstInt->getValue(); |
| 561 | Type *Ty = ConstCand->ConstInt->getType(); |
| 562 | int Cost = 0; |
| 563 | NumUses += ConstCand->Uses.size(); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 564 | LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue() |
| 565 | << "\n"); |
Sjoerd Meijer | 38c2cd0 | 2016-07-14 07:44:20 +0000 | [diff] [blame] | 566 | |
| 567 | for (auto User : ConstCand->Uses) { |
| 568 | unsigned Opcode = User.Inst->getOpcode(); |
| 569 | unsigned OpndIdx = User.OpndIdx; |
| 570 | Cost += TTI->getIntImmCost(Opcode, OpndIdx, Value, Ty); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 571 | LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n"); |
Sjoerd Meijer | 38c2cd0 | 2016-07-14 07:44:20 +0000 | [diff] [blame] | 572 | |
| 573 | for (auto C2 = S; C2 != E; ++C2) { |
Eugene Zelenko | 8002c50 | 2017-09-13 21:43:53 +0000 | [diff] [blame] | 574 | Optional<APInt> Diff = calculateOffsetDiff( |
| 575 | C2->ConstInt->getValue(), |
| 576 | ConstCand->ConstInt->getValue()); |
Sjoerd Meijer | 38c2cd0 | 2016-07-14 07:44:20 +0000 | [diff] [blame] | 577 | if (Diff) { |
| 578 | const int ImmCosts = |
| 579 | TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty); |
| 580 | Cost -= ImmCosts; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 581 | LLVM_DEBUG(dbgs() << "Offset " << Diff.getValue() << " " |
| 582 | << "has penalty: " << ImmCosts << "\n" |
| 583 | << "Adjusted cost: " << Cost << "\n"); |
Sjoerd Meijer | 38c2cd0 | 2016-07-14 07:44:20 +0000 | [diff] [blame] | 584 | } |
| 585 | } |
| 586 | } |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 587 | LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n"); |
Sjoerd Meijer | 38c2cd0 | 2016-07-14 07:44:20 +0000 | [diff] [blame] | 588 | if (Cost > MaxCost) { |
| 589 | MaxCost = Cost; |
| 590 | MaxCostItr = ConstCand; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 591 | LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue() |
| 592 | << "\n"); |
Sjoerd Meijer | 38c2cd0 | 2016-07-14 07:44:20 +0000 | [diff] [blame] | 593 | } |
| 594 | } |
| 595 | return NumUses; |
| 596 | } |
| 597 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 598 | /// Find the base constant within the given range and rebase all other |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 599 | /// constants with respect to the base constant. |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 600 | void ConstantHoistingPass::findAndMakeBaseConstant( |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 601 | ConstCandVecType::iterator S, ConstCandVecType::iterator E, |
| 602 | SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec) { |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 603 | auto MaxCostItr = S; |
Sjoerd Meijer | 38c2cd0 | 2016-07-14 07:44:20 +0000 | [diff] [blame] | 604 | unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr); |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 605 | |
| 606 | // Don't hoist constants that have only one use. |
| 607 | if (NumUses <= 1) |
| 608 | return; |
| 609 | |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 610 | ConstantInt *ConstInt = MaxCostItr->ConstInt; |
| 611 | ConstantExpr *ConstExpr = MaxCostItr->ConstExpr; |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 612 | ConstantInfo ConstInfo; |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 613 | ConstInfo.BaseInt = ConstInt; |
| 614 | ConstInfo.BaseExpr = ConstExpr; |
| 615 | Type *Ty = ConstInt->getType(); |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 616 | |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 617 | // Rebase the constants with respect to the base constant. |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 618 | for (auto ConstCand = S; ConstCand != E; ++ConstCand) { |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 619 | APInt Diff = ConstCand->ConstInt->getValue() - ConstInt->getValue(); |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 620 | Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff); |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 621 | Type *ConstTy = |
| 622 | ConstCand->ConstExpr ? ConstCand->ConstExpr->getType() : nullptr; |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 623 | ConstInfo.RebasedConstants.push_back( |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 624 | RebasedConstantInfo(std::move(ConstCand->Uses), Offset, ConstTy)); |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 625 | } |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 626 | ConstInfoVec.push_back(std::move(ConstInfo)); |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 627 | } |
| 628 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 629 | /// Finds and combines constant candidates that can be easily |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 630 | /// rematerialized with an add from a common base constant. |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 631 | void ConstantHoistingPass::findBaseConstants(GlobalVariable *BaseGV) { |
| 632 | // If BaseGV is nullptr, find base among candidate constant integers; |
| 633 | // Otherwise find base among constant GEPs that share the same BaseGV. |
| 634 | ConstCandVecType &ConstCandVec = BaseGV ? |
| 635 | ConstGEPCandMap[BaseGV] : ConstIntCandVec; |
| 636 | ConstInfoVecType &ConstInfoVec = BaseGV ? |
| 637 | ConstGEPInfoMap[BaseGV] : ConstIntInfoVec; |
| 638 | |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 639 | // Sort the constants by value and type. This invalidates the mapping! |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 640 | std::stable_sort(ConstCandVec.begin(), ConstCandVec.end(), |
Mandeep Singh Grang | 636d94d | 2018-04-13 19:47:57 +0000 | [diff] [blame] | 641 | [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) { |
Juergen Ributzka | a29a5b8 | 2014-03-21 06:04:30 +0000 | [diff] [blame] | 642 | if (LHS.ConstInt->getType() != RHS.ConstInt->getType()) |
| 643 | return LHS.ConstInt->getType()->getBitWidth() < |
| 644 | RHS.ConstInt->getType()->getBitWidth(); |
| 645 | return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue()); |
Juergen Ributzka | 4635793 | 2014-03-20 20:17:13 +0000 | [diff] [blame] | 646 | }); |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 647 | |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 648 | // Simple linear scan through the sorted constant candidate vector for viable |
| 649 | // merge candidates. |
| 650 | auto MinValItr = ConstCandVec.begin(); |
| 651 | for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end(); |
| 652 | CC != E; ++CC) { |
| 653 | if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) { |
Zhaoshi Zheng | 35818e2 | 2018-08-28 23:00:59 +0000 | [diff] [blame] | 654 | Type *MemUseValTy = nullptr; |
| 655 | for (auto &U : CC->Uses) { |
| 656 | auto *UI = U.Inst; |
| 657 | if (LoadInst *LI = dyn_cast<LoadInst>(UI)) { |
| 658 | MemUseValTy = LI->getType(); |
| 659 | break; |
| 660 | } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) { |
| 661 | // Make sure the constant is used as pointer operand of the StoreInst. |
| 662 | if (SI->getPointerOperand() == SI->getOperand(U.OpndIdx)) { |
| 663 | MemUseValTy = SI->getValueOperand()->getType(); |
| 664 | break; |
| 665 | } |
| 666 | } |
| 667 | } |
| 668 | |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 669 | // Check if the constant is in range of an add with immediate. |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 670 | APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue(); |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 671 | if ((Diff.getBitWidth() <= 64) && |
Zhaoshi Zheng | 35818e2 | 2018-08-28 23:00:59 +0000 | [diff] [blame] | 672 | TTI->isLegalAddImmediate(Diff.getSExtValue()) && |
| 673 | // Check if Diff can be used as offset in addressing mode of the user |
| 674 | // memory instruction. |
| 675 | (!MemUseValTy || TTI->isLegalAddressingMode(MemUseValTy, |
| 676 | /*BaseGV*/nullptr, /*BaseOffset*/Diff.getSExtValue(), |
| 677 | /*HasBaseReg*/true, /*Scale*/0))) |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 678 | continue; |
| 679 | } |
| 680 | // We either have now a different constant type or the constant is not in |
| 681 | // range of an add with immediate anymore. |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 682 | findAndMakeBaseConstant(MinValItr, CC, ConstInfoVec); |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 683 | // Start a new base constant search. |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 684 | MinValItr = CC; |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 685 | } |
| 686 | // Finalize the last base constant search. |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 687 | findAndMakeBaseConstant(MinValItr, ConstCandVec.end(), ConstInfoVec); |
Juergen Ributzka | 4635793 | 2014-03-20 20:17:13 +0000 | [diff] [blame] | 688 | } |
| 689 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 690 | /// Updates the operand at Idx in instruction Inst with the result of |
Juergen Ributzka | e802d50 | 2014-03-22 01:49:27 +0000 | [diff] [blame] | 691 | /// instruction Mat. If the instruction is a PHI node then special |
Simon Pilgrim | 7d18a70 | 2016-11-20 13:19:49 +0000 | [diff] [blame] | 692 | /// handling for duplicate values form the same incoming basic block is |
Juergen Ributzka | e802d50 | 2014-03-22 01:49:27 +0000 | [diff] [blame] | 693 | /// required. |
| 694 | /// \return The update will always succeed, but the return value indicated if |
| 695 | /// Mat was used for the update or not. |
| 696 | static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) { |
| 697 | if (auto PHI = dyn_cast<PHINode>(Inst)) { |
| 698 | // Check if any previous operand of the PHI node has the same incoming basic |
| 699 | // block. This is a very odd case that happens when the incoming basic block |
| 700 | // has a switch statement. In this case use the same value as the previous |
| 701 | // operand(s), otherwise we will fail verification due to different values. |
| 702 | // The values are actually the same, but the variable names are different |
| 703 | // and the verifier doesn't like that. |
| 704 | BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx); |
| 705 | for (unsigned i = 0; i < Idx; ++i) { |
| 706 | if (PHI->getIncomingBlock(i) == IncomingBB) { |
| 707 | Value *IncomingVal = PHI->getIncomingValue(i); |
| 708 | Inst->setOperand(Idx, IncomingVal); |
| 709 | return false; |
| 710 | } |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | Inst->setOperand(Idx, Mat); |
| 715 | return true; |
| 716 | } |
| 717 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 718 | /// Emit materialization code for all rebased constants and update their |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 719 | /// users. |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 720 | void ConstantHoistingPass::emitBaseConstants(Instruction *Base, |
| 721 | Constant *Offset, |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 722 | Type *Ty, |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 723 | const ConstantUser &ConstUser) { |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 724 | Instruction *Mat = Base; |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 725 | |
| 726 | // The same offset can be dereferenced to different types in nested struct. |
| 727 | if (!Offset && Ty && Ty != Base->getType()) |
| 728 | Offset = ConstantInt::get(Type::getInt32Ty(*Ctx), 0); |
| 729 | |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 730 | if (Offset) { |
| 731 | Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst, |
| 732 | ConstUser.OpndIdx); |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 733 | if (Ty) { |
| 734 | // Constant being rebased is a ConstantExpr. |
| 735 | PointerType *Int8PtrTy = Type::getInt8PtrTy(*Ctx, |
| 736 | cast<PointerType>(Ty)->getAddressSpace()); |
| 737 | Base = new BitCastInst(Base, Int8PtrTy, "base_bitcast", InsertionPt); |
| 738 | Mat = GetElementPtrInst::Create(Int8PtrTy->getElementType(), Base, |
| 739 | Offset, "mat_gep", InsertionPt); |
| 740 | Mat = new BitCastInst(Mat, Ty, "mat_bitcast", InsertionPt); |
| 741 | } else |
| 742 | // Constant being rebased is a ConstantInt. |
| 743 | Mat = BinaryOperator::Create(Instruction::Add, Base, Offset, |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 744 | "const_mat", InsertionPt); |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 745 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 746 | LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0) |
| 747 | << " + " << *Offset << ") in BB " |
| 748 | << Mat->getParent()->getName() << '\n' |
| 749 | << *Mat << '\n'); |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 750 | Mat->setDebugLoc(ConstUser.Inst->getDebugLoc()); |
| 751 | } |
| 752 | Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx); |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 753 | |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 754 | // Visit constant integer. |
| 755 | if (isa<ConstantInt>(Opnd)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 756 | LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n'); |
Juergen Ributzka | e802d50 | 2014-03-22 01:49:27 +0000 | [diff] [blame] | 757 | if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset) |
| 758 | Mat->eraseFromParent(); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 759 | LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n'); |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 760 | return; |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 761 | } |
Juergen Ributzka | 6dab520 | 2014-03-20 19:55:52 +0000 | [diff] [blame] | 762 | |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 763 | // Visit cast instruction. |
| 764 | if (auto CastInst = dyn_cast<Instruction>(Opnd)) { |
| 765 | assert(CastInst->isCast() && "Expected an cast instruction!"); |
| 766 | // Check if we already have visited this cast instruction before to avoid |
| 767 | // unnecessary cloning. |
| 768 | Instruction *&ClonedCastInst = ClonedCastMap[CastInst]; |
| 769 | if (!ClonedCastInst) { |
| 770 | ClonedCastInst = CastInst->clone(); |
| 771 | ClonedCastInst->setOperand(0, Mat); |
| 772 | ClonedCastInst->insertAfter(CastInst); |
| 773 | // Use the same debug location as the original cast instruction. |
| 774 | ClonedCastInst->setDebugLoc(CastInst->getDebugLoc()); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 775 | LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n' |
| 776 | << "To : " << *ClonedCastInst << '\n'); |
Juergen Ributzka | 4635793 | 2014-03-20 20:17:13 +0000 | [diff] [blame] | 777 | } |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 778 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 779 | LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n'); |
Juergen Ributzka | e802d50 | 2014-03-22 01:49:27 +0000 | [diff] [blame] | 780 | updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 781 | LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n'); |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 782 | return; |
Juergen Ributzka | 4635793 | 2014-03-20 20:17:13 +0000 | [diff] [blame] | 783 | } |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 784 | |
| 785 | // Visit constant expression. |
| 786 | if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) { |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 787 | if (ConstExpr->isGEPWithNoNotionalOverIndexing()) { |
| 788 | // Operand is a ConstantGEP, replace it. |
| 789 | updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat); |
| 790 | return; |
| 791 | } |
| 792 | |
| 793 | // Aside from constant GEPs, only constant cast expressions are collected. |
| 794 | assert(ConstExpr->isCast() && "ConstExpr should be a cast"); |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 795 | Instruction *ConstExprInst = ConstExpr->getAsInstruction(); |
| 796 | ConstExprInst->setOperand(0, Mat); |
| 797 | ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst, |
| 798 | ConstUser.OpndIdx)); |
| 799 | |
| 800 | // Use the same debug location as the instruction we are about to update. |
| 801 | ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc()); |
| 802 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 803 | LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n' |
| 804 | << "From : " << *ConstExpr << '\n'); |
| 805 | LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n'); |
Juergen Ributzka | e802d50 | 2014-03-22 01:49:27 +0000 | [diff] [blame] | 806 | if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) { |
| 807 | ConstExprInst->eraseFromParent(); |
| 808 | if (Offset) |
| 809 | Mat->eraseFromParent(); |
| 810 | } |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 811 | LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n'); |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 812 | return; |
Juergen Ributzka | 4c8a025 | 2014-02-08 00:20:45 +0000 | [diff] [blame] | 813 | } |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 814 | } |
| 815 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 816 | /// Hoist and hide the base constant behind a bitcast and emit |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 817 | /// materialization code for derived constants. |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 818 | bool ConstantHoistingPass::emitBaseConstants(GlobalVariable *BaseGV) { |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 819 | bool MadeChange = false; |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 820 | SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec = |
| 821 | BaseGV ? ConstGEPInfoMap[BaseGV] : ConstIntInfoVec; |
| 822 | for (auto const &ConstInfo : ConstInfoVec) { |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 823 | SmallPtrSet<Instruction *, 8> IPSet = findConstantInsertionPoint(ConstInfo); |
| 824 | assert(!IPSet.empty() && "IPSet is empty"); |
| 825 | |
| 826 | unsigned UsesNum = 0; |
| 827 | unsigned ReBasesNum = 0; |
Zhaoshi Zheng | 9571033 | 2018-09-26 00:59:09 +0000 | [diff] [blame] | 828 | unsigned NotRebasedNum = 0; |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 829 | for (Instruction *IP : IPSet) { |
Zhaoshi Zheng | 9571033 | 2018-09-26 00:59:09 +0000 | [diff] [blame] | 830 | // First, collect constants depending on this IP of the base. |
| 831 | unsigned Uses = 0; |
| 832 | using RebasedUse = std::tuple<Constant *, Type *, ConstantUser>; |
| 833 | SmallVector<RebasedUse, 4> ToBeRebased; |
| 834 | for (auto const &RCI : ConstInfo.RebasedConstants) { |
| 835 | for (auto const &U : RCI.Uses) { |
| 836 | Uses++; |
| 837 | BasicBlock *OrigMatInsertBB = |
| 838 | findMatInsertPt(U.Inst, U.OpndIdx)->getParent(); |
| 839 | // If Base constant is to be inserted in multiple places, |
| 840 | // generate rebase for U using the Base dominating U. |
| 841 | if (IPSet.size() == 1 || |
| 842 | DT->dominates(IP->getParent(), OrigMatInsertBB)) |
| 843 | ToBeRebased.push_back(RebasedUse(RCI.Offset, RCI.Ty, U)); |
| 844 | } |
| 845 | } |
| 846 | UsesNum = Uses; |
| 847 | |
| 848 | // If only few constants depend on this IP of base, skip rebasing, |
| 849 | // assuming the base and the rebased have the same materialization cost. |
| 850 | if (ToBeRebased.size() < MinNumOfDependentToRebase) { |
| 851 | NotRebasedNum += ToBeRebased.size(); |
| 852 | continue; |
| 853 | } |
| 854 | |
| 855 | // Emit an instance of the base at this IP. |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 856 | Instruction *Base = nullptr; |
| 857 | // Hoist and hide the base constant behind a bitcast. |
| 858 | if (ConstInfo.BaseExpr) { |
| 859 | assert(BaseGV && "A base constant expression must have an base GV"); |
| 860 | Type *Ty = ConstInfo.BaseExpr->getType(); |
| 861 | Base = new BitCastInst(ConstInfo.BaseExpr, Ty, "const", IP); |
| 862 | } else { |
| 863 | IntegerType *Ty = ConstInfo.BaseInt->getType(); |
| 864 | Base = new BitCastInst(ConstInfo.BaseInt, Ty, "const", IP); |
| 865 | } |
Paul Robinson | b46256b | 2017-11-09 20:01:31 +0000 | [diff] [blame] | 866 | |
| 867 | Base->setDebugLoc(IP->getDebugLoc()); |
| 868 | |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 869 | LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseInt |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 870 | << ") to BB " << IP->getParent()->getName() << '\n' |
| 871 | << *Base << '\n'); |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 872 | |
Zhaoshi Zheng | 9571033 | 2018-09-26 00:59:09 +0000 | [diff] [blame] | 873 | // Emit materialization code for rebased constants depending on this IP. |
| 874 | for (auto const &R : ToBeRebased) { |
| 875 | Constant *Off = std::get<0>(R); |
| 876 | Type *Ty = std::get<1>(R); |
| 877 | ConstantUser U = std::get<2>(R); |
| 878 | emitBaseConstants(Base, Off, Ty, U); |
| 879 | ReBasesNum++; |
| 880 | // Use the same debug location as the last user of the constant. |
| 881 | Base->setDebugLoc(DILocation::getMergedLocation( |
| 882 | Base->getDebugLoc(), U.Inst->getDebugLoc())); |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 883 | } |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 884 | assert(!Base->use_empty() && "The use list is empty!?"); |
| 885 | assert(isa<Instruction>(Base->user_back()) && |
| 886 | "All uses should be instructions."); |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 887 | } |
| 888 | (void)UsesNum; |
| 889 | (void)ReBasesNum; |
Zhaoshi Zheng | 9571033 | 2018-09-26 00:59:09 +0000 | [diff] [blame] | 890 | (void)NotRebasedNum; |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 891 | // Expect all uses are rebased after rebase is done. |
Zhaoshi Zheng | 9571033 | 2018-09-26 00:59:09 +0000 | [diff] [blame] | 892 | assert(UsesNum == (ReBasesNum + NotRebasedNum) && |
| 893 | "Not all uses are rebased"); |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 894 | |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 895 | NumConstantsHoisted++; |
| 896 | |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 897 | // Base constant is also included in ConstInfo.RebasedConstants, so |
| 898 | // deduct 1 from ConstInfo.RebasedConstants.size(). |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 899 | NumConstantsRebased += ConstInfo.RebasedConstants.size() - 1; |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 900 | |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 901 | MadeChange = true; |
| 902 | } |
| 903 | return MadeChange; |
| 904 | } |
| 905 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 906 | /// Check all cast instructions we made a copy of and remove them if they |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 907 | /// have no more users. |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 908 | void ConstantHoistingPass::deleteDeadCastInst() const { |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 909 | for (auto const &I : ClonedCastMap) |
| 910 | if (I.first->use_empty()) |
Juergen Ributzka | e474752 | 2014-03-22 01:49:30 +0000 | [diff] [blame] | 911 | I.first->eraseFromParent(); |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 912 | } |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 913 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 914 | /// Optimize expensive integer constants in the given function. |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 915 | bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI, |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 916 | DominatorTree &DT, BlockFrequencyInfo *BFI, |
| 917 | BasicBlock &Entry) { |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 918 | this->TTI = &TTI; |
| 919 | this->DT = &DT; |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 920 | this->BFI = BFI; |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 921 | this->DL = &Fn.getParent()->getDataLayout(); |
| 922 | this->Ctx = &Fn.getContext(); |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 923 | this->Entry = &Entry; |
Juergen Ributzka | 4635793 | 2014-03-20 20:17:13 +0000 | [diff] [blame] | 924 | // Collect all constant candidates. |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 925 | collectConstantCandidates(Fn); |
Juergen Ributzka | 4635793 | 2014-03-20 20:17:13 +0000 | [diff] [blame] | 926 | |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 927 | // Combine constants that can be easily materialized with an add from a common |
| 928 | // base constant. |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 929 | if (!ConstIntCandVec.empty()) |
| 930 | findBaseConstants(nullptr); |
| 931 | for (auto &MapEntry : ConstGEPCandMap) |
| 932 | if (!MapEntry.second.empty()) |
| 933 | findBaseConstants(MapEntry.first); |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 934 | |
Juergen Ributzka | f0dff49 | 2014-03-21 06:04:45 +0000 | [diff] [blame] | 935 | // Finally hoist the base constant and emit materialization code for dependent |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 936 | // constants. |
Zhaoshi Zheng | a0aa41d | 2018-09-04 22:17:03 +0000 | [diff] [blame] | 937 | bool MadeChange = false; |
| 938 | if (!ConstIntInfoVec.empty()) |
| 939 | MadeChange = emitBaseConstants(nullptr); |
| 940 | for (auto MapEntry : ConstGEPInfoMap) |
| 941 | if (!MapEntry.second.empty()) |
| 942 | MadeChange |= emitBaseConstants(MapEntry.first); |
| 943 | |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 944 | |
Juergen Ributzka | 5429c06 | 2014-03-21 06:04:36 +0000 | [diff] [blame] | 945 | // Cleanup dead instructions. |
| 946 | deleteDeadCastInst(); |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 947 | |
Fangrui Song | f4b25f7 | 2019-03-01 05:27:01 +0000 | [diff] [blame^] | 948 | cleanup(); |
| 949 | |
Juergen Ributzka | f26beda | 2014-01-25 02:02:55 +0000 | [diff] [blame] | 950 | return MadeChange; |
| 951 | } |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 952 | |
| 953 | PreservedAnalyses ConstantHoistingPass::run(Function &F, |
| 954 | FunctionAnalysisManager &AM) { |
| 955 | auto &DT = AM.getResult<DominatorTreeAnalysis>(F); |
| 956 | auto &TTI = AM.getResult<TargetIRAnalysis>(F); |
Wei Mi | 337d4d9 | 2017-04-21 15:50:16 +0000 | [diff] [blame] | 957 | auto BFI = ConstHoistWithBlockFrequency |
| 958 | ? &AM.getResult<BlockFrequencyAnalysis>(F) |
| 959 | : nullptr; |
| 960 | if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock())) |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 961 | return PreservedAnalyses::all(); |
| 962 | |
Chandler Carruth | ca68a3e | 2017-01-15 06:32:49 +0000 | [diff] [blame] | 963 | PreservedAnalyses PA; |
| 964 | PA.preserveSet<CFGAnalyses>(); |
| 965 | return PA; |
Michael Kuperstein | 071d830 | 2016-07-02 00:16:47 +0000 | [diff] [blame] | 966 | } |