CalcSpillWeights.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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 (Register::isVirtualRegister(HReg))
  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 (!Register::isVirtualRegister(Reg) || 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, LIS.getAliasAnalysis()))
  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::futureWeight(LiveInterval &LI, SlotIndex Start,
  128. SlotIndex End) {
  129. return weightCalcHelper(LI, &Start, &End);
  130. }
  131. float VirtRegAuxInfo::weightCalcHelper(LiveInterval &LI, SlotIndex *Start,
  132. SlotIndex *End) {
  133. MachineRegisterInfo &MRI = MF.getRegInfo();
  134. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  135. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  136. MachineBasicBlock *MBB = nullptr;
  137. MachineLoop *Loop = nullptr;
  138. bool IsExiting = false;
  139. float TotalWeight = 0;
  140. unsigned NumInstr = 0; // Number of instructions using LI
  141. SmallPtrSet<MachineInstr *, 8> Visited;
  142. std::pair<Register, Register> TargetHint = MRI.getRegAllocationHint(LI.reg());
  143. if (LI.isSpillable()) {
  144. Register Reg = LI.reg();
  145. Register Original = VRM.getOriginal(Reg);
  146. const LiveInterval &OrigInt = LIS.getInterval(Original);
  147. // li comes from a split of OrigInt. If OrigInt was marked
  148. // as not spillable, make sure the new interval is marked
  149. // as not spillable as well.
  150. if (!OrigInt.isSpillable())
  151. LI.markNotSpillable();
  152. }
  153. // Don't recompute spill weight for an unspillable register.
  154. bool IsSpillable = LI.isSpillable();
  155. bool IsLocalSplitArtifact = Start && End;
  156. // Do not update future local split artifacts.
  157. bool ShouldUpdateLI = !IsLocalSplitArtifact;
  158. if (IsLocalSplitArtifact) {
  159. MachineBasicBlock *LocalMBB = LIS.getMBBFromIndex(*End);
  160. assert(LocalMBB == LIS.getMBBFromIndex(*Start) &&
  161. "start and end are expected to be in the same basic block");
  162. // Local split artifact will have 2 additional copy instructions and they
  163. // will be in the same BB.
  164. // localLI = COPY other
  165. // ...
  166. // other = COPY localLI
  167. TotalWeight += LiveIntervals::getSpillWeight(true, false, &MBFI, LocalMBB);
  168. TotalWeight += LiveIntervals::getSpillWeight(false, true, &MBFI, LocalMBB);
  169. NumInstr += 2;
  170. }
  171. // CopyHint is a sortable hint derived from a COPY instruction.
  172. struct CopyHint {
  173. const Register Reg;
  174. const float Weight;
  175. CopyHint(Register R, float W) : Reg(R), Weight(W) {}
  176. bool operator<(const CopyHint &Rhs) const {
  177. // Always prefer any physreg hint.
  178. if (Reg.isPhysical() != Rhs.Reg.isPhysical())
  179. return Reg.isPhysical();
  180. if (Weight != Rhs.Weight)
  181. return (Weight > Rhs.Weight);
  182. return Reg.id() < Rhs.Reg.id(); // Tie-breaker.
  183. }
  184. };
  185. std::set<CopyHint> CopyHints;
  186. DenseMap<unsigned, float> Hint;
  187. for (MachineRegisterInfo::reg_instr_nodbg_iterator
  188. I = MRI.reg_instr_nodbg_begin(LI.reg()),
  189. E = MRI.reg_instr_nodbg_end();
  190. I != E;) {
  191. MachineInstr *MI = &*(I++);
  192. // For local split artifacts, we are interested only in instructions between
  193. // the expected start and end of the range.
  194. SlotIndex SI = LIS.getInstructionIndex(*MI);
  195. if (IsLocalSplitArtifact && ((SI < *Start) || (SI > *End)))
  196. continue;
  197. NumInstr++;
  198. if (MI->isIdentityCopy() || MI->isImplicitDef())
  199. continue;
  200. if (!Visited.insert(MI).second)
  201. continue;
  202. // For terminators that produce values, ask the backend if the register is
  203. // not spillable.
  204. if (TII.isUnspillableTerminator(MI) && MI->definesRegister(LI.reg())) {
  205. LI.markNotSpillable();
  206. return -1.0f;
  207. }
  208. float Weight = 1.0f;
  209. if (IsSpillable) {
  210. // Get loop info for mi.
  211. if (MI->getParent() != MBB) {
  212. MBB = MI->getParent();
  213. Loop = Loops.getLoopFor(MBB);
  214. IsExiting = Loop ? Loop->isLoopExiting(MBB) : false;
  215. }
  216. // Calculate instr weight.
  217. bool Reads, Writes;
  218. std::tie(Reads, Writes) = MI->readsWritesVirtualRegister(LI.reg());
  219. Weight = LiveIntervals::getSpillWeight(Writes, Reads, &MBFI, *MI);
  220. // Give extra weight to what looks like a loop induction variable update.
  221. if (Writes && IsExiting && LIS.isLiveOutOfMBB(LI, MBB))
  222. Weight *= 3;
  223. TotalWeight += Weight;
  224. }
  225. // Get allocation hints from copies.
  226. if (!MI->isCopy())
  227. continue;
  228. Register HintReg = copyHint(MI, LI.reg(), TRI, MRI);
  229. if (!HintReg)
  230. continue;
  231. // Force hweight onto the stack so that x86 doesn't add hidden precision,
  232. // making the comparison incorrectly pass (i.e., 1 > 1 == true??).
  233. //
  234. // FIXME: we probably shouldn't use floats at all.
  235. volatile float HWeight = Hint[HintReg] += Weight;
  236. if (HintReg.isVirtual() || MRI.isAllocatable(HintReg))
  237. CopyHints.insert(CopyHint(HintReg, HWeight));
  238. }
  239. // Pass all the sorted copy hints to mri.
  240. if (ShouldUpdateLI && CopyHints.size()) {
  241. // Remove a generic hint if previously added by target.
  242. if (TargetHint.first == 0 && TargetHint.second)
  243. MRI.clearSimpleHint(LI.reg());
  244. std::set<Register> HintedRegs;
  245. for (auto &Hint : CopyHints) {
  246. if (!HintedRegs.insert(Hint.Reg).second ||
  247. (TargetHint.first != 0 && Hint.Reg == TargetHint.second))
  248. // Don't add the same reg twice or the target-type hint again.
  249. continue;
  250. MRI.addRegAllocationHint(LI.reg(), Hint.Reg);
  251. }
  252. // Weakly boost the spill weight of hinted registers.
  253. TotalWeight *= 1.01F;
  254. }
  255. // If the live interval was already unspillable, leave it that way.
  256. if (!IsSpillable)
  257. return -1.0;
  258. // Mark li as unspillable if all live ranges are tiny and the interval
  259. // is not live at any reg mask. If the interval is live at a reg mask
  260. // spilling may be required. If li is live as use in statepoint instruction
  261. // spilling may be required due to if we mark interval with use in statepoint
  262. // as not spillable we are risky to end up with no register to allocate.
  263. // At the same time STATEPOINT instruction is perfectly fine to have this
  264. // operand on stack, so spilling such interval and folding its load from stack
  265. // into instruction itself makes perfect sense.
  266. if (ShouldUpdateLI && LI.isZeroLength(LIS.getSlotIndexes()) &&
  267. !LI.isLiveAtIndexes(LIS.getRegMaskSlots()) &&
  268. !isLiveAtStatepointVarArg(LI)) {
  269. LI.markNotSpillable();
  270. return -1.0;
  271. }
  272. // If all of the definitions of the interval are re-materializable,
  273. // it is a preferred candidate for spilling.
  274. // FIXME: this gets much more complicated once we support non-trivial
  275. // re-materialization.
  276. if (isRematerializable(LI, LIS, VRM, *MF.getSubtarget().getInstrInfo()))
  277. TotalWeight *= 0.5F;
  278. if (IsLocalSplitArtifact)
  279. return normalize(TotalWeight, Start->distance(*End), NumInstr);
  280. return normalize(TotalWeight, LI.getSize(), NumInstr);
  281. }