MachineLICM.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600
  1. //===- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ----------===//
  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 performs loop invariant code motion on machine instructions. We
  10. // attempt to remove as much code from the body of a loop as possible.
  11. //
  12. // This pass is not intended to be a replacement or a complete alternative
  13. // for the LLVM-IR-level LICM pass. It is only designed to hoist simple
  14. // constructs that are not exposed before lowering and instruction selection.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/ADT/BitVector.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/Analysis/AliasAnalysis.h"
  24. #include "llvm/CodeGen/MachineBasicBlock.h"
  25. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  26. #include "llvm/CodeGen/MachineDominators.h"
  27. #include "llvm/CodeGen/MachineFrameInfo.h"
  28. #include "llvm/CodeGen/MachineFunction.h"
  29. #include "llvm/CodeGen/MachineFunctionPass.h"
  30. #include "llvm/CodeGen/MachineInstr.h"
  31. #include "llvm/CodeGen/MachineLoopInfo.h"
  32. #include "llvm/CodeGen/MachineMemOperand.h"
  33. #include "llvm/CodeGen/MachineOperand.h"
  34. #include "llvm/CodeGen/MachineRegisterInfo.h"
  35. #include "llvm/CodeGen/PseudoSourceValue.h"
  36. #include "llvm/CodeGen/TargetInstrInfo.h"
  37. #include "llvm/CodeGen/TargetLowering.h"
  38. #include "llvm/CodeGen/TargetRegisterInfo.h"
  39. #include "llvm/CodeGen/TargetSchedule.h"
  40. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  41. #include "llvm/IR/DebugLoc.h"
  42. #include "llvm/InitializePasses.h"
  43. #include "llvm/MC/MCInstrDesc.h"
  44. #include "llvm/MC/MCRegister.h"
  45. #include "llvm/MC/MCRegisterInfo.h"
  46. #include "llvm/Pass.h"
  47. #include "llvm/Support/Casting.h"
  48. #include "llvm/Support/CommandLine.h"
  49. #include "llvm/Support/Debug.h"
  50. #include "llvm/Support/raw_ostream.h"
  51. #include <algorithm>
  52. #include <cassert>
  53. #include <limits>
  54. #include <vector>
  55. using namespace llvm;
  56. #define DEBUG_TYPE "machinelicm"
  57. static cl::opt<bool>
  58. AvoidSpeculation("avoid-speculation",
  59. cl::desc("MachineLICM should avoid speculation"),
  60. cl::init(true), cl::Hidden);
  61. static cl::opt<bool>
  62. HoistCheapInsts("hoist-cheap-insts",
  63. cl::desc("MachineLICM should hoist even cheap instructions"),
  64. cl::init(false), cl::Hidden);
  65. static cl::opt<bool>
  66. SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
  67. cl::desc("MachineLICM should sink instructions into "
  68. "loops to avoid register spills"),
  69. cl::init(false), cl::Hidden);
  70. static cl::opt<bool>
  71. HoistConstStores("hoist-const-stores",
  72. cl::desc("Hoist invariant stores"),
  73. cl::init(true), cl::Hidden);
  74. // The default threshold of 100 (i.e. if target block is 100 times hotter)
  75. // is based on empirical data on a single target and is subject to tuning.
  76. static cl::opt<unsigned>
  77. BlockFrequencyRatioThreshold("block-freq-ratio-threshold",
  78. cl::desc("Do not hoist instructions if target"
  79. "block is N times hotter than the source."),
  80. cl::init(100), cl::Hidden);
  81. enum class UseBFI { None, PGO, All };
  82. static cl::opt<UseBFI>
  83. DisableHoistingToHotterBlocks("disable-hoisting-to-hotter-blocks",
  84. cl::desc("Disable hoisting instructions to"
  85. " hotter blocks"),
  86. cl::init(UseBFI::PGO), cl::Hidden,
  87. cl::values(clEnumValN(UseBFI::None, "none",
  88. "disable the feature"),
  89. clEnumValN(UseBFI::PGO, "pgo",
  90. "enable the feature when using profile data"),
  91. clEnumValN(UseBFI::All, "all",
  92. "enable the feature with/wo profile data")));
  93. STATISTIC(NumHoisted,
  94. "Number of machine instructions hoisted out of loops");
  95. STATISTIC(NumLowRP,
  96. "Number of instructions hoisted in low reg pressure situation");
  97. STATISTIC(NumHighLatency,
  98. "Number of high latency instructions hoisted");
  99. STATISTIC(NumCSEed,
  100. "Number of hoisted machine instructions CSEed");
  101. STATISTIC(NumPostRAHoisted,
  102. "Number of machine instructions hoisted out of loops post regalloc");
  103. STATISTIC(NumStoreConst,
  104. "Number of stores of const phys reg hoisted out of loops");
  105. STATISTIC(NumNotHoistedDueToHotness,
  106. "Number of instructions not hoisted due to block frequency");
  107. namespace {
  108. class MachineLICMBase : public MachineFunctionPass {
  109. const TargetInstrInfo *TII;
  110. const TargetLoweringBase *TLI;
  111. const TargetRegisterInfo *TRI;
  112. const MachineFrameInfo *MFI;
  113. MachineRegisterInfo *MRI;
  114. TargetSchedModel SchedModel;
  115. bool PreRegAlloc;
  116. bool HasProfileData;
  117. // Various analyses that we use...
  118. AliasAnalysis *AA; // Alias analysis info.
  119. MachineBlockFrequencyInfo *MBFI; // Machine block frequncy info
  120. MachineLoopInfo *MLI; // Current MachineLoopInfo
  121. MachineDominatorTree *DT; // Machine dominator tree for the cur loop
  122. // State that is updated as we process loops
  123. bool Changed; // True if a loop is changed.
  124. bool FirstInLoop; // True if it's the first LICM in the loop.
  125. MachineLoop *CurLoop; // The current loop we are working on.
  126. MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
  127. // Exit blocks for CurLoop.
  128. SmallVector<MachineBasicBlock *, 8> ExitBlocks;
  129. bool isExitBlock(const MachineBasicBlock *MBB) const {
  130. return is_contained(ExitBlocks, MBB);
  131. }
  132. // Track 'estimated' register pressure.
  133. SmallSet<Register, 32> RegSeen;
  134. SmallVector<unsigned, 8> RegPressure;
  135. // Register pressure "limit" per register pressure set. If the pressure
  136. // is higher than the limit, then it's considered high.
  137. SmallVector<unsigned, 8> RegLimit;
  138. // Register pressure on path leading from loop preheader to current BB.
  139. SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
  140. // For each opcode, keep a list of potential CSE instructions.
  141. DenseMap<unsigned, std::vector<MachineInstr *>> CSEMap;
  142. enum {
  143. SpeculateFalse = 0,
  144. SpeculateTrue = 1,
  145. SpeculateUnknown = 2
  146. };
  147. // If a MBB does not dominate loop exiting blocks then it may not safe
  148. // to hoist loads from this block.
  149. // Tri-state: 0 - false, 1 - true, 2 - unknown
  150. unsigned SpeculationState;
  151. public:
  152. MachineLICMBase(char &PassID, bool PreRegAlloc)
  153. : MachineFunctionPass(PassID), PreRegAlloc(PreRegAlloc) {}
  154. bool runOnMachineFunction(MachineFunction &MF) override;
  155. void getAnalysisUsage(AnalysisUsage &AU) const override {
  156. AU.addRequired<MachineLoopInfo>();
  157. if (DisableHoistingToHotterBlocks != UseBFI::None)
  158. AU.addRequired<MachineBlockFrequencyInfo>();
  159. AU.addRequired<MachineDominatorTree>();
  160. AU.addRequired<AAResultsWrapperPass>();
  161. AU.addPreserved<MachineLoopInfo>();
  162. MachineFunctionPass::getAnalysisUsage(AU);
  163. }
  164. void releaseMemory() override {
  165. RegSeen.clear();
  166. RegPressure.clear();
  167. RegLimit.clear();
  168. BackTrace.clear();
  169. CSEMap.clear();
  170. }
  171. private:
  172. /// Keep track of information about hoisting candidates.
  173. struct CandidateInfo {
  174. MachineInstr *MI;
  175. unsigned Def;
  176. int FI;
  177. CandidateInfo(MachineInstr *mi, unsigned def, int fi)
  178. : MI(mi), Def(def), FI(fi) {}
  179. };
  180. void HoistRegionPostRA();
  181. void HoistPostRA(MachineInstr *MI, unsigned Def);
  182. void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
  183. BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
  184. SmallVectorImpl<CandidateInfo> &Candidates);
  185. void AddToLiveIns(MCRegister Reg);
  186. bool IsLICMCandidate(MachineInstr &I);
  187. bool IsLoopInvariantInst(MachineInstr &I);
  188. bool HasLoopPHIUse(const MachineInstr *MI) const;
  189. bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
  190. Register Reg) const;
  191. bool IsCheapInstruction(MachineInstr &MI) const;
  192. bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
  193. bool Cheap);
  194. void UpdateBackTraceRegPressure(const MachineInstr *MI);
  195. bool IsProfitableToHoist(MachineInstr &MI);
  196. bool IsGuaranteedToExecute(MachineBasicBlock *BB);
  197. void EnterScope(MachineBasicBlock *MBB);
  198. void ExitScope(MachineBasicBlock *MBB);
  199. void ExitScopeIfDone(
  200. MachineDomTreeNode *Node,
  201. DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
  202. DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
  203. void HoistOutOfLoop(MachineDomTreeNode *HeaderN);
  204. void SinkIntoLoop();
  205. void InitRegPressure(MachineBasicBlock *BB);
  206. DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
  207. bool ConsiderSeen,
  208. bool ConsiderUnseenAsDef);
  209. void UpdateRegPressure(const MachineInstr *MI,
  210. bool ConsiderUnseenAsDef = false);
  211. MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
  212. MachineInstr *LookForDuplicate(const MachineInstr *MI,
  213. std::vector<MachineInstr *> &PrevMIs);
  214. bool
  215. EliminateCSE(MachineInstr *MI,
  216. DenseMap<unsigned, std::vector<MachineInstr *>>::iterator &CI);
  217. bool MayCSE(MachineInstr *MI);
  218. bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
  219. void InitCSEMap(MachineBasicBlock *BB);
  220. bool isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
  221. MachineBasicBlock *TgtBlock);
  222. MachineBasicBlock *getCurPreheader();
  223. };
  224. class MachineLICM : public MachineLICMBase {
  225. public:
  226. static char ID;
  227. MachineLICM() : MachineLICMBase(ID, false) {
  228. initializeMachineLICMPass(*PassRegistry::getPassRegistry());
  229. }
  230. };
  231. class EarlyMachineLICM : public MachineLICMBase {
  232. public:
  233. static char ID;
  234. EarlyMachineLICM() : MachineLICMBase(ID, true) {
  235. initializeEarlyMachineLICMPass(*PassRegistry::getPassRegistry());
  236. }
  237. };
  238. } // end anonymous namespace
  239. char MachineLICM::ID;
  240. char EarlyMachineLICM::ID;
  241. char &llvm::MachineLICMID = MachineLICM::ID;
  242. char &llvm::EarlyMachineLICMID = EarlyMachineLICM::ID;
  243. INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE,
  244. "Machine Loop Invariant Code Motion", false, false)
  245. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  246. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  247. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  248. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  249. INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE,
  250. "Machine Loop Invariant Code Motion", false, false)
  251. INITIALIZE_PASS_BEGIN(EarlyMachineLICM, "early-machinelicm",
  252. "Early Machine Loop Invariant Code Motion", false, false)
  253. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  254. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  255. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  256. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  257. INITIALIZE_PASS_END(EarlyMachineLICM, "early-machinelicm",
  258. "Early Machine Loop Invariant Code Motion", false, false)
  259. /// Test if the given loop is the outer-most loop that has a unique predecessor.
  260. static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
  261. // Check whether this loop even has a unique predecessor.
  262. if (!CurLoop->getLoopPredecessor())
  263. return false;
  264. // Ok, now check to see if any of its outer loops do.
  265. for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
  266. if (L->getLoopPredecessor())
  267. return false;
  268. // None of them did, so this is the outermost with a unique predecessor.
  269. return true;
  270. }
  271. bool MachineLICMBase::runOnMachineFunction(MachineFunction &MF) {
  272. if (skipFunction(MF.getFunction()))
  273. return false;
  274. Changed = FirstInLoop = false;
  275. const TargetSubtargetInfo &ST = MF.getSubtarget();
  276. TII = ST.getInstrInfo();
  277. TLI = ST.getTargetLowering();
  278. TRI = ST.getRegisterInfo();
  279. MFI = &MF.getFrameInfo();
  280. MRI = &MF.getRegInfo();
  281. SchedModel.init(&ST);
  282. PreRegAlloc = MRI->isSSA();
  283. HasProfileData = MF.getFunction().hasProfileData();
  284. if (PreRegAlloc)
  285. LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
  286. else
  287. LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
  288. LLVM_DEBUG(dbgs() << MF.getName() << " ********\n");
  289. if (PreRegAlloc) {
  290. // Estimate register pressure during pre-regalloc pass.
  291. unsigned NumRPS = TRI->getNumRegPressureSets();
  292. RegPressure.resize(NumRPS);
  293. std::fill(RegPressure.begin(), RegPressure.end(), 0);
  294. RegLimit.resize(NumRPS);
  295. for (unsigned i = 0, e = NumRPS; i != e; ++i)
  296. RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
  297. }
  298. // Get our Loop information...
  299. if (DisableHoistingToHotterBlocks != UseBFI::None)
  300. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  301. MLI = &getAnalysis<MachineLoopInfo>();
  302. DT = &getAnalysis<MachineDominatorTree>();
  303. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  304. SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
  305. while (!Worklist.empty()) {
  306. CurLoop = Worklist.pop_back_val();
  307. CurPreheader = nullptr;
  308. ExitBlocks.clear();
  309. // If this is done before regalloc, only visit outer-most preheader-sporting
  310. // loops.
  311. if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
  312. Worklist.append(CurLoop->begin(), CurLoop->end());
  313. continue;
  314. }
  315. CurLoop->getExitBlocks(ExitBlocks);
  316. if (!PreRegAlloc)
  317. HoistRegionPostRA();
  318. else {
  319. // CSEMap is initialized for loop header when the first instruction is
  320. // being hoisted.
  321. MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
  322. FirstInLoop = true;
  323. HoistOutOfLoop(N);
  324. CSEMap.clear();
  325. if (SinkInstsToAvoidSpills)
  326. SinkIntoLoop();
  327. }
  328. }
  329. return Changed;
  330. }
  331. /// Return true if instruction stores to the specified frame.
  332. static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
  333. // Check mayStore before memory operands so that e.g. DBG_VALUEs will return
  334. // true since they have no memory operands.
  335. if (!MI->mayStore())
  336. return false;
  337. // If we lost memory operands, conservatively assume that the instruction
  338. // writes to all slots.
  339. if (MI->memoperands_empty())
  340. return true;
  341. for (const MachineMemOperand *MemOp : MI->memoperands()) {
  342. if (!MemOp->isStore() || !MemOp->getPseudoValue())
  343. continue;
  344. if (const FixedStackPseudoSourceValue *Value =
  345. dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
  346. if (Value->getFrameIndex() == FI)
  347. return true;
  348. }
  349. }
  350. return false;
  351. }
  352. /// Examine the instruction for potentai LICM candidate. Also
  353. /// gather register def and frame object update information.
  354. void MachineLICMBase::ProcessMI(MachineInstr *MI,
  355. BitVector &PhysRegDefs,
  356. BitVector &PhysRegClobbers,
  357. SmallSet<int, 32> &StoredFIs,
  358. SmallVectorImpl<CandidateInfo> &Candidates) {
  359. bool RuledOut = false;
  360. bool HasNonInvariantUse = false;
  361. unsigned Def = 0;
  362. for (const MachineOperand &MO : MI->operands()) {
  363. if (MO.isFI()) {
  364. // Remember if the instruction stores to the frame index.
  365. int FI = MO.getIndex();
  366. if (!StoredFIs.count(FI) &&
  367. MFI->isSpillSlotObjectIndex(FI) &&
  368. InstructionStoresToFI(MI, FI))
  369. StoredFIs.insert(FI);
  370. HasNonInvariantUse = true;
  371. continue;
  372. }
  373. // We can't hoist an instruction defining a physreg that is clobbered in
  374. // the loop.
  375. if (MO.isRegMask()) {
  376. PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
  377. continue;
  378. }
  379. if (!MO.isReg())
  380. continue;
  381. Register Reg = MO.getReg();
  382. if (!Reg)
  383. continue;
  384. assert(Register::isPhysicalRegister(Reg) &&
  385. "Not expecting virtual register!");
  386. if (!MO.isDef()) {
  387. if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
  388. // If it's using a non-loop-invariant register, then it's obviously not
  389. // safe to hoist.
  390. HasNonInvariantUse = true;
  391. continue;
  392. }
  393. if (MO.isImplicit()) {
  394. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
  395. PhysRegClobbers.set(*AI);
  396. if (!MO.isDead())
  397. // Non-dead implicit def? This cannot be hoisted.
  398. RuledOut = true;
  399. // No need to check if a dead implicit def is also defined by
  400. // another instruction.
  401. continue;
  402. }
  403. // FIXME: For now, avoid instructions with multiple defs, unless
  404. // it's a dead implicit def.
  405. if (Def)
  406. RuledOut = true;
  407. else
  408. Def = Reg;
  409. // If we have already seen another instruction that defines the same
  410. // register, then this is not safe. Two defs is indicated by setting a
  411. // PhysRegClobbers bit.
  412. for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
  413. if (PhysRegDefs.test(*AS))
  414. PhysRegClobbers.set(*AS);
  415. }
  416. // Need a second loop because MCRegAliasIterator can visit the same
  417. // register twice.
  418. for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS)
  419. PhysRegDefs.set(*AS);
  420. if (PhysRegClobbers.test(Reg))
  421. // MI defined register is seen defined by another instruction in
  422. // the loop, it cannot be a LICM candidate.
  423. RuledOut = true;
  424. }
  425. // Only consider reloads for now and remats which do not have register
  426. // operands. FIXME: Consider unfold load folding instructions.
  427. if (Def && !RuledOut) {
  428. int FI = std::numeric_limits<int>::min();
  429. if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
  430. (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
  431. Candidates.push_back(CandidateInfo(MI, Def, FI));
  432. }
  433. }
  434. /// Walk the specified region of the CFG and hoist loop invariants out to the
  435. /// preheader.
  436. void MachineLICMBase::HoistRegionPostRA() {
  437. MachineBasicBlock *Preheader = getCurPreheader();
  438. if (!Preheader)
  439. return;
  440. unsigned NumRegs = TRI->getNumRegs();
  441. BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
  442. BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
  443. SmallVector<CandidateInfo, 32> Candidates;
  444. SmallSet<int, 32> StoredFIs;
  445. // Walk the entire region, count number of defs for each register, and
  446. // collect potential LICM candidates.
  447. for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
  448. // If the header of the loop containing this basic block is a landing pad,
  449. // then don't try to hoist instructions out of this loop.
  450. const MachineLoop *ML = MLI->getLoopFor(BB);
  451. if (ML && ML->getHeader()->isEHPad()) continue;
  452. // Conservatively treat live-in's as an external def.
  453. // FIXME: That means a reload that're reused in successor block(s) will not
  454. // be LICM'ed.
  455. for (const auto &LI : BB->liveins()) {
  456. for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
  457. PhysRegDefs.set(*AI);
  458. }
  459. SpeculationState = SpeculateUnknown;
  460. for (MachineInstr &MI : *BB)
  461. ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
  462. }
  463. // Gather the registers read / clobbered by the terminator.
  464. BitVector TermRegs(NumRegs);
  465. MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
  466. if (TI != Preheader->end()) {
  467. for (const MachineOperand &MO : TI->operands()) {
  468. if (!MO.isReg())
  469. continue;
  470. Register Reg = MO.getReg();
  471. if (!Reg)
  472. continue;
  473. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
  474. TermRegs.set(*AI);
  475. }
  476. }
  477. // Now evaluate whether the potential candidates qualify.
  478. // 1. Check if the candidate defined register is defined by another
  479. // instruction in the loop.
  480. // 2. If the candidate is a load from stack slot (always true for now),
  481. // check if the slot is stored anywhere in the loop.
  482. // 3. Make sure candidate def should not clobber
  483. // registers read by the terminator. Similarly its def should not be
  484. // clobbered by the terminator.
  485. for (CandidateInfo &Candidate : Candidates) {
  486. if (Candidate.FI != std::numeric_limits<int>::min() &&
  487. StoredFIs.count(Candidate.FI))
  488. continue;
  489. unsigned Def = Candidate.Def;
  490. if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
  491. bool Safe = true;
  492. MachineInstr *MI = Candidate.MI;
  493. for (const MachineOperand &MO : MI->operands()) {
  494. if (!MO.isReg() || MO.isDef() || !MO.getReg())
  495. continue;
  496. Register Reg = MO.getReg();
  497. if (PhysRegDefs.test(Reg) ||
  498. PhysRegClobbers.test(Reg)) {
  499. // If it's using a non-loop-invariant register, then it's obviously
  500. // not safe to hoist.
  501. Safe = false;
  502. break;
  503. }
  504. }
  505. if (Safe)
  506. HoistPostRA(MI, Candidate.Def);
  507. }
  508. }
  509. }
  510. /// Add register 'Reg' to the livein sets of BBs in the current loop, and make
  511. /// sure it is not killed by any instructions in the loop.
  512. void MachineLICMBase::AddToLiveIns(MCRegister Reg) {
  513. for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
  514. if (!BB->isLiveIn(Reg))
  515. BB->addLiveIn(Reg);
  516. for (MachineInstr &MI : *BB) {
  517. for (MachineOperand &MO : MI.operands()) {
  518. if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
  519. if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
  520. MO.setIsKill(false);
  521. }
  522. }
  523. }
  524. }
  525. /// When an instruction is found to only use loop invariant operands that is
  526. /// safe to hoist, this instruction is called to do the dirty work.
  527. void MachineLICMBase::HoistPostRA(MachineInstr *MI, unsigned Def) {
  528. MachineBasicBlock *Preheader = getCurPreheader();
  529. // Now move the instructions to the predecessor, inserting it before any
  530. // terminator instructions.
  531. LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader)
  532. << " from " << printMBBReference(*MI->getParent()) << ": "
  533. << *MI);
  534. // Splice the instruction to the preheader.
  535. MachineBasicBlock *MBB = MI->getParent();
  536. Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
  537. // Since we are moving the instruction out of its basic block, we do not
  538. // retain its debug location. Doing so would degrade the debugging
  539. // experience and adversely affect the accuracy of profiling information.
  540. assert(!MI->isDebugInstr() && "Should not hoist debug inst");
  541. MI->setDebugLoc(DebugLoc());
  542. // Add register to livein list to all the BBs in the current loop since a
  543. // loop invariant must be kept live throughout the whole loop. This is
  544. // important to ensure later passes do not scavenge the def register.
  545. AddToLiveIns(Def);
  546. ++NumPostRAHoisted;
  547. Changed = true;
  548. }
  549. /// Check if this mbb is guaranteed to execute. If not then a load from this mbb
  550. /// may not be safe to hoist.
  551. bool MachineLICMBase::IsGuaranteedToExecute(MachineBasicBlock *BB) {
  552. if (SpeculationState != SpeculateUnknown)
  553. return SpeculationState == SpeculateFalse;
  554. if (BB != CurLoop->getHeader()) {
  555. // Check loop exiting blocks.
  556. SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
  557. CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
  558. for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
  559. if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
  560. SpeculationState = SpeculateTrue;
  561. return false;
  562. }
  563. }
  564. SpeculationState = SpeculateFalse;
  565. return true;
  566. }
  567. void MachineLICMBase::EnterScope(MachineBasicBlock *MBB) {
  568. LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
  569. // Remember livein register pressure.
  570. BackTrace.push_back(RegPressure);
  571. }
  572. void MachineLICMBase::ExitScope(MachineBasicBlock *MBB) {
  573. LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
  574. BackTrace.pop_back();
  575. }
  576. /// Destroy scope for the MBB that corresponds to the given dominator tree node
  577. /// if its a leaf or all of its children are done. Walk up the dominator tree to
  578. /// destroy ancestors which are now done.
  579. void MachineLICMBase::ExitScopeIfDone(MachineDomTreeNode *Node,
  580. DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
  581. DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
  582. if (OpenChildren[Node])
  583. return;
  584. // Pop scope.
  585. ExitScope(Node->getBlock());
  586. // Now traverse upwards to pop ancestors whose offsprings are all done.
  587. while (MachineDomTreeNode *Parent = ParentMap[Node]) {
  588. unsigned Left = --OpenChildren[Parent];
  589. if (Left != 0)
  590. break;
  591. ExitScope(Parent->getBlock());
  592. Node = Parent;
  593. }
  594. }
  595. /// Walk the specified loop in the CFG (defined by all blocks dominated by the
  596. /// specified header block, and that are in the current loop) in depth first
  597. /// order w.r.t the DominatorTree. This allows us to visit definitions before
  598. /// uses, allowing us to hoist a loop body in one pass without iteration.
  599. void MachineLICMBase::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
  600. MachineBasicBlock *Preheader = getCurPreheader();
  601. if (!Preheader)
  602. return;
  603. SmallVector<MachineDomTreeNode*, 32> Scopes;
  604. SmallVector<MachineDomTreeNode*, 8> WorkList;
  605. DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
  606. DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
  607. // Perform a DFS walk to determine the order of visit.
  608. WorkList.push_back(HeaderN);
  609. while (!WorkList.empty()) {
  610. MachineDomTreeNode *Node = WorkList.pop_back_val();
  611. assert(Node && "Null dominator tree node?");
  612. MachineBasicBlock *BB = Node->getBlock();
  613. // If the header of the loop containing this basic block is a landing pad,
  614. // then don't try to hoist instructions out of this loop.
  615. const MachineLoop *ML = MLI->getLoopFor(BB);
  616. if (ML && ML->getHeader()->isEHPad())
  617. continue;
  618. // If this subregion is not in the top level loop at all, exit.
  619. if (!CurLoop->contains(BB))
  620. continue;
  621. Scopes.push_back(Node);
  622. unsigned NumChildren = Node->getNumChildren();
  623. // Don't hoist things out of a large switch statement. This often causes
  624. // code to be hoisted that wasn't going to be executed, and increases
  625. // register pressure in a situation where it's likely to matter.
  626. if (BB->succ_size() >= 25)
  627. NumChildren = 0;
  628. OpenChildren[Node] = NumChildren;
  629. if (NumChildren) {
  630. // Add children in reverse order as then the next popped worklist node is
  631. // the first child of this node. This means we ultimately traverse the
  632. // DOM tree in exactly the same order as if we'd recursed.
  633. for (MachineDomTreeNode *Child : reverse(Node->children())) {
  634. ParentMap[Child] = Node;
  635. WorkList.push_back(Child);
  636. }
  637. }
  638. }
  639. if (Scopes.size() == 0)
  640. return;
  641. // Compute registers which are livein into the loop headers.
  642. RegSeen.clear();
  643. BackTrace.clear();
  644. InitRegPressure(Preheader);
  645. // Now perform LICM.
  646. for (MachineDomTreeNode *Node : Scopes) {
  647. MachineBasicBlock *MBB = Node->getBlock();
  648. EnterScope(MBB);
  649. // Process the block
  650. SpeculationState = SpeculateUnknown;
  651. for (MachineBasicBlock::iterator
  652. MII = MBB->begin(), E = MBB->end(); MII != E; ) {
  653. MachineBasicBlock::iterator NextMII = MII; ++NextMII;
  654. MachineInstr *MI = &*MII;
  655. if (!Hoist(MI, Preheader))
  656. UpdateRegPressure(MI);
  657. // If we have hoisted an instruction that may store, it can only be a
  658. // constant store.
  659. MII = NextMII;
  660. }
  661. // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
  662. ExitScopeIfDone(Node, OpenChildren, ParentMap);
  663. }
  664. }
  665. /// Sink instructions into loops if profitable. This especially tries to prevent
  666. /// register spills caused by register pressure if there is little to no
  667. /// overhead moving instructions into loops.
  668. void MachineLICMBase::SinkIntoLoop() {
  669. MachineBasicBlock *Preheader = getCurPreheader();
  670. if (!Preheader)
  671. return;
  672. SmallVector<MachineInstr *, 8> Candidates;
  673. for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
  674. I != Preheader->instr_end(); ++I) {
  675. // We need to ensure that we can safely move this instruction into the loop.
  676. // As such, it must not have side-effects, e.g. such as a call has.
  677. LLVM_DEBUG(dbgs() << "LICM: Analysing sink candidate: " << *I);
  678. if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I)) {
  679. LLVM_DEBUG(dbgs() << "LICM: Added as sink candidate.\n");
  680. Candidates.push_back(&*I);
  681. continue;
  682. }
  683. LLVM_DEBUG(dbgs() << "LICM: Not added as sink candidate.\n");
  684. }
  685. for (MachineInstr *I : Candidates) {
  686. const MachineOperand &MO = I->getOperand(0);
  687. if (!MO.isDef() || !MO.isReg() || !MO.getReg())
  688. continue;
  689. if (!MRI->hasOneDef(MO.getReg()))
  690. continue;
  691. bool CanSink = true;
  692. MachineBasicBlock *SinkBlock = nullptr;
  693. LLVM_DEBUG(dbgs() << "LICM: Try sinking: " << *I);
  694. for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
  695. LLVM_DEBUG(dbgs() << "LICM: Analysing use: "; MI.dump());
  696. // FIXME: Come up with a proper cost model that estimates whether sinking
  697. // the instruction (and thus possibly executing it on every loop
  698. // iteration) is more expensive than a register.
  699. // For now assumes that copies are cheap and thus almost always worth it.
  700. if (!MI.isCopy()) {
  701. CanSink = false;
  702. break;
  703. }
  704. if (!SinkBlock) {
  705. SinkBlock = MI.getParent();
  706. LLVM_DEBUG(dbgs() << "LICM: Setting sink block to: "
  707. << printMBBReference(*SinkBlock) << "\n");
  708. continue;
  709. }
  710. SinkBlock = DT->findNearestCommonDominator(SinkBlock, MI.getParent());
  711. if (!SinkBlock) {
  712. LLVM_DEBUG(dbgs() << "LICM: Can't find nearest dominator\n");
  713. CanSink = false;
  714. break;
  715. }
  716. LLVM_DEBUG(dbgs() << "LICM: Setting nearest common dom block: " <<
  717. printMBBReference(*SinkBlock) << "\n");
  718. }
  719. if (!CanSink) {
  720. LLVM_DEBUG(dbgs() << "LICM: Can't sink instruction.\n");
  721. continue;
  722. }
  723. if (!SinkBlock) {
  724. LLVM_DEBUG(dbgs() << "LICM: Not sinking, can't find sink block.\n");
  725. continue;
  726. }
  727. if (SinkBlock == Preheader) {
  728. LLVM_DEBUG(dbgs() << "LICM: Not sinking, sink block is the preheader\n");
  729. continue;
  730. }
  731. LLVM_DEBUG(dbgs() << "LICM: Sinking to " << printMBBReference(*SinkBlock)
  732. << " from " << printMBBReference(*I->getParent())
  733. << ": " << *I);
  734. SinkBlock->splice(SinkBlock->getFirstNonPHI(), Preheader, I);
  735. // The instruction is moved from its basic block, so do not retain the
  736. // debug information.
  737. assert(!I->isDebugInstr() && "Should not sink debug inst");
  738. I->setDebugLoc(DebugLoc());
  739. }
  740. }
  741. static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
  742. return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
  743. }
  744. /// Find all virtual register references that are liveout of the preheader to
  745. /// initialize the starting "register pressure". Note this does not count live
  746. /// through (livein but not used) registers.
  747. void MachineLICMBase::InitRegPressure(MachineBasicBlock *BB) {
  748. std::fill(RegPressure.begin(), RegPressure.end(), 0);
  749. // If the preheader has only a single predecessor and it ends with a
  750. // fallthrough or an unconditional branch, then scan its predecessor for live
  751. // defs as well. This happens whenever the preheader is created by splitting
  752. // the critical edge from the loop predecessor to the loop header.
  753. if (BB->pred_size() == 1) {
  754. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  755. SmallVector<MachineOperand, 4> Cond;
  756. if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
  757. InitRegPressure(*BB->pred_begin());
  758. }
  759. for (const MachineInstr &MI : *BB)
  760. UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
  761. }
  762. /// Update estimate of register pressure after the specified instruction.
  763. void MachineLICMBase::UpdateRegPressure(const MachineInstr *MI,
  764. bool ConsiderUnseenAsDef) {
  765. auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
  766. for (const auto &RPIdAndCost : Cost) {
  767. unsigned Class = RPIdAndCost.first;
  768. if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
  769. RegPressure[Class] = 0;
  770. else
  771. RegPressure[Class] += RPIdAndCost.second;
  772. }
  773. }
  774. /// Calculate the additional register pressure that the registers used in MI
  775. /// cause.
  776. ///
  777. /// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
  778. /// figure out which usages are live-ins.
  779. /// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
  780. DenseMap<unsigned, int>
  781. MachineLICMBase::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
  782. bool ConsiderUnseenAsDef) {
  783. DenseMap<unsigned, int> Cost;
  784. if (MI->isImplicitDef())
  785. return Cost;
  786. for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
  787. const MachineOperand &MO = MI->getOperand(i);
  788. if (!MO.isReg() || MO.isImplicit())
  789. continue;
  790. Register Reg = MO.getReg();
  791. if (!Register::isVirtualRegister(Reg))
  792. continue;
  793. // FIXME: It seems bad to use RegSeen only for some of these calculations.
  794. bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
  795. const TargetRegisterClass *RC = MRI->getRegClass(Reg);
  796. RegClassWeight W = TRI->getRegClassWeight(RC);
  797. int RCCost = 0;
  798. if (MO.isDef())
  799. RCCost = W.RegWeight;
  800. else {
  801. bool isKill = isOperandKill(MO, MRI);
  802. if (isNew && !isKill && ConsiderUnseenAsDef)
  803. // Haven't seen this, it must be a livein.
  804. RCCost = W.RegWeight;
  805. else if (!isNew && isKill)
  806. RCCost = -W.RegWeight;
  807. }
  808. if (RCCost == 0)
  809. continue;
  810. const int *PS = TRI->getRegClassPressureSets(RC);
  811. for (; *PS != -1; ++PS) {
  812. if (Cost.find(*PS) == Cost.end())
  813. Cost[*PS] = RCCost;
  814. else
  815. Cost[*PS] += RCCost;
  816. }
  817. }
  818. return Cost;
  819. }
  820. /// Return true if this machine instruction loads from global offset table or
  821. /// constant pool.
  822. static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
  823. assert(MI.mayLoad() && "Expected MI that loads!");
  824. // If we lost memory operands, conservatively assume that the instruction
  825. // reads from everything..
  826. if (MI.memoperands_empty())
  827. return true;
  828. for (MachineMemOperand *MemOp : MI.memoperands())
  829. if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
  830. if (PSV->isGOT() || PSV->isConstantPool())
  831. return true;
  832. return false;
  833. }
  834. // This function iterates through all the operands of the input store MI and
  835. // checks that each register operand statisfies isCallerPreservedPhysReg.
  836. // This means, the value being stored and the address where it is being stored
  837. // is constant throughout the body of the function (not including prologue and
  838. // epilogue). When called with an MI that isn't a store, it returns false.
  839. // A future improvement can be to check if the store registers are constant
  840. // throughout the loop rather than throughout the funtion.
  841. static bool isInvariantStore(const MachineInstr &MI,
  842. const TargetRegisterInfo *TRI,
  843. const MachineRegisterInfo *MRI) {
  844. bool FoundCallerPresReg = false;
  845. if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
  846. (MI.getNumOperands() == 0))
  847. return false;
  848. // Check that all register operands are caller-preserved physical registers.
  849. for (const MachineOperand &MO : MI.operands()) {
  850. if (MO.isReg()) {
  851. Register Reg = MO.getReg();
  852. // If operand is a virtual register, check if it comes from a copy of a
  853. // physical register.
  854. if (Register::isVirtualRegister(Reg))
  855. Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
  856. if (Register::isVirtualRegister(Reg))
  857. return false;
  858. if (!TRI->isCallerPreservedPhysReg(Reg.asMCReg(), *MI.getMF()))
  859. return false;
  860. else
  861. FoundCallerPresReg = true;
  862. } else if (!MO.isImm()) {
  863. return false;
  864. }
  865. }
  866. return FoundCallerPresReg;
  867. }
  868. // Return true if the input MI is a copy instruction that feeds an invariant
  869. // store instruction. This means that the src of the copy has to satisfy
  870. // isCallerPreservedPhysReg and atleast one of it's users should satisfy
  871. // isInvariantStore.
  872. static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
  873. const MachineRegisterInfo *MRI,
  874. const TargetRegisterInfo *TRI) {
  875. // FIXME: If targets would like to look through instructions that aren't
  876. // pure copies, this can be updated to a query.
  877. if (!MI.isCopy())
  878. return false;
  879. const MachineFunction *MF = MI.getMF();
  880. // Check that we are copying a constant physical register.
  881. Register CopySrcReg = MI.getOperand(1).getReg();
  882. if (Register::isVirtualRegister(CopySrcReg))
  883. return false;
  884. if (!TRI->isCallerPreservedPhysReg(CopySrcReg.asMCReg(), *MF))
  885. return false;
  886. Register CopyDstReg = MI.getOperand(0).getReg();
  887. // Check if any of the uses of the copy are invariant stores.
  888. assert(Register::isVirtualRegister(CopyDstReg) &&
  889. "copy dst is not a virtual reg");
  890. for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
  891. if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
  892. return true;
  893. }
  894. return false;
  895. }
  896. /// Returns true if the instruction may be a suitable candidate for LICM.
  897. /// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
  898. bool MachineLICMBase::IsLICMCandidate(MachineInstr &I) {
  899. // Check if it's safe to move the instruction.
  900. bool DontMoveAcrossStore = true;
  901. if ((!I.isSafeToMove(AA, DontMoveAcrossStore)) &&
  902. !(HoistConstStores && isInvariantStore(I, TRI, MRI))) {
  903. LLVM_DEBUG(dbgs() << "LICM: Instruction not safe to move.\n");
  904. return false;
  905. }
  906. // If it is load then check if it is guaranteed to execute by making sure that
  907. // it dominates all exiting blocks. If it doesn't, then there is a path out of
  908. // the loop which does not execute this load, so we can't hoist it. Loads
  909. // from constant memory are not safe to speculate all the time, for example
  910. // indexed load from a jump table.
  911. // Stores and side effects are already checked by isSafeToMove.
  912. if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
  913. !IsGuaranteedToExecute(I.getParent())) {
  914. LLVM_DEBUG(dbgs() << "LICM: Load not guaranteed to execute.\n");
  915. return false;
  916. }
  917. // Convergent attribute has been used on operations that involve inter-thread
  918. // communication which results are implicitly affected by the enclosing
  919. // control flows. It is not safe to hoist or sink such operations across
  920. // control flow.
  921. if (I.isConvergent())
  922. return false;
  923. return true;
  924. }
  925. /// Returns true if the instruction is loop invariant.
  926. bool MachineLICMBase::IsLoopInvariantInst(MachineInstr &I) {
  927. if (!IsLICMCandidate(I)) {
  928. LLVM_DEBUG(dbgs() << "LICM: Instruction not a LICM candidate\n");
  929. return false;
  930. }
  931. return CurLoop->isLoopInvariant(I);
  932. }
  933. /// Return true if the specified instruction is used by a phi node and hoisting
  934. /// it could cause a copy to be inserted.
  935. bool MachineLICMBase::HasLoopPHIUse(const MachineInstr *MI) const {
  936. SmallVector<const MachineInstr*, 8> Work(1, MI);
  937. do {
  938. MI = Work.pop_back_val();
  939. for (const MachineOperand &MO : MI->operands()) {
  940. if (!MO.isReg() || !MO.isDef())
  941. continue;
  942. Register Reg = MO.getReg();
  943. if (!Register::isVirtualRegister(Reg))
  944. continue;
  945. for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
  946. // A PHI may cause a copy to be inserted.
  947. if (UseMI.isPHI()) {
  948. // A PHI inside the loop causes a copy because the live range of Reg is
  949. // extended across the PHI.
  950. if (CurLoop->contains(&UseMI))
  951. return true;
  952. // A PHI in an exit block can cause a copy to be inserted if the PHI
  953. // has multiple predecessors in the loop with different values.
  954. // For now, approximate by rejecting all exit blocks.
  955. if (isExitBlock(UseMI.getParent()))
  956. return true;
  957. continue;
  958. }
  959. // Look past copies as well.
  960. if (UseMI.isCopy() && CurLoop->contains(&UseMI))
  961. Work.push_back(&UseMI);
  962. }
  963. }
  964. } while (!Work.empty());
  965. return false;
  966. }
  967. /// Compute operand latency between a def of 'Reg' and an use in the current
  968. /// loop, return true if the target considered it high.
  969. bool MachineLICMBase::HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
  970. Register Reg) const {
  971. if (MRI->use_nodbg_empty(Reg))
  972. return false;
  973. for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
  974. if (UseMI.isCopyLike())
  975. continue;
  976. if (!CurLoop->contains(UseMI.getParent()))
  977. continue;
  978. for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
  979. const MachineOperand &MO = UseMI.getOperand(i);
  980. if (!MO.isReg() || !MO.isUse())
  981. continue;
  982. Register MOReg = MO.getReg();
  983. if (MOReg != Reg)
  984. continue;
  985. if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
  986. return true;
  987. }
  988. // Only look at the first in loop use.
  989. break;
  990. }
  991. return false;
  992. }
  993. /// Return true if the instruction is marked "cheap" or the operand latency
  994. /// between its def and a use is one or less.
  995. bool MachineLICMBase::IsCheapInstruction(MachineInstr &MI) const {
  996. if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
  997. return true;
  998. bool isCheap = false;
  999. unsigned NumDefs = MI.getDesc().getNumDefs();
  1000. for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
  1001. MachineOperand &DefMO = MI.getOperand(i);
  1002. if (!DefMO.isReg() || !DefMO.isDef())
  1003. continue;
  1004. --NumDefs;
  1005. Register Reg = DefMO.getReg();
  1006. if (Register::isPhysicalRegister(Reg))
  1007. continue;
  1008. if (!TII->hasLowDefLatency(SchedModel, MI, i))
  1009. return false;
  1010. isCheap = true;
  1011. }
  1012. return isCheap;
  1013. }
  1014. /// Visit BBs from header to current BB, check if hoisting an instruction of the
  1015. /// given cost matrix can cause high register pressure.
  1016. bool
  1017. MachineLICMBase::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
  1018. bool CheapInstr) {
  1019. for (const auto &RPIdAndCost : Cost) {
  1020. if (RPIdAndCost.second <= 0)
  1021. continue;
  1022. unsigned Class = RPIdAndCost.first;
  1023. int Limit = RegLimit[Class];
  1024. // Don't hoist cheap instructions if they would increase register pressure,
  1025. // even if we're under the limit.
  1026. if (CheapInstr && !HoistCheapInsts)
  1027. return true;
  1028. for (const auto &RP : BackTrace)
  1029. if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
  1030. return true;
  1031. }
  1032. return false;
  1033. }
  1034. /// Traverse the back trace from header to the current block and update their
  1035. /// register pressures to reflect the effect of hoisting MI from the current
  1036. /// block to the preheader.
  1037. void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr *MI) {
  1038. // First compute the 'cost' of the instruction, i.e. its contribution
  1039. // to register pressure.
  1040. auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
  1041. /*ConsiderUnseenAsDef=*/false);
  1042. // Update register pressure of blocks from loop header to current block.
  1043. for (auto &RP : BackTrace)
  1044. for (const auto &RPIdAndCost : Cost)
  1045. RP[RPIdAndCost.first] += RPIdAndCost.second;
  1046. }
  1047. /// Return true if it is potentially profitable to hoist the given loop
  1048. /// invariant.
  1049. bool MachineLICMBase::IsProfitableToHoist(MachineInstr &MI) {
  1050. if (MI.isImplicitDef())
  1051. return true;
  1052. // Besides removing computation from the loop, hoisting an instruction has
  1053. // these effects:
  1054. //
  1055. // - The value defined by the instruction becomes live across the entire
  1056. // loop. This increases register pressure in the loop.
  1057. //
  1058. // - If the value is used by a PHI in the loop, a copy will be required for
  1059. // lowering the PHI after extending the live range.
  1060. //
  1061. // - When hoisting the last use of a value in the loop, that value no longer
  1062. // needs to be live in the loop. This lowers register pressure in the loop.
  1063. if (HoistConstStores && isCopyFeedingInvariantStore(MI, MRI, TRI))
  1064. return true;
  1065. bool CheapInstr = IsCheapInstruction(MI);
  1066. bool CreatesCopy = HasLoopPHIUse(&MI);
  1067. // Don't hoist a cheap instruction if it would create a copy in the loop.
  1068. if (CheapInstr && CreatesCopy) {
  1069. LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
  1070. return false;
  1071. }
  1072. // Rematerializable instructions should always be hoisted since the register
  1073. // allocator can just pull them down again when needed.
  1074. if (TII->isTriviallyReMaterializable(MI, AA))
  1075. return true;
  1076. // FIXME: If there are long latency loop-invariant instructions inside the
  1077. // loop at this point, why didn't the optimizer's LICM hoist them?
  1078. for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
  1079. const MachineOperand &MO = MI.getOperand(i);
  1080. if (!MO.isReg() || MO.isImplicit())
  1081. continue;
  1082. Register Reg = MO.getReg();
  1083. if (!Register::isVirtualRegister(Reg))
  1084. continue;
  1085. if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
  1086. LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI);
  1087. ++NumHighLatency;
  1088. return true;
  1089. }
  1090. }
  1091. // Estimate register pressure to determine whether to LICM the instruction.
  1092. // In low register pressure situation, we can be more aggressive about
  1093. // hoisting. Also, favors hoisting long latency instructions even in
  1094. // moderately high pressure situation.
  1095. // Cheap instructions will only be hoisted if they don't increase register
  1096. // pressure at all.
  1097. auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
  1098. /*ConsiderUnseenAsDef=*/false);
  1099. // Visit BBs from header to current BB, if hoisting this doesn't cause
  1100. // high register pressure, then it's safe to proceed.
  1101. if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
  1102. LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
  1103. ++NumLowRP;
  1104. return true;
  1105. }
  1106. // Don't risk increasing register pressure if it would create copies.
  1107. if (CreatesCopy) {
  1108. LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
  1109. return false;
  1110. }
  1111. // Do not "speculate" in high register pressure situation. If an
  1112. // instruction is not guaranteed to be executed in the loop, it's best to be
  1113. // conservative.
  1114. if (AvoidSpeculation &&
  1115. (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
  1116. LLVM_DEBUG(dbgs() << "Won't speculate: " << MI);
  1117. return false;
  1118. }
  1119. // High register pressure situation, only hoist if the instruction is going
  1120. // to be remat'ed.
  1121. if (!TII->isTriviallyReMaterializable(MI, AA) &&
  1122. !MI.isDereferenceableInvariantLoad(AA)) {
  1123. LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
  1124. return false;
  1125. }
  1126. return true;
  1127. }
  1128. /// Unfold a load from the given machineinstr if the load itself could be
  1129. /// hoisted. Return the unfolded and hoistable load, or null if the load
  1130. /// couldn't be unfolded or if it wouldn't be hoistable.
  1131. MachineInstr *MachineLICMBase::ExtractHoistableLoad(MachineInstr *MI) {
  1132. // Don't unfold simple loads.
  1133. if (MI->canFoldAsLoad())
  1134. return nullptr;
  1135. // If not, we may be able to unfold a load and hoist that.
  1136. // First test whether the instruction is loading from an amenable
  1137. // memory location.
  1138. if (!MI->isDereferenceableInvariantLoad(AA))
  1139. return nullptr;
  1140. // Next determine the register class for a temporary register.
  1141. unsigned LoadRegIndex;
  1142. unsigned NewOpc =
  1143. TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
  1144. /*UnfoldLoad=*/true,
  1145. /*UnfoldStore=*/false,
  1146. &LoadRegIndex);
  1147. if (NewOpc == 0) return nullptr;
  1148. const MCInstrDesc &MID = TII->get(NewOpc);
  1149. MachineFunction &MF = *MI->getMF();
  1150. const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
  1151. // Ok, we're unfolding. Create a temporary register and do the unfold.
  1152. Register Reg = MRI->createVirtualRegister(RC);
  1153. SmallVector<MachineInstr *, 2> NewMIs;
  1154. bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
  1155. /*UnfoldLoad=*/true,
  1156. /*UnfoldStore=*/false, NewMIs);
  1157. (void)Success;
  1158. assert(Success &&
  1159. "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
  1160. "succeeded!");
  1161. assert(NewMIs.size() == 2 &&
  1162. "Unfolded a load into multiple instructions!");
  1163. MachineBasicBlock *MBB = MI->getParent();
  1164. MachineBasicBlock::iterator Pos = MI;
  1165. MBB->insert(Pos, NewMIs[0]);
  1166. MBB->insert(Pos, NewMIs[1]);
  1167. // If unfolding produced a load that wasn't loop-invariant or profitable to
  1168. // hoist, discard the new instructions and bail.
  1169. if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
  1170. NewMIs[0]->eraseFromParent();
  1171. NewMIs[1]->eraseFromParent();
  1172. return nullptr;
  1173. }
  1174. // Update register pressure for the unfolded instruction.
  1175. UpdateRegPressure(NewMIs[1]);
  1176. // Otherwise we successfully unfolded a load that we can hoist.
  1177. // Update the call site info.
  1178. if (MI->shouldUpdateCallSiteInfo())
  1179. MF.eraseCallSiteInfo(MI);
  1180. MI->eraseFromParent();
  1181. return NewMIs[0];
  1182. }
  1183. /// Initialize the CSE map with instructions that are in the current loop
  1184. /// preheader that may become duplicates of instructions that are hoisted
  1185. /// out of the loop.
  1186. void MachineLICMBase::InitCSEMap(MachineBasicBlock *BB) {
  1187. for (MachineInstr &MI : *BB)
  1188. CSEMap[MI.getOpcode()].push_back(&MI);
  1189. }
  1190. /// Find an instruction amount PrevMIs that is a duplicate of MI.
  1191. /// Return this instruction if it's found.
  1192. MachineInstr *
  1193. MachineLICMBase::LookForDuplicate(const MachineInstr *MI,
  1194. std::vector<MachineInstr *> &PrevMIs) {
  1195. for (MachineInstr *PrevMI : PrevMIs)
  1196. if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
  1197. return PrevMI;
  1198. return nullptr;
  1199. }
  1200. /// Given a LICM'ed instruction, look for an instruction on the preheader that
  1201. /// computes the same value. If it's found, do a RAU on with the definition of
  1202. /// the existing instruction rather than hoisting the instruction to the
  1203. /// preheader.
  1204. bool MachineLICMBase::EliminateCSE(
  1205. MachineInstr *MI,
  1206. DenseMap<unsigned, std::vector<MachineInstr *>>::iterator &CI) {
  1207. // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
  1208. // the undef property onto uses.
  1209. if (CI == CSEMap.end() || MI->isImplicitDef())
  1210. return false;
  1211. if (MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
  1212. LLVM_DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
  1213. // Replace virtual registers defined by MI by their counterparts defined
  1214. // by Dup.
  1215. SmallVector<unsigned, 2> Defs;
  1216. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  1217. const MachineOperand &MO = MI->getOperand(i);
  1218. // Physical registers may not differ here.
  1219. assert((!MO.isReg() || MO.getReg() == 0 ||
  1220. !Register::isPhysicalRegister(MO.getReg()) ||
  1221. MO.getReg() == Dup->getOperand(i).getReg()) &&
  1222. "Instructions with different phys regs are not identical!");
  1223. if (MO.isReg() && MO.isDef() &&
  1224. !Register::isPhysicalRegister(MO.getReg()))
  1225. Defs.push_back(i);
  1226. }
  1227. SmallVector<const TargetRegisterClass*, 2> OrigRCs;
  1228. for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
  1229. unsigned Idx = Defs[i];
  1230. Register Reg = MI->getOperand(Idx).getReg();
  1231. Register DupReg = Dup->getOperand(Idx).getReg();
  1232. OrigRCs.push_back(MRI->getRegClass(DupReg));
  1233. if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
  1234. // Restore old RCs if more than one defs.
  1235. for (unsigned j = 0; j != i; ++j)
  1236. MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
  1237. return false;
  1238. }
  1239. }
  1240. for (unsigned Idx : Defs) {
  1241. Register Reg = MI->getOperand(Idx).getReg();
  1242. Register DupReg = Dup->getOperand(Idx).getReg();
  1243. MRI->replaceRegWith(Reg, DupReg);
  1244. MRI->clearKillFlags(DupReg);
  1245. // Clear Dup dead flag if any, we reuse it for Reg.
  1246. if (!MRI->use_nodbg_empty(DupReg))
  1247. Dup->getOperand(Idx).setIsDead(false);
  1248. }
  1249. MI->eraseFromParent();
  1250. ++NumCSEed;
  1251. return true;
  1252. }
  1253. return false;
  1254. }
  1255. /// Return true if the given instruction will be CSE'd if it's hoisted out of
  1256. /// the loop.
  1257. bool MachineLICMBase::MayCSE(MachineInstr *MI) {
  1258. unsigned Opcode = MI->getOpcode();
  1259. DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
  1260. CSEMap.find(Opcode);
  1261. // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
  1262. // the undef property onto uses.
  1263. if (CI == CSEMap.end() || MI->isImplicitDef())
  1264. return false;
  1265. return LookForDuplicate(MI, CI->second) != nullptr;
  1266. }
  1267. /// When an instruction is found to use only loop invariant operands
  1268. /// that are safe to hoist, this instruction is called to do the dirty work.
  1269. /// It returns true if the instruction is hoisted.
  1270. bool MachineLICMBase::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
  1271. MachineBasicBlock *SrcBlock = MI->getParent();
  1272. // Disable the instruction hoisting due to block hotness
  1273. if ((DisableHoistingToHotterBlocks == UseBFI::All ||
  1274. (DisableHoistingToHotterBlocks == UseBFI::PGO && HasProfileData)) &&
  1275. isTgtHotterThanSrc(SrcBlock, Preheader)) {
  1276. ++NumNotHoistedDueToHotness;
  1277. return false;
  1278. }
  1279. // First check whether we should hoist this instruction.
  1280. if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
  1281. // If not, try unfolding a hoistable load.
  1282. MI = ExtractHoistableLoad(MI);
  1283. if (!MI) return false;
  1284. }
  1285. // If we have hoisted an instruction that may store, it can only be a constant
  1286. // store.
  1287. if (MI->mayStore())
  1288. NumStoreConst++;
  1289. // Now move the instructions to the predecessor, inserting it before any
  1290. // terminator instructions.
  1291. LLVM_DEBUG({
  1292. dbgs() << "Hoisting " << *MI;
  1293. if (MI->getParent()->getBasicBlock())
  1294. dbgs() << " from " << printMBBReference(*MI->getParent());
  1295. if (Preheader->getBasicBlock())
  1296. dbgs() << " to " << printMBBReference(*Preheader);
  1297. dbgs() << "\n";
  1298. });
  1299. // If this is the first instruction being hoisted to the preheader,
  1300. // initialize the CSE map with potential common expressions.
  1301. if (FirstInLoop) {
  1302. InitCSEMap(Preheader);
  1303. FirstInLoop = false;
  1304. }
  1305. // Look for opportunity to CSE the hoisted instruction.
  1306. unsigned Opcode = MI->getOpcode();
  1307. DenseMap<unsigned, std::vector<MachineInstr *>>::iterator CI =
  1308. CSEMap.find(Opcode);
  1309. if (!EliminateCSE(MI, CI)) {
  1310. // Otherwise, splice the instruction to the preheader.
  1311. Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
  1312. // Since we are moving the instruction out of its basic block, we do not
  1313. // retain its debug location. Doing so would degrade the debugging
  1314. // experience and adversely affect the accuracy of profiling information.
  1315. assert(!MI->isDebugInstr() && "Should not hoist debug inst");
  1316. MI->setDebugLoc(DebugLoc());
  1317. // Update register pressure for BBs from header to this block.
  1318. UpdateBackTraceRegPressure(MI);
  1319. // Clear the kill flags of any register this instruction defines,
  1320. // since they may need to be live throughout the entire loop
  1321. // rather than just live for part of it.
  1322. for (MachineOperand &MO : MI->operands())
  1323. if (MO.isReg() && MO.isDef() && !MO.isDead())
  1324. MRI->clearKillFlags(MO.getReg());
  1325. // Add to the CSE map.
  1326. if (CI != CSEMap.end())
  1327. CI->second.push_back(MI);
  1328. else
  1329. CSEMap[Opcode].push_back(MI);
  1330. }
  1331. ++NumHoisted;
  1332. Changed = true;
  1333. return true;
  1334. }
  1335. /// Get the preheader for the current loop, splitting a critical edge if needed.
  1336. MachineBasicBlock *MachineLICMBase::getCurPreheader() {
  1337. // Determine the block to which to hoist instructions. If we can't find a
  1338. // suitable loop predecessor, we can't do any hoisting.
  1339. // If we've tried to get a preheader and failed, don't try again.
  1340. if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
  1341. return nullptr;
  1342. if (!CurPreheader) {
  1343. CurPreheader = CurLoop->getLoopPreheader();
  1344. if (!CurPreheader) {
  1345. MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
  1346. if (!Pred) {
  1347. CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
  1348. return nullptr;
  1349. }
  1350. CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
  1351. if (!CurPreheader) {
  1352. CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
  1353. return nullptr;
  1354. }
  1355. }
  1356. }
  1357. return CurPreheader;
  1358. }
  1359. /// Is the target basic block at least "BlockFrequencyRatioThreshold"
  1360. /// times hotter than the source basic block.
  1361. bool MachineLICMBase::isTgtHotterThanSrc(MachineBasicBlock *SrcBlock,
  1362. MachineBasicBlock *TgtBlock) {
  1363. // Parse source and target basic block frequency from MBFI
  1364. uint64_t SrcBF = MBFI->getBlockFreq(SrcBlock).getFrequency();
  1365. uint64_t DstBF = MBFI->getBlockFreq(TgtBlock).getFrequency();
  1366. // Disable the hoisting if source block frequency is zero
  1367. if (!SrcBF)
  1368. return true;
  1369. double Ratio = (double)DstBF / SrcBF;
  1370. // Compare the block frequency ratio with the threshold
  1371. return Ratio > BlockFrequencyRatioThreshold;
  1372. }