CalcSpillWeights.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. //===- CalcSpillWeights.cpp -----------------------------------------------===//
  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. #include "llvm/CodeGen/CalcSpillWeights.h"
  9. #include "llvm/ADT/SmallPtrSet.h"
  10. #include "llvm/CodeGen/LiveInterval.h"
  11. #include "llvm/CodeGen/LiveIntervals.h"
  12. #include "llvm/CodeGen/MachineFunction.h"
  13. #include "llvm/CodeGen/MachineInstr.h"
  14. #include "llvm/CodeGen/MachineLoopInfo.h"
  15. #include "llvm/CodeGen/MachineOperand.h"
  16. #include "llvm/CodeGen/MachineRegisterInfo.h"
  17. #include "llvm/CodeGen/StackMaps.h"
  18. #include "llvm/CodeGen/TargetInstrInfo.h"
  19. #include "llvm/CodeGen/TargetRegisterInfo.h"
  20. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  21. #include "llvm/CodeGen/VirtRegMap.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include <cassert>
  25. #include <tuple>
  26. using namespace llvm;
  27. #define DEBUG_TYPE "calcspillweights"
  28. void VirtRegAuxInfo::calculateSpillWeightsAndHints() {
  29. LLVM_DEBUG(dbgs() << "********** Compute Spill Weights **********\n"
  30. << "********** Function: " << MF.getName() << '\n');
  31. MachineRegisterInfo &MRI = MF.getRegInfo();
  32. for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
  33. Register Reg = Register::index2VirtReg(I);
  34. if (MRI.reg_nodbg_empty(Reg))
  35. continue;
  36. calculateSpillWeightAndHint(LIS.getInterval(Reg));
  37. }
  38. }
  39. // Return the preferred allocation register for reg, given a COPY instruction.
  40. Register VirtRegAuxInfo::copyHint(const MachineInstr *MI, unsigned Reg,
  41. const TargetRegisterInfo &TRI,
  42. const MachineRegisterInfo &MRI) {
  43. unsigned Sub, HSub;
  44. Register HReg;
  45. if (MI->getOperand(0).getReg() == Reg) {
  46. Sub = MI->getOperand(0).getSubReg();
  47. HReg = MI->getOperand(1).getReg();
  48. HSub = MI->getOperand(1).getSubReg();
  49. } else {
  50. Sub = MI->getOperand(1).getSubReg();
  51. HReg = MI->getOperand(0).getReg();
  52. HSub = MI->getOperand(0).getSubReg();
  53. }
  54. if (!HReg)
  55. return 0;
  56. if (HReg.isVirtual())
  57. return Sub == HSub ? HReg : Register();
  58. const TargetRegisterClass *RC = MRI.getRegClass(Reg);
  59. MCRegister CopiedPReg = HSub ? TRI.getSubReg(HReg, HSub) : HReg.asMCReg();
  60. if (RC->contains(CopiedPReg))
  61. return CopiedPReg;
  62. // Check if reg:sub matches so that a super register could be hinted.
  63. if (Sub)
  64. return TRI.getMatchingSuperReg(CopiedPReg, Sub, RC);
  65. return 0;
  66. }
  67. // Check if all values in LI are rematerializable
  68. bool VirtRegAuxInfo::isRematerializable(const LiveInterval &LI,
  69. const LiveIntervals &LIS,
  70. const VirtRegMap &VRM,
  71. const TargetInstrInfo &TII) {
  72. Register Reg = LI.reg();
  73. Register Original = VRM.getOriginal(Reg);
  74. for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
  75. I != E; ++I) {
  76. const VNInfo *VNI = *I;
  77. if (VNI->isUnused())
  78. continue;
  79. if (VNI->isPHIDef())
  80. return false;
  81. MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
  82. assert(MI && "Dead valno in interval");
  83. // Trace copies introduced by live range splitting. The inline
  84. // spiller can rematerialize through these copies, so the spill
  85. // weight must reflect this.
  86. while (MI->isFullCopy()) {
  87. // The copy destination must match the interval register.
  88. if (MI->getOperand(0).getReg() != Reg)
  89. return false;
  90. // Get the source register.
  91. Reg = MI->getOperand(1).getReg();
  92. // If the original (pre-splitting) registers match this
  93. // copy came from a split.
  94. if (!Reg.isVirtual() || VRM.getOriginal(Reg) != Original)
  95. return false;
  96. // Follow the copy live-in value.
  97. const LiveInterval &SrcLI = LIS.getInterval(Reg);
  98. LiveQueryResult SrcQ = SrcLI.Query(VNI->def);
  99. VNI = SrcQ.valueIn();
  100. assert(VNI && "Copy from non-existing value");
  101. if (VNI->isPHIDef())
  102. return false;
  103. MI = LIS.getInstructionFromIndex(VNI->def);
  104. assert(MI && "Dead valno in interval");
  105. }
  106. if (!TII.isTriviallyReMaterializable(*MI))
  107. return false;
  108. }
  109. return true;
  110. }
  111. bool VirtRegAuxInfo::isLiveAtStatepointVarArg(LiveInterval &LI) {
  112. return any_of(VRM.getRegInfo().reg_operands(LI.reg()),
  113. [](MachineOperand &MO) {
  114. MachineInstr *MI = MO.getParent();
  115. if (MI->getOpcode() != TargetOpcode::STATEPOINT)
  116. return false;
  117. return StatepointOpers(MI).getVarIdx() <= MI->getOperandNo(&MO);
  118. });
  119. }
  120. void VirtRegAuxInfo::calculateSpillWeightAndHint(LiveInterval &LI) {
  121. float Weight = weightCalcHelper(LI);
  122. // Check if unspillable.
  123. if (Weight < 0)
  124. return;
  125. LI.setWeight(Weight);
  126. }
  127. float VirtRegAuxInfo::weightCalcHelper(LiveInterval &LI, SlotIndex *Start,
  128. SlotIndex *End) {
  129. MachineRegisterInfo &MRI = MF.getRegInfo();
  130. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  131. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  132. MachineBasicBlock *MBB = nullptr;
  133. MachineLoop *Loop = nullptr;
  134. bool IsExiting = false;
  135. float TotalWeight = 0;
  136. unsigned NumInstr = 0; // Number of instructions using LI
  137. SmallPtrSet<MachineInstr *, 8> Visited;
  138. std::pair<Register, Register> TargetHint = MRI.getRegAllocationHint(LI.reg());
  139. if (LI.isSpillable()) {
  140. Register Reg = LI.reg();
  141. Register Original = VRM.getOriginal(Reg);
  142. const LiveInterval &OrigInt = LIS.getInterval(Original);
  143. // li comes from a split of OrigInt. If OrigInt was marked
  144. // as not spillable, make sure the new interval is marked
  145. // as not spillable as well.
  146. if (!OrigInt.isSpillable())
  147. LI.markNotSpillable();
  148. }
  149. // Don't recompute spill weight for an unspillable register.
  150. bool IsSpillable = LI.isSpillable();
  151. bool IsLocalSplitArtifact = Start && End;
  152. // Do not update future local split artifacts.
  153. bool ShouldUpdateLI = !IsLocalSplitArtifact;
  154. if (IsLocalSplitArtifact) {
  155. MachineBasicBlock *LocalMBB = LIS.getMBBFromIndex(*End);
  156. assert(LocalMBB == LIS.getMBBFromIndex(*Start) &&
  157. "start and end are expected to be in the same basic block");
  158. // Local split artifact will have 2 additional copy instructions and they
  159. // will be in the same BB.
  160. // localLI = COPY other
  161. // ...
  162. // other = COPY localLI
  163. TotalWeight += LiveIntervals::getSpillWeight(true, false, &MBFI, LocalMBB);
  164. TotalWeight += LiveIntervals::getSpillWeight(false, true, &MBFI, LocalMBB);
  165. NumInstr += 2;
  166. }
  167. // CopyHint is a sortable hint derived from a COPY instruction.
  168. struct CopyHint {
  169. const Register Reg;
  170. const float Weight;
  171. CopyHint(Register R, float W) : Reg(R), Weight(W) {}
  172. bool operator<(const CopyHint &Rhs) const {
  173. // Always prefer any physreg hint.
  174. if (Reg.isPhysical() != Rhs.Reg.isPhysical())
  175. return Reg.isPhysical();
  176. if (Weight != Rhs.Weight)
  177. return (Weight > Rhs.Weight);
  178. return Reg.id() < Rhs.Reg.id(); // Tie-breaker.
  179. }
  180. };
  181. std::set<CopyHint> CopyHints;
  182. DenseMap<unsigned, float> Hint;
  183. for (MachineRegisterInfo::reg_instr_nodbg_iterator
  184. I = MRI.reg_instr_nodbg_begin(LI.reg()),
  185. E = MRI.reg_instr_nodbg_end();
  186. I != E;) {
  187. MachineInstr *MI = &*(I++);
  188. // For local split artifacts, we are interested only in instructions between
  189. // the expected start and end of the range.
  190. SlotIndex SI = LIS.getInstructionIndex(*MI);
  191. if (IsLocalSplitArtifact && ((SI < *Start) || (SI > *End)))
  192. continue;
  193. NumInstr++;
  194. if (MI->isIdentityCopy() || MI->isImplicitDef())
  195. continue;
  196. if (!Visited.insert(MI).second)
  197. continue;
  198. // For terminators that produce values, ask the backend if the register is
  199. // not spillable.
  200. if (TII.isUnspillableTerminator(MI) && MI->definesRegister(LI.reg())) {
  201. LI.markNotSpillable();
  202. return -1.0f;
  203. }
  204. float Weight = 1.0f;
  205. if (IsSpillable) {
  206. // Get loop info for mi.
  207. if (MI->getParent() != MBB) {
  208. MBB = MI->getParent();
  209. Loop = Loops.getLoopFor(MBB);
  210. IsExiting = Loop ? Loop->isLoopExiting(MBB) : false;
  211. }
  212. // Calculate instr weight.
  213. bool Reads, Writes;
  214. std::tie(Reads, Writes) = MI->readsWritesVirtualRegister(LI.reg());
  215. Weight = LiveIntervals::getSpillWeight(Writes, Reads, &MBFI, *MI);
  216. // Give extra weight to what looks like a loop induction variable update.
  217. if (Writes && IsExiting && LIS.isLiveOutOfMBB(LI, MBB))
  218. Weight *= 3;
  219. TotalWeight += Weight;
  220. }
  221. // Get allocation hints from copies.
  222. if (!MI->isCopy())
  223. continue;
  224. Register HintReg = copyHint(MI, LI.reg(), TRI, MRI);
  225. if (!HintReg)
  226. continue;
  227. // Force hweight onto the stack so that x86 doesn't add hidden precision,
  228. // making the comparison incorrectly pass (i.e., 1 > 1 == true??).
  229. //
  230. // FIXME: we probably shouldn't use floats at all.
  231. volatile float HWeight = Hint[HintReg] += Weight;
  232. if (HintReg.isVirtual() || MRI.isAllocatable(HintReg))
  233. CopyHints.insert(CopyHint(HintReg, HWeight));
  234. }
  235. // Pass all the sorted copy hints to mri.
  236. if (ShouldUpdateLI && CopyHints.size()) {
  237. // Remove a generic hint if previously added by target.
  238. if (TargetHint.first == 0 && TargetHint.second)
  239. MRI.clearSimpleHint(LI.reg());
  240. SmallSet<Register, 4> HintedRegs;
  241. for (const auto &Hint : CopyHints) {
  242. if (!HintedRegs.insert(Hint.Reg).second ||
  243. (TargetHint.first != 0 && Hint.Reg == TargetHint.second))
  244. // Don't add the same reg twice or the target-type hint again.
  245. continue;
  246. MRI.addRegAllocationHint(LI.reg(), Hint.Reg);
  247. }
  248. // Weakly boost the spill weight of hinted registers.
  249. TotalWeight *= 1.01F;
  250. }
  251. // If the live interval was already unspillable, leave it that way.
  252. if (!IsSpillable)
  253. return -1.0;
  254. // Mark li as unspillable if all live ranges are tiny and the interval
  255. // is not live at any reg mask. If the interval is live at a reg mask
  256. // spilling may be required. If li is live as use in statepoint instruction
  257. // spilling may be required due to if we mark interval with use in statepoint
  258. // as not spillable we are risky to end up with no register to allocate.
  259. // At the same time STATEPOINT instruction is perfectly fine to have this
  260. // operand on stack, so spilling such interval and folding its load from stack
  261. // into instruction itself makes perfect sense.
  262. if (ShouldUpdateLI && LI.isZeroLength(LIS.getSlotIndexes()) &&
  263. !LI.isLiveAtIndexes(LIS.getRegMaskSlots()) &&
  264. !isLiveAtStatepointVarArg(LI)) {
  265. LI.markNotSpillable();
  266. return -1.0;
  267. }
  268. // If all of the definitions of the interval are re-materializable,
  269. // it is a preferred candidate for spilling.
  270. // FIXME: this gets much more complicated once we support non-trivial
  271. // re-materialization.
  272. if (isRematerializable(LI, LIS, VRM, *MF.getSubtarget().getInstrInfo()))
  273. TotalWeight *= 0.5F;
  274. if (IsLocalSplitArtifact)
  275. return normalize(TotalWeight, Start->distance(*End), NumInstr);
  276. return normalize(TotalWeight, LI.getSize(), NumInstr);
  277. }