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