ConstantHoisting.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //==- ConstantHoisting.h - Prepare code for expensive constants --*- C++ -*-==//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This pass identifies expensive constants to hoist and coalesces them to
  15. // better prepare it for SelectionDAG-based code generation. This works around
  16. // the limitations of the basic-block-at-a-time approach.
  17. //
  18. // First it scans all instructions for integer constants and calculates its
  19. // cost. If the constant can be folded into the instruction (the cost is
  20. // TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
  21. // consider it expensive and leave it alone. This is the default behavior and
  22. // the default implementation of getIntImmCostInst will always return TCC_Free.
  23. //
  24. // If the cost is more than TCC_BASIC, then the integer constant can't be folded
  25. // into the instruction and it might be beneficial to hoist the constant.
  26. // Similar constants are coalesced to reduce register pressure and
  27. // materialization code.
  28. //
  29. // When a constant is hoisted, it is also hidden behind a bitcast to force it to
  30. // be live-out of the basic block. Otherwise the constant would be just
  31. // duplicated and each basic block would have its own copy in the SelectionDAG.
  32. // The SelectionDAG recognizes such constants as opaque and doesn't perform
  33. // certain transformations on them, which would create a new expensive constant.
  34. //
  35. // This optimization is only applied to integer constants in instructions and
  36. // simple (this means not nested) constant cast expressions. For example:
  37. // %0 = load i64* inttoptr (i64 big_constant to i64*)
  38. //
  39. //===----------------------------------------------------------------------===//
  40. #ifndef LLVM_TRANSFORMS_SCALAR_CONSTANTHOISTING_H
  41. #define LLVM_TRANSFORMS_SCALAR_CONSTANTHOISTING_H
  42. #include "llvm/ADT/DenseMap.h"
  43. #include "llvm/ADT/MapVector.h"
  44. #include "llvm/ADT/PointerUnion.h"
  45. #include "llvm/ADT/SetVector.h"
  46. #include "llvm/ADT/SmallVector.h"
  47. #include "llvm/IR/PassManager.h"
  48. #include <algorithm>
  49. #include <vector>
  50. namespace llvm {
  51. class BasicBlock;
  52. class BlockFrequencyInfo;
  53. class Constant;
  54. class ConstantInt;
  55. class ConstantExpr;
  56. class DominatorTree;
  57. class Function;
  58. class GlobalVariable;
  59. class Instruction;
  60. class ProfileSummaryInfo;
  61. class TargetTransformInfo;
  62. /// A private "module" namespace for types and utilities used by
  63. /// ConstantHoisting. These are implementation details and should not be used by
  64. /// clients.
  65. namespace consthoist {
  66. /// Keeps track of the user of a constant and the operand index where the
  67. /// constant is used.
  68. struct ConstantUser {
  69. Instruction *Inst;
  70. unsigned OpndIdx;
  71. ConstantUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) {}
  72. };
  73. using ConstantUseListType = SmallVector<ConstantUser, 8>;
  74. /// Keeps track of a constant candidate and its uses.
  75. struct ConstantCandidate {
  76. ConstantUseListType Uses;
  77. // If the candidate is a ConstantExpr (currely only constant GEP expressions
  78. // whose base pointers are GlobalVariables are supported), ConstInt records
  79. // its offset from the base GV, ConstExpr tracks the candidate GEP expr.
  80. ConstantInt *ConstInt;
  81. ConstantExpr *ConstExpr;
  82. unsigned CumulativeCost = 0;
  83. ConstantCandidate(ConstantInt *ConstInt, ConstantExpr *ConstExpr=nullptr) :
  84. ConstInt(ConstInt), ConstExpr(ConstExpr) {}
  85. /// Add the user to the use list and update the cost.
  86. void addUser(Instruction *Inst, unsigned Idx, unsigned Cost) {
  87. CumulativeCost += Cost;
  88. Uses.push_back(ConstantUser(Inst, Idx));
  89. }
  90. };
  91. /// This represents a constant that has been rebased with respect to a
  92. /// base constant. The difference to the base constant is recorded in Offset.
  93. struct RebasedConstantInfo {
  94. ConstantUseListType Uses;
  95. Constant *Offset;
  96. Type *Ty;
  97. RebasedConstantInfo(ConstantUseListType &&Uses, Constant *Offset,
  98. Type *Ty=nullptr) : Uses(std::move(Uses)), Offset(Offset), Ty(Ty) {}
  99. };
  100. using RebasedConstantListType = SmallVector<RebasedConstantInfo, 4>;
  101. /// A base constant and all its rebased constants.
  102. struct ConstantInfo {
  103. // If the candidate is a ConstantExpr (currely only constant GEP expressions
  104. // whose base pointers are GlobalVariables are supported), ConstInt records
  105. // its offset from the base GV, ConstExpr tracks the candidate GEP expr.
  106. ConstantInt *BaseInt;
  107. ConstantExpr *BaseExpr;
  108. RebasedConstantListType RebasedConstants;
  109. };
  110. } // end namespace consthoist
  111. class ConstantHoistingPass : public PassInfoMixin<ConstantHoistingPass> {
  112. public:
  113. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  114. // Glue for old PM.
  115. bool runImpl(Function &F, TargetTransformInfo &TTI, DominatorTree &DT,
  116. BlockFrequencyInfo *BFI, BasicBlock &Entry,
  117. ProfileSummaryInfo *PSI);
  118. void cleanup() {
  119. ClonedCastMap.clear();
  120. ConstIntCandVec.clear();
  121. for (auto MapEntry : ConstGEPCandMap)
  122. MapEntry.second.clear();
  123. ConstGEPCandMap.clear();
  124. ConstIntInfoVec.clear();
  125. for (auto MapEntry : ConstGEPInfoMap)
  126. MapEntry.second.clear();
  127. ConstGEPInfoMap.clear();
  128. }
  129. private:
  130. using ConstPtrUnionType = PointerUnion<ConstantInt *, ConstantExpr *>;
  131. using ConstCandMapType = DenseMap<ConstPtrUnionType, unsigned>;
  132. const TargetTransformInfo *TTI;
  133. DominatorTree *DT;
  134. BlockFrequencyInfo *BFI;
  135. LLVMContext *Ctx;
  136. const DataLayout *DL;
  137. BasicBlock *Entry;
  138. ProfileSummaryInfo *PSI;
  139. /// Keeps track of constant candidates found in the function.
  140. using ConstCandVecType = std::vector<consthoist::ConstantCandidate>;
  141. using GVCandVecMapType = MapVector<GlobalVariable *, ConstCandVecType>;
  142. ConstCandVecType ConstIntCandVec;
  143. GVCandVecMapType ConstGEPCandMap;
  144. /// These are the final constants we decided to hoist.
  145. using ConstInfoVecType = SmallVector<consthoist::ConstantInfo, 8>;
  146. using GVInfoVecMapType = MapVector<GlobalVariable *, ConstInfoVecType>;
  147. ConstInfoVecType ConstIntInfoVec;
  148. GVInfoVecMapType ConstGEPInfoMap;
  149. /// Keep track of cast instructions we already cloned.
  150. MapVector<Instruction *, Instruction *> ClonedCastMap;
  151. Instruction *findMatInsertPt(Instruction *Inst, unsigned Idx = ~0U) const;
  152. SetVector<Instruction *>
  153. findConstantInsertionPoint(const consthoist::ConstantInfo &ConstInfo) const;
  154. void collectConstantCandidates(ConstCandMapType &ConstCandMap,
  155. Instruction *Inst, unsigned Idx,
  156. ConstantInt *ConstInt);
  157. void collectConstantCandidates(ConstCandMapType &ConstCandMap,
  158. Instruction *Inst, unsigned Idx,
  159. ConstantExpr *ConstExpr);
  160. void collectConstantCandidates(ConstCandMapType &ConstCandMap,
  161. Instruction *Inst, unsigned Idx);
  162. void collectConstantCandidates(ConstCandMapType &ConstCandMap,
  163. Instruction *Inst);
  164. void collectConstantCandidates(Function &Fn);
  165. void findAndMakeBaseConstant(ConstCandVecType::iterator S,
  166. ConstCandVecType::iterator E,
  167. SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec);
  168. unsigned maximizeConstantsInRange(ConstCandVecType::iterator S,
  169. ConstCandVecType::iterator E,
  170. ConstCandVecType::iterator &MaxCostItr);
  171. // If BaseGV is nullptr, find base among Constant Integer candidates;
  172. // otherwise find base among constant GEPs sharing BaseGV as base pointer.
  173. void findBaseConstants(GlobalVariable *BaseGV);
  174. void emitBaseConstants(Instruction *Base, Constant *Offset, Type *Ty,
  175. const consthoist::ConstantUser &ConstUser);
  176. // If BaseGV is nullptr, emit Constant Integer base; otherwise emit
  177. // constant GEP base.
  178. bool emitBaseConstants(GlobalVariable *BaseGV);
  179. void deleteDeadCastInst() const;
  180. };
  181. } // end namespace llvm
  182. #endif // LLVM_TRANSFORMS_SCALAR_CONSTANTHOISTING_H
  183. #ifdef __GNUC__
  184. #pragma GCC diagnostic pop
  185. #endif