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