1 //===- RegAllocGreedy.cpp - greedy register allocator ---------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the RAGreedy function pass for register allocation in
12 //===----------------------------------------------------------------------===//
14 #include "AllocationOrder.h"
15 #include "InterferenceCache.h"
16 #include "LiveDebugVariables.h"
17 #include "RegAllocBase.h"
18 #include "SpillPlacement.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/IndexedMap.h"
24 #include "llvm/ADT/MapVector.h"
25 #include "llvm/ADT/SetVector.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/Analysis/AliasAnalysis.h"
32 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
33 #include "llvm/CodeGen/CalcSpillWeights.h"
34 #include "llvm/CodeGen/EdgeBundles.h"
35 #include "llvm/CodeGen/LiveInterval.h"
36 #include "llvm/CodeGen/LiveIntervalUnion.h"
37 #include "llvm/CodeGen/LiveIntervals.h"
38 #include "llvm/CodeGen/LiveRangeEdit.h"
39 #include "llvm/CodeGen/LiveRegMatrix.h"
40 #include "llvm/CodeGen/LiveStacks.h"
41 #include "llvm/CodeGen/MachineBasicBlock.h"
42 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
43 #include "llvm/CodeGen/MachineDominators.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineFunctionPass.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineLoopInfo.h"
49 #include "llvm/CodeGen/MachineOperand.h"
50 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/RegAllocRegistry.h"
53 #include "llvm/CodeGen/RegisterClassInfo.h"
54 #include "llvm/CodeGen/SlotIndexes.h"
55 #include "llvm/CodeGen/Spiller.h"
56 #include "llvm/CodeGen/TargetInstrInfo.h"
57 #include "llvm/CodeGen/TargetRegisterInfo.h"
58 #include "llvm/CodeGen/TargetSubtargetInfo.h"
59 #include "llvm/CodeGen/VirtRegMap.h"
60 #include "llvm/IR/Function.h"
61 #include "llvm/IR/LLVMContext.h"
62 #include "llvm/MC/MCRegisterInfo.h"
63 #include "llvm/Pass.h"
64 #include "llvm/Support/BlockFrequency.h"
65 #include "llvm/Support/BranchProbability.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/MathExtras.h"
69 #include "llvm/Support/Timer.h"
70 #include "llvm/Support/raw_ostream.h"
71 #include "llvm/Target/TargetMachine.h"
82 #define DEBUG_TYPE "regalloc"
84 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
85 STATISTIC(NumLocalSplits, "Number of split local live ranges");
86 STATISTIC(NumEvicted, "Number of interferences evicted");
88 static cl::opt<SplitEditor::ComplementSpillMode> SplitSpillMode(
89 "split-spill-mode", cl::Hidden,
90 cl::desc("Spill mode for splitting live ranges"),
91 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
92 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
93 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed")),
94 cl::init(SplitEditor::SM_Speed));
96 static cl::opt<unsigned>
97 LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
98 cl::desc("Last chance recoloring max depth"),
101 static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
102 "lcr-max-interf", cl::Hidden,
103 cl::desc("Last chance recoloring maximum number of considered"
104 " interference at a time"),
107 static cl::opt<bool> ExhaustiveSearch(
108 "exhaustive-register-search", cl::NotHidden,
109 cl::desc("Exhaustive Search for registers bypassing the depth "
110 "and interference cutoffs of last chance recoloring"),
113 static cl::opt<bool> EnableLocalReassignment(
114 "enable-local-reassign", cl::Hidden,
115 cl::desc("Local reassignment can yield better allocation decisions, but "
116 "may be compile time intensive"),
119 static cl::opt<bool> EnableDeferredSpilling(
120 "enable-deferred-spilling", cl::Hidden,
121 cl::desc("Instead of spilling a variable right away, defer the actual "
122 "code insertion to the end of the allocation. That way the "
123 "allocator might still find a suitable coloring for this "
124 "variable because of other evicted variables."),
127 // FIXME: Find a good default for this flag and remove the flag.
128 static cl::opt<unsigned>
129 CSRFirstTimeCost("regalloc-csr-first-time-cost",
130 cl::desc("Cost for first time use of callee-saved register."),
131 cl::init(0), cl::Hidden);
133 static cl::opt<bool> ConsiderLocalIntervalCost(
134 "consider-local-interval-cost", cl::Hidden,
135 cl::desc("Consider the cost of local intervals created by a split "
136 "candidate when choosing the best split candidate."),
139 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
140 createGreedyRegisterAllocator);
144 class RAGreedy : public MachineFunctionPass,
146 private LiveRangeEdit::Delegate {
147 // Convenient shortcuts.
148 using PQueue = std::priority_queue<std::pair<unsigned, unsigned>>;
149 using SmallLISet = SmallPtrSet<LiveInterval *, 4>;
150 using SmallVirtRegSet = SmallSet<unsigned, 16>;
155 // Shortcuts to some useful interface.
156 const TargetInstrInfo *TII;
157 const TargetRegisterInfo *TRI;
158 RegisterClassInfo RCI;
161 SlotIndexes *Indexes;
162 MachineBlockFrequencyInfo *MBFI;
163 MachineDominatorTree *DomTree;
164 MachineLoopInfo *Loops;
165 MachineOptimizationRemarkEmitter *ORE;
166 EdgeBundles *Bundles;
167 SpillPlacement *SpillPlacer;
168 LiveDebugVariables *DebugVars;
172 std::unique_ptr<Spiller> SpillerInstance;
174 unsigned NextCascade;
176 // Live ranges pass through a number of stages as we try to allocate them.
177 // Some of the stages may also create new live ranges:
179 // - Region splitting.
180 // - Per-block splitting.
181 // - Local splitting.
184 // Ranges produced by one of the stages skip the previous stages when they are
185 // dequeued. This improves performance because we can skip interference checks
186 // that are unlikely to give any results. It also guarantees that the live
187 // range splitting algorithm terminates, something that is otherwise hard to
189 enum LiveRangeStage {
190 /// Newly created live range that has never been queued.
193 /// Only attempt assignment and eviction. Then requeue as RS_Split.
196 /// Attempt live range splitting if assignment is impossible.
199 /// Attempt more aggressive live range splitting that is guaranteed to make
200 /// progress. This is used for split products that may not be making
204 /// Live range will be spilled. No more splitting will be attempted.
208 /// Live range is in memory. Because of other evictions, it might get moved
209 /// in a register in the end.
212 /// There is nothing more we can do to this live range. Abort compilation
213 /// if it can't be assigned.
217 // Enum CutOffStage to keep a track whether the register allocation failed
218 // because of the cutoffs encountered in last chance recoloring.
219 // Note: This is used as bitmask. New value should be next power of 2.
221 // No cutoffs encountered
224 // lcr-max-depth cutoff encountered
227 // lcr-max-interf cutoff encountered
234 static const char *const StageName[];
237 // RegInfo - Keep additional information about each live range.
239 LiveRangeStage Stage = RS_New;
241 // Cascade - Eviction loop prevention. See canEvictInterference().
242 unsigned Cascade = 0;
247 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
249 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
250 return ExtraRegInfo[VirtReg.reg].Stage;
253 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
254 ExtraRegInfo.resize(MRI->getNumVirtRegs());
255 ExtraRegInfo[VirtReg.reg].Stage = Stage;
258 template<typename Iterator>
259 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
260 ExtraRegInfo.resize(MRI->getNumVirtRegs());
261 for (;Begin != End; ++Begin) {
262 unsigned Reg = *Begin;
263 if (ExtraRegInfo[Reg].Stage == RS_New)
264 ExtraRegInfo[Reg].Stage = NewStage;
268 /// Cost of evicting interference.
269 struct EvictionCost {
270 unsigned BrokenHints = 0; ///< Total number of broken hints.
271 float MaxWeight = 0; ///< Maximum spill weight evicted.
273 EvictionCost() = default;
275 bool isMax() const { return BrokenHints == ~0u; }
277 void setMax() { BrokenHints = ~0u; }
279 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
281 bool operator<(const EvictionCost &O) const {
282 return std::tie(BrokenHints, MaxWeight) <
283 std::tie(O.BrokenHints, O.MaxWeight);
287 /// EvictionTrack - Keeps track of past evictions in order to optimize region
289 class EvictionTrack {
293 std::pair<unsigned /* evictor */, unsigned /* physreg */>;
294 using EvicteeInfo = llvm::DenseMap<unsigned /* evictee */, EvictorInfo>;
297 /// Each Vreg that has been evicted in the last stage of selectOrSplit will
298 /// be mapped to the evictor Vreg and the PhysReg it was evicted from.
299 EvicteeInfo Evictees;
302 /// Clear all eviction information.
303 void clear() { Evictees.clear(); }
305 /// Clear eviction information for the given evictee Vreg.
306 /// E.g. when Vreg get's a new allocation, the old eviction info is no
308 /// \param Evictee The evictee Vreg for whom we want to clear collected
310 void clearEvicteeInfo(unsigned Evictee) { Evictees.erase(Evictee); }
312 /// Track new eviction.
313 /// The Evictor vreg has evicted the Evictee vreg from Physreg.
314 /// \param PhysReg The physical register Evictee was evicted from.
315 /// \param Evictor The evictor Vreg that evicted Evictee.
316 /// \param Evictee The evictee Vreg.
317 void addEviction(unsigned PhysReg, unsigned Evictor, unsigned Evictee) {
318 Evictees[Evictee].first = Evictor;
319 Evictees[Evictee].second = PhysReg;
322 /// Return the Evictor Vreg which evicted Evictee Vreg from PhysReg.
323 /// \param Evictee The evictee vreg.
324 /// \return The Evictor vreg which evicted Evictee vreg from PhysReg. 0 if
325 /// nobody has evicted Evictee from PhysReg.
326 EvictorInfo getEvictor(unsigned Evictee) {
327 if (Evictees.count(Evictee)) {
328 return Evictees[Evictee];
331 return EvictorInfo(0, 0);
335 // Keeps track of past evictions in order to optimize region split decision.
336 EvictionTrack LastEvicted;
339 std::unique_ptr<SplitAnalysis> SA;
340 std::unique_ptr<SplitEditor> SE;
342 /// Cached per-block interference maps
343 InterferenceCache IntfCache;
345 /// All basic blocks where the current register has uses.
346 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
348 /// Global live range splitting candidate info.
349 struct GlobalSplitCandidate {
350 // Register intended for assignment, or 0.
353 // SplitKit interval index for this candidate.
356 // Interference for PhysReg.
357 InterferenceCache::Cursor Intf;
359 // Bundles where this candidate should be live.
360 BitVector LiveBundles;
361 SmallVector<unsigned, 8> ActiveBlocks;
363 void reset(InterferenceCache &Cache, unsigned Reg) {
366 Intf.setPhysReg(Cache, Reg);
368 ActiveBlocks.clear();
371 // Set B[i] = C for every live bundle where B[i] was NoCand.
372 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
374 for (unsigned i : LiveBundles.set_bits())
375 if (B[i] == NoCand) {
383 /// Candidate info for each PhysReg in AllocationOrder.
384 /// This vector never shrinks, but grows to the size of the largest register
386 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
388 enum : unsigned { NoCand = ~0u };
390 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
391 /// NoCand which indicates the stack interval.
392 SmallVector<unsigned, 32> BundleCand;
394 /// Callee-save register cost, calculated once per machine function.
395 BlockFrequency CSRCost;
397 /// Run or not the local reassignment heuristic. This information is
398 /// obtained from the TargetSubtargetInfo.
399 bool EnableLocalReassign;
401 /// Enable or not the consideration of the cost of local intervals created
402 /// by a split candidate when choosing the best split candidate.
403 bool EnableAdvancedRASplitCost;
405 /// Set of broken hints that may be reconciled later because of eviction.
406 SmallSetVector<LiveInterval *, 8> SetOfBrokenHints;
411 /// Return the pass name.
412 StringRef getPassName() const override { return "Greedy Register Allocator"; }
414 /// RAGreedy analysis usage.
415 void getAnalysisUsage(AnalysisUsage &AU) const override;
416 void releaseMemory() override;
417 Spiller &spiller() override { return *SpillerInstance; }
418 void enqueue(LiveInterval *LI) override;
419 LiveInterval *dequeue() override;
420 Register selectOrSplit(LiveInterval&, SmallVectorImpl<Register>&) override;
421 void aboutToRemoveInterval(LiveInterval &) override;
423 /// Perform register allocation.
424 bool runOnMachineFunction(MachineFunction &mf) override;
426 MachineFunctionProperties getRequiredProperties() const override {
427 return MachineFunctionProperties().set(
428 MachineFunctionProperties::Property::NoPHIs);
434 Register selectOrSplitImpl(LiveInterval &, SmallVectorImpl<Register> &,
435 SmallVirtRegSet &, unsigned = 0);
437 bool LRE_CanEraseVirtReg(unsigned) override;
438 void LRE_WillShrinkVirtReg(unsigned) override;
439 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
440 void enqueue(PQueue &CurQueue, LiveInterval *LI);
441 LiveInterval *dequeue(PQueue &CurQueue);
443 BlockFrequency calcSpillCost();
444 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
445 bool addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
446 bool growRegion(GlobalSplitCandidate &Cand);
447 bool splitCanCauseEvictionChain(unsigned Evictee, GlobalSplitCandidate &Cand,
449 const AllocationOrder &Order);
450 bool splitCanCauseLocalSpill(unsigned VirtRegToSplit,
451 GlobalSplitCandidate &Cand, unsigned BBNumber,
452 const AllocationOrder &Order);
453 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate &,
454 const AllocationOrder &Order,
455 bool *CanCauseEvictionChain);
456 bool calcCompactRegion(GlobalSplitCandidate&);
457 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
458 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
459 Register canReassign(LiveInterval &VirtReg, Register PrevReg);
460 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
461 bool canEvictInterference(LiveInterval&, Register, bool, EvictionCost&,
462 const SmallVirtRegSet&);
463 bool canEvictInterferenceInRange(LiveInterval &VirtReg, Register oPhysReg,
464 SlotIndex Start, SlotIndex End,
465 EvictionCost &MaxCost);
466 unsigned getCheapestEvicteeWeight(const AllocationOrder &Order,
467 LiveInterval &VirtReg, SlotIndex Start,
468 SlotIndex End, float *BestEvictWeight);
469 void evictInterference(LiveInterval&, Register,
470 SmallVectorImpl<Register>&);
471 bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
472 SmallLISet &RecoloringCandidates,
473 const SmallVirtRegSet &FixedRegisters);
475 Register tryAssign(LiveInterval&, AllocationOrder&,
476 SmallVectorImpl<Register>&,
477 const SmallVirtRegSet&);
478 unsigned tryEvict(LiveInterval&, AllocationOrder&,
479 SmallVectorImpl<Register>&, unsigned,
480 const SmallVirtRegSet&);
481 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
482 SmallVectorImpl<Register>&);
483 /// Calculate cost of region splitting.
484 unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
485 AllocationOrder &Order,
486 BlockFrequency &BestCost,
487 unsigned &NumCands, bool IgnoreCSR,
488 bool *CanCauseEvictionChain = nullptr);
489 /// Perform region splitting.
490 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
492 SmallVectorImpl<Register> &NewVRegs);
493 /// Check other options before using a callee-saved register for the first
495 unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
496 Register PhysReg, unsigned &CostPerUseLimit,
497 SmallVectorImpl<Register> &NewVRegs);
498 void initializeCSRCost();
499 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
500 SmallVectorImpl<Register>&);
501 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
502 SmallVectorImpl<Register>&);
503 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
504 SmallVectorImpl<Register>&);
505 unsigned trySplit(LiveInterval&, AllocationOrder&,
506 SmallVectorImpl<Register>&,
507 const SmallVirtRegSet&);
508 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
509 SmallVectorImpl<Register> &,
510 SmallVirtRegSet &, unsigned);
511 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<Register> &,
512 SmallVirtRegSet &, unsigned);
513 void tryHintRecoloring(LiveInterval &);
514 void tryHintsRecoloring();
516 /// Model the information carried by one end of a copy.
518 /// The frequency of the copy.
520 /// The virtual register or physical register.
522 /// Its currently assigned register.
523 /// In case of a physical register Reg == PhysReg.
526 HintInfo(BlockFrequency Freq, Register Reg, MCRegister PhysReg)
527 : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {}
529 using HintsInfo = SmallVector<HintInfo, 4>;
531 BlockFrequency getBrokenHintFreq(const HintsInfo &, unsigned);
532 void collectHintInfo(unsigned, HintsInfo &);
534 bool isUnusedCalleeSavedReg(MCRegister PhysReg) const;
536 /// Compute and report the number of spills and reloads for a loop.
537 void reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
538 unsigned &FoldedReloads, unsigned &Spills,
539 unsigned &FoldedSpills);
541 /// Report the number of spills and reloads for each loop.
542 void reportNumberOfSplillsReloads() {
543 for (MachineLoop *L : *Loops) {
544 unsigned Reloads, FoldedReloads, Spills, FoldedSpills;
545 reportNumberOfSplillsReloads(L, Reloads, FoldedReloads, Spills,
551 } // end anonymous namespace
553 char RAGreedy::ID = 0;
554 char &llvm::RAGreedyID = RAGreedy::ID;
556 INITIALIZE_PASS_BEGIN(RAGreedy, "greedy",
557 "Greedy Register Allocator", false, false)
558 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
559 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
560 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
561 INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
562 INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
563 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
564 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
565 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
566 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
567 INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
568 INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
569 INITIALIZE_PASS_DEPENDENCY(SpillPlacement)
570 INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
571 INITIALIZE_PASS_END(RAGreedy, "greedy",
572 "Greedy Register Allocator", false, false)
575 const char *const RAGreedy::StageName[] = {
586 // Hysteresis to use when comparing floats.
587 // This helps stabilize decisions based on float comparisons.
588 const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
590 FunctionPass* llvm::createGreedyRegisterAllocator() {
591 return new RAGreedy();
594 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
597 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
598 AU.setPreservesCFG();
599 AU.addRequired<MachineBlockFrequencyInfo>();
600 AU.addPreserved<MachineBlockFrequencyInfo>();
601 AU.addRequired<AAResultsWrapperPass>();
602 AU.addPreserved<AAResultsWrapperPass>();
603 AU.addRequired<LiveIntervals>();
604 AU.addPreserved<LiveIntervals>();
605 AU.addRequired<SlotIndexes>();
606 AU.addPreserved<SlotIndexes>();
607 AU.addRequired<LiveDebugVariables>();
608 AU.addPreserved<LiveDebugVariables>();
609 AU.addRequired<LiveStacks>();
610 AU.addPreserved<LiveStacks>();
611 AU.addRequired<MachineDominatorTree>();
612 AU.addPreserved<MachineDominatorTree>();
613 AU.addRequired<MachineLoopInfo>();
614 AU.addPreserved<MachineLoopInfo>();
615 AU.addRequired<VirtRegMap>();
616 AU.addPreserved<VirtRegMap>();
617 AU.addRequired<LiveRegMatrix>();
618 AU.addPreserved<LiveRegMatrix>();
619 AU.addRequired<EdgeBundles>();
620 AU.addRequired<SpillPlacement>();
621 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
622 MachineFunctionPass::getAnalysisUsage(AU);
625 //===----------------------------------------------------------------------===//
626 // LiveRangeEdit delegate methods
627 //===----------------------------------------------------------------------===//
629 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
630 LiveInterval &LI = LIS->getInterval(VirtReg);
631 if (VRM->hasPhys(VirtReg)) {
632 Matrix->unassign(LI);
633 aboutToRemoveInterval(LI);
636 // Unassigned virtreg is probably in the priority queue.
637 // RegAllocBase will erase it after dequeueing.
638 // Nonetheless, clear the live-range so that the debug
639 // dump will show the right state for that VirtReg.
644 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
645 if (!VRM->hasPhys(VirtReg))
648 // Register is assigned, put it back on the queue for reassignment.
649 LiveInterval &LI = LIS->getInterval(VirtReg);
650 Matrix->unassign(LI);
654 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
655 // Cloning a register we haven't even heard about yet? Just ignore it.
656 if (!ExtraRegInfo.inBounds(Old))
659 // LRE may clone a virtual register because dead code elimination causes it to
660 // be split into connected components. The new components are much smaller
661 // than the original, so they should get a new chance at being assigned.
662 // same stage as the parent.
663 ExtraRegInfo[Old].Stage = RS_Assign;
664 ExtraRegInfo.grow(New);
665 ExtraRegInfo[New] = ExtraRegInfo[Old];
668 void RAGreedy::releaseMemory() {
669 SpillerInstance.reset();
670 ExtraRegInfo.clear();
674 void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
676 void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
677 // Prioritize live ranges by size, assigning larger ranges first.
678 // The queue holds (size, reg) pairs.
679 const unsigned Size = LI->getSize();
680 const unsigned Reg = LI->reg;
681 assert(Register::isVirtualRegister(Reg) &&
682 "Can only enqueue virtual registers");
685 ExtraRegInfo.grow(Reg);
686 if (ExtraRegInfo[Reg].Stage == RS_New)
687 ExtraRegInfo[Reg].Stage = RS_Assign;
689 if (ExtraRegInfo[Reg].Stage == RS_Split) {
690 // Unsplit ranges that couldn't be allocated immediately are deferred until
691 // everything else has been allocated.
693 } else if (ExtraRegInfo[Reg].Stage == RS_Memory) {
694 // Memory operand should be considered last.
695 // Change the priority such that Memory operand are assigned in
696 // the reverse order that they came in.
697 // TODO: Make this a member variable and probably do something about hints.
698 static unsigned MemOp = 0;
701 // Giant live ranges fall back to the global assignment heuristic, which
702 // prevents excessive spilling in pathological cases.
703 bool ReverseLocal = TRI->reverseLocalAssignment();
704 const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
705 bool ForceGlobal = !ReverseLocal &&
706 (Size / SlotIndex::InstrDist) > (2 * RC.getNumRegs());
708 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
709 LIS->intervalIsInOneMBB(*LI)) {
710 // Allocate original local ranges in linear instruction order. Since they
711 // are singly defined, this produces optimal coloring in the absence of
712 // global interference and other constraints.
714 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
716 // Allocating bottom up may allow many short LRGs to be assigned first
717 // to one of the cheap registers. This could be much faster for very
718 // large blocks on targets with many physical registers.
719 Prio = Indexes->getZeroIndex().getInstrDistance(LI->endIndex());
721 Prio |= RC.AllocationPriority << 24;
723 // Allocate global and split ranges in long->short order. Long ranges that
724 // don't fit should be spilled (or split) ASAP so they don't create
725 // interference. Mark a bit to prioritize global above local ranges.
726 Prio = (1u << 29) + Size;
728 // Mark a higher bit to prioritize global and local above RS_Split.
731 // Boost ranges that have a physical register hint.
732 if (VRM->hasKnownPreference(Reg))
735 // The virtual register number is a tie breaker for same-sized ranges.
736 // Give lower vreg numbers higher priority to assign them first.
737 CurQueue.push(std::make_pair(Prio, ~Reg));
740 LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
742 LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
743 if (CurQueue.empty())
745 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
750 //===----------------------------------------------------------------------===//
752 //===----------------------------------------------------------------------===//
754 /// tryAssign - Try to assign VirtReg to an available register.
755 Register RAGreedy::tryAssign(LiveInterval &VirtReg,
756 AllocationOrder &Order,
757 SmallVectorImpl<Register> &NewVRegs,
758 const SmallVirtRegSet &FixedRegisters) {
761 while ((PhysReg = Order.next()))
762 if (!Matrix->checkInterference(VirtReg, PhysReg))
764 if (!PhysReg || Order.isHint())
767 // PhysReg is available, but there may be a better choice.
769 // If we missed a simple hint, try to cheaply evict interference from the
770 // preferred register.
771 if (Register Hint = MRI->getSimpleHint(VirtReg.reg))
772 if (Order.isHint(Hint)) {
773 LLVM_DEBUG(dbgs() << "missed hint " << printReg(Hint, TRI) << '\n');
774 EvictionCost MaxCost;
775 MaxCost.setBrokenHints(1);
776 if (canEvictInterference(VirtReg, Hint, true, MaxCost, FixedRegisters)) {
777 evictInterference(VirtReg, Hint, NewVRegs);
780 // Record the missed hint, we may be able to recover
781 // at the end if the surrounding allocation changed.
782 SetOfBrokenHints.insert(&VirtReg);
785 // Try to evict interference from a cheaper alternative.
786 unsigned Cost = TRI->getCostPerUse(PhysReg);
788 // Most registers have 0 additional cost.
792 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is available at cost "
794 Register CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost, FixedRegisters);
795 return CheapReg ? CheapReg : PhysReg;
798 //===----------------------------------------------------------------------===//
799 // Interference eviction
800 //===----------------------------------------------------------------------===//
802 Register RAGreedy::canReassign(LiveInterval &VirtReg, Register PrevReg) {
803 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
805 while ((PhysReg = Order.next())) {
806 if (PhysReg == PrevReg)
809 MCRegUnitIterator Units(PhysReg, TRI);
810 for (; Units.isValid(); ++Units) {
811 // Instantiate a "subquery", not to be confused with the Queries array.
812 LiveIntervalUnion::Query subQ(VirtReg, Matrix->getLiveUnions()[*Units]);
813 if (subQ.checkInterference())
816 // If no units have interference, break out with the current PhysReg.
817 if (!Units.isValid())
821 LLVM_DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
822 << printReg(PrevReg, TRI) << " to "
823 << printReg(PhysReg, TRI) << '\n');
827 /// shouldEvict - determine if A should evict the assigned live range B. The
828 /// eviction policy defined by this function together with the allocation order
829 /// defined by enqueue() decides which registers ultimately end up being split
832 /// Cascade numbers are used to prevent infinite loops if this function is a
835 /// @param A The live range to be assigned.
836 /// @param IsHint True when A is about to be assigned to its preferred
838 /// @param B The live range to be evicted.
839 /// @param BreaksHint True when B is already assigned to its preferred register.
840 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
841 LiveInterval &B, bool BreaksHint) {
842 bool CanSplit = getStage(B) < RS_Spill;
844 // Be fairly aggressive about following hints as long as the evictee can be
846 if (CanSplit && IsHint && !BreaksHint)
849 if (A.weight > B.weight) {
850 LLVM_DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
856 /// canEvictInterference - Return true if all interferences between VirtReg and
857 /// PhysReg can be evicted.
859 /// @param VirtReg Live range that is about to be assigned.
860 /// @param PhysReg Desired register for assignment.
861 /// @param IsHint True when PhysReg is VirtReg's preferred register.
862 /// @param MaxCost Only look for cheaper candidates and update with new cost
863 /// when returning true.
864 /// @returns True when interference can be evicted cheaper than MaxCost.
865 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, Register PhysReg,
866 bool IsHint, EvictionCost &MaxCost,
867 const SmallVirtRegSet &FixedRegisters) {
868 // It is only possible to evict virtual register interference.
869 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
872 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
874 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
875 // involved in an eviction before. If a cascade number was assigned, deny
876 // evicting anything with the same or a newer cascade number. This prevents
877 // infinite eviction loops.
879 // This works out so a register without a cascade number is allowed to evict
880 // anything, and it can be evicted by anything.
881 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
883 Cascade = NextCascade;
886 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
887 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
888 // If there is 10 or more interferences, chances are one is heavier.
889 if (Q.collectInterferingVRegs(10) >= 10)
892 // Check if any interfering live range is heavier than MaxWeight.
893 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
894 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
895 assert(Register::isVirtualRegister(Intf->reg) &&
896 "Only expecting virtual register interference from query");
898 // Do not allow eviction of a virtual register if we are in the middle
899 // of last-chance recoloring and this virtual register is one that we
900 // have scavenged a physical register for.
901 if (FixedRegisters.count(Intf->reg))
904 // Never evict spill products. They cannot split or spill.
905 if (getStage(*Intf) == RS_Done)
907 // Once a live range becomes small enough, it is urgent that we find a
908 // register for it. This is indicated by an infinite spill weight. These
909 // urgent live ranges get to evict almost anything.
911 // Also allow urgent evictions of unspillable ranges from a strictly
912 // larger allocation order.
913 bool Urgent = !VirtReg.isSpillable() &&
914 (Intf->isSpillable() ||
915 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
916 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
917 // Only evict older cascades or live ranges without a cascade.
918 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
919 if (Cascade <= IntfCascade) {
922 // We permit breaking cascades for urgent evictions. It should be the
923 // last resort, though, so make it really expensive.
924 Cost.BrokenHints += 10;
926 // Would this break a satisfied hint?
927 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
928 // Update eviction cost.
929 Cost.BrokenHints += BreaksHint;
930 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
931 // Abort if this would be too expensive.
932 if (!(Cost < MaxCost))
936 // Apply the eviction policy for non-urgent evictions.
937 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
939 // If !MaxCost.isMax(), then we're just looking for a cheap register.
940 // Evicting another local live range in this case could lead to suboptimal
942 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
943 (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) {
952 /// Return true if all interferences between VirtReg and PhysReg between
953 /// Start and End can be evicted.
955 /// \param VirtReg Live range that is about to be assigned.
956 /// \param PhysReg Desired register for assignment.
957 /// \param Start Start of range to look for interferences.
958 /// \param End End of range to look for interferences.
959 /// \param MaxCost Only look for cheaper candidates and update with new cost
960 /// when returning true.
961 /// \return True when interference can be evicted cheaper than MaxCost.
962 bool RAGreedy::canEvictInterferenceInRange(LiveInterval &VirtReg,
963 Register PhysReg, SlotIndex Start,
965 EvictionCost &MaxCost) {
968 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
969 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
971 // Check if any interfering live range is heavier than MaxWeight.
972 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
973 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
975 // Check if interference overlast the segment in interest.
976 if (!Intf->overlaps(Start, End))
979 // Cannot evict non virtual reg interference.
980 if (!Register::isVirtualRegister(Intf->reg))
982 // Never evict spill products. They cannot split or spill.
983 if (getStage(*Intf) == RS_Done)
986 // Would this break a satisfied hint?
987 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
988 // Update eviction cost.
989 Cost.BrokenHints += BreaksHint;
990 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
991 // Abort if this would be too expensive.
992 if (!(Cost < MaxCost))
997 if (Cost.MaxWeight == 0)
1004 /// Return the physical register that will be best
1005 /// candidate for eviction by a local split interval that will be created
1006 /// between Start and End.
1008 /// \param Order The allocation order
1009 /// \param VirtReg Live range that is about to be assigned.
1010 /// \param Start Start of range to look for interferences
1011 /// \param End End of range to look for interferences
1012 /// \param BestEvictweight The eviction cost of that eviction
1013 /// \return The PhysReg which is the best candidate for eviction and the
1014 /// eviction cost in BestEvictweight
1015 unsigned RAGreedy::getCheapestEvicteeWeight(const AllocationOrder &Order,
1016 LiveInterval &VirtReg,
1017 SlotIndex Start, SlotIndex End,
1018 float *BestEvictweight) {
1019 EvictionCost BestEvictCost;
1020 BestEvictCost.setMax();
1021 BestEvictCost.MaxWeight = VirtReg.weight;
1022 unsigned BestEvicteePhys = 0;
1024 // Go over all physical registers and find the best candidate for eviction
1025 for (auto PhysReg : Order.getOrder()) {
1027 if (!canEvictInterferenceInRange(VirtReg, PhysReg, Start, End,
1032 BestEvicteePhys = PhysReg;
1034 *BestEvictweight = BestEvictCost.MaxWeight;
1035 return BestEvicteePhys;
1038 /// evictInterference - Evict any interferring registers that prevent VirtReg
1039 /// from being assigned to Physreg. This assumes that canEvictInterference
1041 void RAGreedy::evictInterference(LiveInterval &VirtReg, Register PhysReg,
1042 SmallVectorImpl<Register> &NewVRegs) {
1043 // Make sure that VirtReg has a cascade number, and assign that cascade
1044 // number to every evicted register. These live ranges than then only be
1045 // evicted by a newer cascade, preventing infinite loops.
1046 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
1048 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
1050 LLVM_DEBUG(dbgs() << "evicting " << printReg(PhysReg, TRI)
1051 << " interference: Cascade " << Cascade << '\n');
1053 // Collect all interfering virtregs first.
1054 SmallVector<LiveInterval*, 8> Intfs;
1055 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1056 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
1057 // We usually have the interfering VRegs cached so collectInterferingVRegs()
1058 // should be fast, we may need to recalculate if when different physregs
1059 // overlap the same register unit so we had different SubRanges queried
1061 Q.collectInterferingVRegs();
1062 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
1063 Intfs.append(IVR.begin(), IVR.end());
1066 // Evict them second. This will invalidate the queries.
1067 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
1068 LiveInterval *Intf = Intfs[i];
1069 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
1070 if (!VRM->hasPhys(Intf->reg))
1073 LastEvicted.addEviction(PhysReg, VirtReg.reg, Intf->reg);
1075 Matrix->unassign(*Intf);
1076 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
1077 VirtReg.isSpillable() < Intf->isSpillable()) &&
1078 "Cannot decrease cascade number, illegal eviction");
1079 ExtraRegInfo[Intf->reg].Cascade = Cascade;
1081 NewVRegs.push_back(Intf->reg);
1085 /// Returns true if the given \p PhysReg is a callee saved register and has not
1086 /// been used for allocation yet.
1087 bool RAGreedy::isUnusedCalleeSavedReg(MCRegister PhysReg) const {
1088 MCRegister CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
1092 return !Matrix->isPhysRegUsed(PhysReg);
1095 /// tryEvict - Try to evict all interferences for a physreg.
1096 /// @param VirtReg Currently unassigned virtual register.
1097 /// @param Order Physregs to try.
1098 /// @return Physreg to assign VirtReg, or 0.
1099 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
1100 AllocationOrder &Order,
1101 SmallVectorImpl<Register> &NewVRegs,
1102 unsigned CostPerUseLimit,
1103 const SmallVirtRegSet &FixedRegisters) {
1104 NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription,
1105 TimePassesIsEnabled);
1107 // Keep track of the cheapest interference seen so far.
1108 EvictionCost BestCost;
1110 unsigned BestPhys = 0;
1111 unsigned OrderLimit = Order.getOrder().size();
1113 // When we are just looking for a reduced cost per use, don't break any
1114 // hints, and only evict smaller spill weights.
1115 if (CostPerUseLimit < ~0u) {
1116 BestCost.BrokenHints = 0;
1117 BestCost.MaxWeight = VirtReg.weight;
1119 // Check of any registers in RC are below CostPerUseLimit.
1120 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
1121 unsigned MinCost = RegClassInfo.getMinCost(RC);
1122 if (MinCost >= CostPerUseLimit) {
1123 LLVM_DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = "
1124 << MinCost << ", no cheaper registers to be found.\n");
1128 // It is normal for register classes to have a long tail of registers with
1129 // the same cost. We don't need to look at them if they're too expensive.
1130 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
1131 OrderLimit = RegClassInfo.getLastCostChange(RC);
1132 LLVM_DEBUG(dbgs() << "Only trying the first " << OrderLimit
1138 while (MCRegister PhysReg = Order.next(OrderLimit)) {
1139 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
1141 // The first use of a callee-saved register in a function has cost 1.
1142 // Don't start using a CSR when the CostPerUseLimit is low.
1143 if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
1145 dbgs() << printReg(PhysReg, TRI) << " would clobber CSR "
1146 << printReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
1151 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost,
1158 // Stop if the hint can be used.
1166 evictInterference(VirtReg, BestPhys, NewVRegs);
1170 //===----------------------------------------------------------------------===//
1172 //===----------------------------------------------------------------------===//
1174 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
1175 /// interference pattern in Physreg and its aliases. Add the constraints to
1176 /// SpillPlacement and return the static cost of this split in Cost, assuming
1177 /// that all preferences in SplitConstraints are met.
1178 /// Return false if there are no bundles with positive bias.
1179 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
1180 BlockFrequency &Cost) {
1181 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1183 // Reset interference dependent info.
1184 SplitConstraints.resize(UseBlocks.size());
1185 BlockFrequency StaticCost = 0;
1186 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1187 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1188 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
1190 BC.Number = BI.MBB->getNumber();
1191 Intf.moveToBlock(BC.Number);
1192 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
1193 BC.Exit = (BI.LiveOut &&
1194 !LIS->getInstructionFromIndex(BI.LastInstr)->isImplicitDef())
1195 ? SpillPlacement::PrefReg
1196 : SpillPlacement::DontCare;
1197 BC.ChangesValue = BI.FirstDef.isValid();
1199 if (!Intf.hasInterference())
1202 // Number of spill code instructions to insert.
1205 // Interference for the live-in value.
1207 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number)) {
1208 BC.Entry = SpillPlacement::MustSpill;
1210 } else if (Intf.first() < BI.FirstInstr) {
1211 BC.Entry = SpillPlacement::PrefSpill;
1213 } else if (Intf.first() < BI.LastInstr) {
1217 // Abort if the spill cannot be inserted at the MBB' start
1218 if (((BC.Entry == SpillPlacement::MustSpill) ||
1219 (BC.Entry == SpillPlacement::PrefSpill)) &&
1220 SlotIndex::isEarlierInstr(BI.FirstInstr,
1221 SA->getFirstSplitPoint(BC.Number)))
1225 // Interference for the live-out value.
1227 if (Intf.last() >= SA->getLastSplitPoint(BC.Number)) {
1228 BC.Exit = SpillPlacement::MustSpill;
1230 } else if (Intf.last() > BI.LastInstr) {
1231 BC.Exit = SpillPlacement::PrefSpill;
1233 } else if (Intf.last() > BI.FirstInstr) {
1238 // Accumulate the total frequency of inserted spill code.
1240 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
1244 // Add constraints for use-blocks. Note that these are the only constraints
1245 // that may add a positive bias, it is downhill from here.
1246 SpillPlacer->addConstraints(SplitConstraints);
1247 return SpillPlacer->scanActiveBundles();
1250 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
1251 /// live-through blocks in Blocks.
1252 bool RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
1253 ArrayRef<unsigned> Blocks) {
1254 const unsigned GroupSize = 8;
1255 SpillPlacement::BlockConstraint BCS[GroupSize];
1256 unsigned TBS[GroupSize];
1257 unsigned B = 0, T = 0;
1259 for (unsigned i = 0; i != Blocks.size(); ++i) {
1260 unsigned Number = Blocks[i];
1261 Intf.moveToBlock(Number);
1263 if (!Intf.hasInterference()) {
1264 assert(T < GroupSize && "Array overflow");
1266 if (++T == GroupSize) {
1267 SpillPlacer->addLinks(makeArrayRef(TBS, T));
1273 assert(B < GroupSize && "Array overflow");
1274 BCS[B].Number = Number;
1276 // Abort if the spill cannot be inserted at the MBB' start
1277 MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
1278 if (!MBB->empty() &&
1279 SlotIndex::isEarlierInstr(LIS->getInstructionIndex(MBB->instr_front()),
1280 SA->getFirstSplitPoint(Number)))
1282 // Interference for the live-in value.
1283 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
1284 BCS[B].Entry = SpillPlacement::MustSpill;
1286 BCS[B].Entry = SpillPlacement::PrefSpill;
1288 // Interference for the live-out value.
1289 if (Intf.last() >= SA->getLastSplitPoint(Number))
1290 BCS[B].Exit = SpillPlacement::MustSpill;
1292 BCS[B].Exit = SpillPlacement::PrefSpill;
1294 if (++B == GroupSize) {
1295 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
1300 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
1301 SpillPlacer->addLinks(makeArrayRef(TBS, T));
1305 bool RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
1306 // Keep track of through blocks that have not been added to SpillPlacer.
1307 BitVector Todo = SA->getThroughBlocks();
1308 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
1309 unsigned AddedTo = 0;
1311 unsigned Visited = 0;
1315 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
1316 // Find new through blocks in the periphery of PrefRegBundles.
1317 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
1318 unsigned Bundle = NewBundles[i];
1319 // Look at all blocks connected to Bundle in the full graph.
1320 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
1321 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
1323 unsigned Block = *I;
1324 if (!Todo.test(Block))
1327 // This is a new through block. Add it to SpillPlacer later.
1328 ActiveBlocks.push_back(Block);
1334 // Any new blocks to add?
1335 if (ActiveBlocks.size() == AddedTo)
1338 // Compute through constraints from the interference, or assume that all
1339 // through blocks prefer spilling when forming compact regions.
1340 auto NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
1342 if (!addThroughConstraints(Cand.Intf, NewBlocks))
1345 // Provide a strong negative bias on through blocks to prevent unwanted
1346 // liveness on loop backedges.
1347 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
1348 AddedTo = ActiveBlocks.size();
1350 // Perhaps iterating can enable more bundles?
1351 SpillPlacer->iterate();
1353 LLVM_DEBUG(dbgs() << ", v=" << Visited);
1357 /// calcCompactRegion - Compute the set of edge bundles that should be live
1358 /// when splitting the current live range into compact regions. Compact
1359 /// regions can be computed without looking at interference. They are the
1360 /// regions formed by removing all the live-through blocks from the live range.
1362 /// Returns false if the current live range is already compact, or if the
1363 /// compact regions would form single block regions anyway.
1364 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1365 // Without any through blocks, the live range is already compact.
1366 if (!SA->getNumThroughBlocks())
1369 // Compact regions don't correspond to any physreg.
1370 Cand.reset(IntfCache, 0);
1372 LLVM_DEBUG(dbgs() << "Compact region bundles");
1374 // Use the spill placer to determine the live bundles. GrowRegion pretends
1375 // that all the through blocks have interference when PhysReg is unset.
1376 SpillPlacer->prepare(Cand.LiveBundles);
1378 // The static split cost will be zero since Cand.Intf reports no interference.
1379 BlockFrequency Cost;
1380 if (!addSplitConstraints(Cand.Intf, Cost)) {
1381 LLVM_DEBUG(dbgs() << ", none.\n");
1385 if (!growRegion(Cand)) {
1386 LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n");
1390 SpillPlacer->finish();
1392 if (!Cand.LiveBundles.any()) {
1393 LLVM_DEBUG(dbgs() << ", none.\n");
1398 for (int i : Cand.LiveBundles.set_bits())
1399 dbgs() << " EB#" << i;
1405 /// calcSpillCost - Compute how expensive it would be to split the live range in
1406 /// SA around all use blocks instead of forming bundle regions.
1407 BlockFrequency RAGreedy::calcSpillCost() {
1408 BlockFrequency Cost = 0;
1409 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1410 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1411 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1412 unsigned Number = BI.MBB->getNumber();
1413 // We normally only need one spill instruction - a load or a store.
1414 Cost += SpillPlacer->getBlockFrequency(Number);
1416 // Unless the value is redefined in the block.
1417 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1418 Cost += SpillPlacer->getBlockFrequency(Number);
1423 /// Check if splitting Evictee will create a local split interval in
1424 /// basic block number BBNumber that may cause a bad eviction chain. This is
1425 /// intended to prevent bad eviction sequences like:
1426 /// movl %ebp, 8(%esp) # 4-byte Spill
1437 /// movl 16(%esp), %ebp # 4 - byte Reload
1439 /// Such sequences are created in 2 scenarios:
1442 /// %0 is evicted from physreg0 by %1.
1443 /// Evictee %0 is intended for region splitting with split candidate
1444 /// physreg0 (the reg %0 was evicted from).
1445 /// Region splitting creates a local interval because of interference with the
1446 /// evictor %1 (normally region splitting creates 2 interval, the "by reg"
1447 /// and "by stack" intervals and local interval created when interference
1449 /// One of the split intervals ends up evicting %2 from physreg1.
1450 /// Evictee %2 is intended for region splitting with split candidate
1452 /// One of the split intervals ends up evicting %3 from physreg2, etc.
1455 /// %0 is evicted from physreg0 by %1.
1456 /// %2 is evicted from physreg2 by %3 etc.
1457 /// Evictee %0 is intended for region splitting with split candidate
1459 /// Region splitting creates a local interval because of interference with the
1461 /// One of the split intervals ends up evicting back original evictor %1
1462 /// from physreg0 (the reg %0 was evicted from).
1463 /// Another evictee %2 is intended for region splitting with split candidate
1465 /// One of the split intervals ends up evicting %3 from physreg2, etc.
1467 /// \param Evictee The register considered to be split.
1468 /// \param Cand The split candidate that determines the physical register
1469 /// we are splitting for and the interferences.
1470 /// \param BBNumber The number of a BB for which the region split process will
1471 /// create a local split interval.
1472 /// \param Order The physical registers that may get evicted by a split
1473 /// artifact of Evictee.
1474 /// \return True if splitting Evictee may cause a bad eviction chain, false
1476 bool RAGreedy::splitCanCauseEvictionChain(unsigned Evictee,
1477 GlobalSplitCandidate &Cand,
1479 const AllocationOrder &Order) {
1480 EvictionTrack::EvictorInfo VregEvictorInfo = LastEvicted.getEvictor(Evictee);
1481 unsigned Evictor = VregEvictorInfo.first;
1482 unsigned PhysReg = VregEvictorInfo.second;
1484 // No actual evictor.
1485 if (!Evictor || !PhysReg)
1488 float MaxWeight = 0;
1489 unsigned FutureEvictedPhysReg =
1490 getCheapestEvicteeWeight(Order, LIS->getInterval(Evictee),
1491 Cand.Intf.first(), Cand.Intf.last(), &MaxWeight);
1493 // The bad eviction chain occurs when either the split candidate is the
1494 // evicting reg or one of the split artifact will evict the evicting reg.
1495 if ((PhysReg != Cand.PhysReg) && (PhysReg != FutureEvictedPhysReg))
1498 Cand.Intf.moveToBlock(BBNumber);
1500 // Check to see if the Evictor contains interference (with Evictee) in the
1501 // given BB. If so, this interference caused the eviction of Evictee from
1502 // PhysReg. This suggest that we will create a local interval during the
1503 // region split to avoid this interference This local interval may cause a bad
1505 if (!LIS->hasInterval(Evictor))
1507 LiveInterval &EvictorLI = LIS->getInterval(Evictor);
1508 if (EvictorLI.FindSegmentContaining(Cand.Intf.first()) == EvictorLI.end())
1511 // Now, check to see if the local interval we will create is going to be
1512 // expensive enough to evict somebody If so, this may cause a bad eviction
1514 VirtRegAuxInfo VRAI(*MF, *LIS, VRM, getAnalysis<MachineLoopInfo>(), *MBFI);
1515 float splitArtifactWeight =
1516 VRAI.futureWeight(LIS->getInterval(Evictee),
1517 Cand.Intf.first().getPrevIndex(), Cand.Intf.last());
1518 if (splitArtifactWeight >= 0 && splitArtifactWeight < MaxWeight)
1524 /// Check if splitting VirtRegToSplit will create a local split interval
1525 /// in basic block number BBNumber that may cause a spill.
1527 /// \param VirtRegToSplit The register considered to be split.
1528 /// \param Cand The split candidate that determines the physical
1529 /// register we are splitting for and the interferences.
1530 /// \param BBNumber The number of a BB for which the region split process
1531 /// will create a local split interval.
1532 /// \param Order The physical registers that may get evicted by a
1533 /// split artifact of VirtRegToSplit.
1534 /// \return True if splitting VirtRegToSplit may cause a spill, false
1536 bool RAGreedy::splitCanCauseLocalSpill(unsigned VirtRegToSplit,
1537 GlobalSplitCandidate &Cand,
1539 const AllocationOrder &Order) {
1540 Cand.Intf.moveToBlock(BBNumber);
1542 // Check if the local interval will find a non interfereing assignment.
1543 for (auto PhysReg : Order.getOrder()) {
1544 if (!Matrix->checkInterference(Cand.Intf.first().getPrevIndex(),
1545 Cand.Intf.last(), PhysReg))
1549 // Check if the local interval will evict a cheaper interval.
1550 float CheapestEvictWeight = 0;
1551 unsigned FutureEvictedPhysReg = getCheapestEvicteeWeight(
1552 Order, LIS->getInterval(VirtRegToSplit), Cand.Intf.first(),
1553 Cand.Intf.last(), &CheapestEvictWeight);
1555 // Have we found an interval that can be evicted?
1556 if (FutureEvictedPhysReg) {
1557 VirtRegAuxInfo VRAI(*MF, *LIS, VRM, getAnalysis<MachineLoopInfo>(), *MBFI);
1558 float splitArtifactWeight =
1559 VRAI.futureWeight(LIS->getInterval(VirtRegToSplit),
1560 Cand.Intf.first().getPrevIndex(), Cand.Intf.last());
1561 // Will the weight of the local interval be higher than the cheapest evictee
1562 // weight? If so it will evict it and will not cause a spill.
1563 if (splitArtifactWeight >= 0 && splitArtifactWeight > CheapestEvictWeight)
1567 // The local interval is not able to find non interferencing assignment and
1568 // not able to evict a less worthy interval, therfore, it can cause a spill.
1572 /// calcGlobalSplitCost - Return the global split cost of following the split
1573 /// pattern in LiveBundles. This cost should be added to the local cost of the
1574 /// interference pattern in SplitConstraints.
1576 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand,
1577 const AllocationOrder &Order,
1578 bool *CanCauseEvictionChain) {
1579 BlockFrequency GlobalCost = 0;
1580 const BitVector &LiveBundles = Cand.LiveBundles;
1581 unsigned VirtRegToSplit = SA->getParent().reg;
1582 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1583 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1584 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1585 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
1586 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, false)];
1587 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, true)];
1590 Cand.Intf.moveToBlock(BC.Number);
1591 // Check wheather a local interval is going to be created during the region
1592 // split. Calculate adavanced spilt cost (cost of local intervals) if option
1594 if (EnableAdvancedRASplitCost && Cand.Intf.hasInterference() && BI.LiveIn &&
1595 BI.LiveOut && RegIn && RegOut) {
1597 if (CanCauseEvictionChain &&
1598 splitCanCauseEvictionChain(VirtRegToSplit, Cand, BC.Number, Order)) {
1599 // This interference causes our eviction from this assignment, we might
1600 // evict somebody else and eventually someone will spill, add that cost.
1601 // See splitCanCauseEvictionChain for detailed description of scenarios.
1602 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1603 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1605 *CanCauseEvictionChain = true;
1607 } else if (splitCanCauseLocalSpill(VirtRegToSplit, Cand, BC.Number,
1609 // This interference causes local interval to spill, add that cost.
1610 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1611 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1616 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1618 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
1620 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1623 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1624 unsigned Number = Cand.ActiveBlocks[i];
1625 bool RegIn = LiveBundles[Bundles->getBundle(Number, false)];
1626 bool RegOut = LiveBundles[Bundles->getBundle(Number, true)];
1627 if (!RegIn && !RegOut)
1629 if (RegIn && RegOut) {
1630 // We need double spill code if this block has interference.
1631 Cand.Intf.moveToBlock(Number);
1632 if (Cand.Intf.hasInterference()) {
1633 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1634 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1636 // Check wheather a local interval is going to be created during the
1638 if (EnableAdvancedRASplitCost && CanCauseEvictionChain &&
1639 splitCanCauseEvictionChain(VirtRegToSplit, Cand, Number, Order)) {
1640 // This interference cause our eviction from this assignment, we might
1641 // evict somebody else, add that cost.
1642 // See splitCanCauseEvictionChain for detailed description of
1644 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1645 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1647 *CanCauseEvictionChain = true;
1652 // live-in / stack-out or stack-in live-out.
1653 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1658 /// splitAroundRegion - Split the current live range around the regions
1659 /// determined by BundleCand and GlobalCand.
1661 /// Before calling this function, GlobalCand and BundleCand must be initialized
1662 /// so each bundle is assigned to a valid candidate, or NoCand for the
1663 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1664 /// objects must be initialized for the current live range, and intervals
1665 /// created for the used candidates.
1667 /// @param LREdit The LiveRangeEdit object handling the current split.
1668 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1669 /// must appear in this list.
1670 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1671 ArrayRef<unsigned> UsedCands) {
1672 // These are the intervals created for new global ranges. We may create more
1673 // intervals for local ranges.
1674 const unsigned NumGlobalIntvs = LREdit.size();
1675 LLVM_DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs
1677 assert(NumGlobalIntvs && "No global intervals configured");
1679 // Isolate even single instructions when dealing with a proper sub-class.
1680 // That guarantees register class inflation for the stack interval because it
1682 unsigned Reg = SA->getParent().reg;
1683 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1685 // First handle all the blocks with uses.
1686 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1687 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1688 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1689 unsigned Number = BI.MBB->getNumber();
1690 unsigned IntvIn = 0, IntvOut = 0;
1691 SlotIndex IntfIn, IntfOut;
1693 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
1694 if (CandIn != NoCand) {
1695 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1696 IntvIn = Cand.IntvIdx;
1697 Cand.Intf.moveToBlock(Number);
1698 IntfIn = Cand.Intf.first();
1702 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
1703 if (CandOut != NoCand) {
1704 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1705 IntvOut = Cand.IntvIdx;
1706 Cand.Intf.moveToBlock(Number);
1707 IntfOut = Cand.Intf.last();
1711 // Create separate intervals for isolated blocks with multiple uses.
1712 if (!IntvIn && !IntvOut) {
1713 LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " isolated.\n");
1714 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1715 SE->splitSingleBlock(BI);
1719 if (IntvIn && IntvOut)
1720 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1722 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1724 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1727 // Handle live-through blocks. The relevant live-through blocks are stored in
1728 // the ActiveBlocks list with each candidate. We need to filter out
1730 BitVector Todo = SA->getThroughBlocks();
1731 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1732 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1733 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1734 unsigned Number = Blocks[i];
1735 if (!Todo.test(Number))
1739 unsigned IntvIn = 0, IntvOut = 0;
1740 SlotIndex IntfIn, IntfOut;
1742 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
1743 if (CandIn != NoCand) {
1744 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1745 IntvIn = Cand.IntvIdx;
1746 Cand.Intf.moveToBlock(Number);
1747 IntfIn = Cand.Intf.first();
1750 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
1751 if (CandOut != NoCand) {
1752 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1753 IntvOut = Cand.IntvIdx;
1754 Cand.Intf.moveToBlock(Number);
1755 IntfOut = Cand.Intf.last();
1757 if (!IntvIn && !IntvOut)
1759 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1765 SmallVector<unsigned, 8> IntvMap;
1766 SE->finish(&IntvMap);
1767 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
1769 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1770 unsigned OrigBlocks = SA->getNumLiveBlocks();
1772 // Sort out the new intervals created by splitting. We get four kinds:
1773 // - Remainder intervals should not be split again.
1774 // - Candidate intervals can be assigned to Cand.PhysReg.
1775 // - Block-local splits are candidates for local splitting.
1776 // - DCE leftovers should go back on the queue.
1777 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1778 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
1780 // Ignore old intervals from DCE.
1781 if (getStage(Reg) != RS_New)
1784 // Remainder interval. Don't try splitting again, spill if it doesn't
1786 if (IntvMap[i] == 0) {
1787 setStage(Reg, RS_Spill);
1791 // Global intervals. Allow repeated splitting as long as the number of live
1792 // blocks is strictly decreasing.
1793 if (IntvMap[i] < NumGlobalIntvs) {
1794 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1795 LLVM_DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1796 << " blocks as original.\n");
1797 // Don't allow repeated splitting as a safe guard against looping.
1798 setStage(Reg, RS_Split2);
1803 // Other intervals are treated as new. This includes local intervals created
1804 // for blocks with multiple uses, and anything created by DCE.
1808 MF->verify(this, "After splitting live range around region");
1811 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1812 SmallVectorImpl<Register> &NewVRegs) {
1813 if (!TRI->shouldRegionSplitForVirtReg(*MF, VirtReg))
1815 unsigned NumCands = 0;
1816 BlockFrequency SpillCost = calcSpillCost();
1817 BlockFrequency BestCost;
1819 // Check if we can split this live range around a compact region.
1820 bool HasCompact = calcCompactRegion(GlobalCand.front());
1822 // Yes, keep GlobalCand[0] as the compact region candidate.
1824 BestCost = BlockFrequency::getMaxFrequency();
1826 // No benefit from the compact region, our fallback will be per-block
1827 // splitting. Make sure we find a solution that is cheaper than spilling.
1828 BestCost = SpillCost;
1829 LLVM_DEBUG(dbgs() << "Cost of isolating all blocks = ";
1830 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
1833 bool CanCauseEvictionChain = false;
1835 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1836 false /*IgnoreCSR*/, &CanCauseEvictionChain);
1838 // Split candidates with compact regions can cause a bad eviction sequence.
1839 // See splitCanCauseEvictionChain for detailed description of scenarios.
1840 // To avoid it, we need to comapre the cost with the spill cost and not the
1841 // current max frequency.
1842 if (HasCompact && (BestCost > SpillCost) && (BestCand != NoCand) &&
1843 CanCauseEvictionChain) {
1847 // No solutions found, fall back to single block splitting.
1848 if (!HasCompact && BestCand == NoCand)
1851 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1854 unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1855 AllocationOrder &Order,
1856 BlockFrequency &BestCost,
1857 unsigned &NumCands, bool IgnoreCSR,
1858 bool *CanCauseEvictionChain) {
1859 unsigned BestCand = NoCand;
1861 while (unsigned PhysReg = Order.next()) {
1862 if (IgnoreCSR && isUnusedCalleeSavedReg(PhysReg))
1865 // Discard bad candidates before we run out of interference cache cursors.
1866 // This will only affect register classes with a lot of registers (>32).
1867 if (NumCands == IntfCache.getMaxCursors()) {
1868 unsigned WorstCount = ~0u;
1870 for (unsigned i = 0; i != NumCands; ++i) {
1871 if (i == BestCand || !GlobalCand[i].PhysReg)
1873 unsigned Count = GlobalCand[i].LiveBundles.count();
1874 if (Count < WorstCount) {
1880 GlobalCand[Worst] = GlobalCand[NumCands];
1881 if (BestCand == NumCands)
1885 if (GlobalCand.size() <= NumCands)
1886 GlobalCand.resize(NumCands+1);
1887 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1888 Cand.reset(IntfCache, PhysReg);
1890 SpillPlacer->prepare(Cand.LiveBundles);
1891 BlockFrequency Cost;
1892 if (!addSplitConstraints(Cand.Intf, Cost)) {
1893 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tno positive bundles\n");
1896 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tstatic = ";
1897 MBFI->printBlockFreq(dbgs(), Cost));
1898 if (Cost >= BestCost) {
1900 if (BestCand == NoCand)
1901 dbgs() << " worse than no bundles\n";
1903 dbgs() << " worse than "
1904 << printReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1908 if (!growRegion(Cand)) {
1909 LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n");
1913 SpillPlacer->finish();
1915 // No live bundles, defer to splitSingleBlocks().
1916 if (!Cand.LiveBundles.any()) {
1917 LLVM_DEBUG(dbgs() << " no bundles.\n");
1921 bool HasEvictionChain = false;
1922 Cost += calcGlobalSplitCost(Cand, Order, &HasEvictionChain);
1924 dbgs() << ", total = ";
1925 MBFI->printBlockFreq(dbgs(), Cost) << " with bundles";
1926 for (int i : Cand.LiveBundles.set_bits())
1927 dbgs() << " EB#" << i;
1930 if (Cost < BestCost) {
1931 BestCand = NumCands;
1933 // See splitCanCauseEvictionChain for detailed description of bad
1934 // eviction chain scenarios.
1935 if (CanCauseEvictionChain)
1936 *CanCauseEvictionChain = HasEvictionChain;
1941 if (CanCauseEvictionChain && BestCand != NoCand) {
1942 // See splitCanCauseEvictionChain for detailed description of bad
1943 // eviction chain scenarios.
1944 LLVM_DEBUG(dbgs() << "Best split candidate of vreg "
1945 << printReg(VirtReg.reg, TRI) << " may ");
1946 if (!(*CanCauseEvictionChain))
1947 LLVM_DEBUG(dbgs() << "not ");
1948 LLVM_DEBUG(dbgs() << "cause bad eviction chain\n");
1954 unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1956 SmallVectorImpl<Register> &NewVRegs) {
1957 SmallVector<unsigned, 8> UsedCands;
1958 // Prepare split editor.
1959 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
1960 SE->reset(LREdit, SplitSpillMode);
1962 // Assign all edge bundles to the preferred candidate, or NoCand.
1963 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1965 // Assign bundles for the best candidate region.
1966 if (BestCand != NoCand) {
1967 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1968 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1969 UsedCands.push_back(BestCand);
1970 Cand.IntvIdx = SE->openIntv();
1971 LLVM_DEBUG(dbgs() << "Split for " << printReg(Cand.PhysReg, TRI) << " in "
1972 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1977 // Assign bundles for the compact region.
1979 GlobalSplitCandidate &Cand = GlobalCand.front();
1980 assert(!Cand.PhysReg && "Compact region has no physreg");
1981 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1982 UsedCands.push_back(0);
1983 Cand.IntvIdx = SE->openIntv();
1984 LLVM_DEBUG(dbgs() << "Split for compact region in " << B
1985 << " bundles, intv " << Cand.IntvIdx << ".\n");
1990 splitAroundRegion(LREdit, UsedCands);
1994 //===----------------------------------------------------------------------===//
1995 // Per-Block Splitting
1996 //===----------------------------------------------------------------------===//
1998 /// tryBlockSplit - Split a global live range around every block with uses. This
1999 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
2000 /// they don't allocate.
2001 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
2002 SmallVectorImpl<Register> &NewVRegs) {
2003 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
2004 Register Reg = VirtReg.reg;
2005 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
2006 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
2007 SE->reset(LREdit, SplitSpillMode);
2008 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
2009 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
2010 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
2011 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
2012 SE->splitSingleBlock(BI);
2014 // No blocks were split.
2018 // We did split for some blocks.
2019 SmallVector<unsigned, 8> IntvMap;
2020 SE->finish(&IntvMap);
2022 // Tell LiveDebugVariables about the new ranges.
2023 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
2025 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2027 // Sort out the new intervals created by splitting. The remainder interval
2028 // goes straight to spilling, the new local ranges get to stay RS_New.
2029 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
2030 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
2031 if (getStage(LI) == RS_New && IntvMap[i] == 0)
2032 setStage(LI, RS_Spill);
2036 MF->verify(this, "After splitting live range around basic blocks");
2040 //===----------------------------------------------------------------------===//
2041 // Per-Instruction Splitting
2042 //===----------------------------------------------------------------------===//
2044 /// Get the number of allocatable registers that match the constraints of \p Reg
2045 /// on \p MI and that are also in \p SuperRC.
2046 static unsigned getNumAllocatableRegsForConstraints(
2047 const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
2048 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
2049 const RegisterClassInfo &RCI) {
2050 assert(SuperRC && "Invalid register class");
2052 const TargetRegisterClass *ConstrainedRC =
2053 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
2054 /* ExploreBundle */ true);
2057 return RCI.getNumAllocatableRegs(ConstrainedRC);
2060 /// tryInstructionSplit - Split a live range around individual instructions.
2061 /// This is normally not worthwhile since the spiller is doing essentially the
2062 /// same thing. However, when the live range is in a constrained register
2063 /// class, it may help to insert copies such that parts of the live range can
2064 /// be moved to a larger register class.
2066 /// This is similar to spilling to a larger register class.
2068 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
2069 SmallVectorImpl<Register> &NewVRegs) {
2070 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
2071 // There is no point to this if there are no larger sub-classes.
2072 if (!RegClassInfo.isProperSubClass(CurRC))
2075 // Always enable split spill mode, since we're effectively spilling to a
2077 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
2078 SE->reset(LREdit, SplitEditor::SM_Size);
2080 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
2081 if (Uses.size() <= 1)
2084 LLVM_DEBUG(dbgs() << "Split around " << Uses.size()
2085 << " individual instrs.\n");
2087 const TargetRegisterClass *SuperRC =
2088 TRI->getLargestLegalSuperClass(CurRC, *MF);
2089 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
2090 // Split around every non-copy instruction if this split will relax
2091 // the constraints on the virtual register.
2092 // Otherwise, splitting just inserts uncoalescable copies that do not help
2094 for (unsigned i = 0; i != Uses.size(); ++i) {
2095 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
2096 if (MI->isFullCopy() ||
2097 SuperRCNumAllocatableRegs ==
2098 getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
2100 LLVM_DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
2104 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
2105 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
2106 SE->useIntv(SegStart, SegStop);
2109 if (LREdit.empty()) {
2110 LLVM_DEBUG(dbgs() << "All uses were copies.\n");
2114 SmallVector<unsigned, 8> IntvMap;
2115 SE->finish(&IntvMap);
2116 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
2117 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2119 // Assign all new registers to RS_Spill. This was the last chance.
2120 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
2124 //===----------------------------------------------------------------------===//
2126 //===----------------------------------------------------------------------===//
2128 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
2129 /// in order to use PhysReg between two entries in SA->UseSlots.
2131 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
2133 void RAGreedy::calcGapWeights(unsigned PhysReg,
2134 SmallVectorImpl<float> &GapWeight) {
2135 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
2136 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
2137 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
2138 const unsigned NumGaps = Uses.size()-1;
2140 // Start and end points for the interference check.
2141 SlotIndex StartIdx =
2142 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
2144 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
2146 GapWeight.assign(NumGaps, 0.0f);
2148 // Add interference from each overlapping register.
2149 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2150 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
2151 .checkInterference())
2154 // We know that VirtReg is a continuous interval from FirstInstr to
2155 // LastInstr, so we don't need InterferenceQuery.
2157 // Interference that overlaps an instruction is counted in both gaps
2158 // surrounding the instruction. The exception is interference before
2159 // StartIdx and after StopIdx.
2161 LiveIntervalUnion::SegmentIter IntI =
2162 Matrix->getLiveUnions()[*Units] .find(StartIdx);
2163 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
2164 // Skip the gaps before IntI.
2165 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
2166 if (++Gap == NumGaps)
2171 // Update the gaps covered by IntI.
2172 const float weight = IntI.value()->weight;
2173 for (; Gap != NumGaps; ++Gap) {
2174 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
2175 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
2183 // Add fixed interference.
2184 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2185 const LiveRange &LR = LIS->getRegUnit(*Units);
2186 LiveRange::const_iterator I = LR.find(StartIdx);
2187 LiveRange::const_iterator E = LR.end();
2189 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
2190 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
2191 while (Uses[Gap+1].getBoundaryIndex() < I->start)
2192 if (++Gap == NumGaps)
2197 for (; Gap != NumGaps; ++Gap) {
2198 GapWeight[Gap] = huge_valf;
2199 if (Uses[Gap+1].getBaseIndex() >= I->end)
2208 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
2211 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
2212 SmallVectorImpl<Register> &NewVRegs) {
2213 // TODO: the function currently only handles a single UseBlock; it should be
2214 // possible to generalize.
2215 if (SA->getUseBlocks().size() != 1)
2218 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
2220 // Note that it is possible to have an interval that is live-in or live-out
2221 // while only covering a single block - A phi-def can use undef values from
2222 // predecessors, and the block could be a single-block loop.
2223 // We don't bother doing anything clever about such a case, we simply assume
2224 // that the interval is continuous from FirstInstr to LastInstr. We should
2225 // make sure that we don't do anything illegal to such an interval, though.
2227 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
2228 if (Uses.size() <= 2)
2230 const unsigned NumGaps = Uses.size()-1;
2233 dbgs() << "tryLocalSplit: ";
2234 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
2235 dbgs() << ' ' << Uses[i];
2239 // If VirtReg is live across any register mask operands, compute a list of
2240 // gaps with register masks.
2241 SmallVector<unsigned, 8> RegMaskGaps;
2242 if (Matrix->checkRegMaskInterference(VirtReg)) {
2243 // Get regmask slots for the whole block.
2244 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
2245 LLVM_DEBUG(dbgs() << RMS.size() << " regmasks in block:");
2246 // Constrain to VirtReg's live range.
2248 llvm::lower_bound(RMS, Uses.front().getRegSlot()) - RMS.begin();
2249 unsigned re = RMS.size();
2250 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
2251 // Look for Uses[i] <= RMS <= Uses[i+1].
2252 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
2253 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
2255 // Skip a regmask on the same instruction as the last use. It doesn't
2256 // overlap the live range.
2257 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
2259 LLVM_DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-'
2261 RegMaskGaps.push_back(i);
2262 // Advance ri to the next gap. A regmask on one of the uses counts in
2264 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
2267 LLVM_DEBUG(dbgs() << '\n');
2270 // Since we allow local split results to be split again, there is a risk of
2271 // creating infinite loops. It is tempting to require that the new live
2272 // ranges have less instructions than the original. That would guarantee
2273 // convergence, but it is too strict. A live range with 3 instructions can be
2274 // split 2+3 (including the COPY), and we want to allow that.
2276 // Instead we use these rules:
2278 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
2279 // noop split, of course).
2280 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
2281 // the new ranges must have fewer instructions than before the split.
2282 // 3. New ranges with the same number of instructions are marked RS_Split2,
2283 // smaller ranges are marked RS_New.
2285 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
2286 // excessive splitting and infinite loops.
2288 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
2290 // Best split candidate.
2291 unsigned BestBefore = NumGaps;
2292 unsigned BestAfter = 0;
2295 const float blockFreq =
2296 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
2297 (1.0f / MBFI->getEntryFreq());
2298 SmallVector<float, 8> GapWeight;
2301 while (unsigned PhysReg = Order.next()) {
2302 // Keep track of the largest spill weight that would need to be evicted in
2303 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
2304 calcGapWeights(PhysReg, GapWeight);
2306 // Remove any gaps with regmask clobbers.
2307 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
2308 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
2309 GapWeight[RegMaskGaps[i]] = huge_valf;
2311 // Try to find the best sequence of gaps to close.
2312 // The new spill weight must be larger than any gap interference.
2314 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
2315 unsigned SplitBefore = 0, SplitAfter = 1;
2317 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
2318 // It is the spill weight that needs to be evicted.
2319 float MaxGap = GapWeight[0];
2322 // Live before/after split?
2323 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
2324 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
2326 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << ' ' << Uses[SplitBefore]
2327 << '-' << Uses[SplitAfter] << " i=" << MaxGap);
2329 // Stop before the interval gets so big we wouldn't be making progress.
2330 if (!LiveBefore && !LiveAfter) {
2331 LLVM_DEBUG(dbgs() << " all\n");
2334 // Should the interval be extended or shrunk?
2337 // How many gaps would the new range have?
2338 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
2340 // Legally, without causing looping?
2341 bool Legal = !ProgressRequired || NewGaps < NumGaps;
2343 if (Legal && MaxGap < huge_valf) {
2344 // Estimate the new spill weight. Each instruction reads or writes the
2345 // register. Conservatively assume there are no read-modify-write
2348 // Try to guess the size of the new interval.
2349 const float EstWeight = normalizeSpillWeight(
2350 blockFreq * (NewGaps + 1),
2351 Uses[SplitBefore].distance(Uses[SplitAfter]) +
2352 (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
2354 // Would this split be possible to allocate?
2355 // Never allocate all gaps, we wouldn't be making progress.
2356 LLVM_DEBUG(dbgs() << " w=" << EstWeight);
2357 if (EstWeight * Hysteresis >= MaxGap) {
2359 float Diff = EstWeight - MaxGap;
2360 if (Diff > BestDiff) {
2361 LLVM_DEBUG(dbgs() << " (best)");
2362 BestDiff = Hysteresis * Diff;
2363 BestBefore = SplitBefore;
2364 BestAfter = SplitAfter;
2371 if (++SplitBefore < SplitAfter) {
2372 LLVM_DEBUG(dbgs() << " shrink\n");
2373 // Recompute the max when necessary.
2374 if (GapWeight[SplitBefore - 1] >= MaxGap) {
2375 MaxGap = GapWeight[SplitBefore];
2376 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
2377 MaxGap = std::max(MaxGap, GapWeight[i]);
2384 // Try to extend the interval.
2385 if (SplitAfter >= NumGaps) {
2386 LLVM_DEBUG(dbgs() << " end\n");
2390 LLVM_DEBUG(dbgs() << " extend\n");
2391 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
2395 // Didn't find any candidates?
2396 if (BestBefore == NumGaps)
2399 LLVM_DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore] << '-'
2400 << Uses[BestAfter] << ", " << BestDiff << ", "
2401 << (BestAfter - BestBefore + 1) << " instrs\n");
2403 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
2407 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
2408 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
2409 SE->useIntv(SegStart, SegStop);
2410 SmallVector<unsigned, 8> IntvMap;
2411 SE->finish(&IntvMap);
2412 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
2414 // If the new range has the same number of instructions as before, mark it as
2415 // RS_Split2 so the next split will be forced to make progress. Otherwise,
2416 // leave the new intervals as RS_New so they can compete.
2417 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
2418 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
2419 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
2420 if (NewGaps >= NumGaps) {
2421 LLVM_DEBUG(dbgs() << "Tagging non-progress ranges: ");
2422 assert(!ProgressRequired && "Didn't make progress when it was required.");
2423 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
2424 if (IntvMap[i] == 1) {
2425 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
2426 LLVM_DEBUG(dbgs() << printReg(LREdit.get(i)));
2428 LLVM_DEBUG(dbgs() << '\n');
2435 //===----------------------------------------------------------------------===//
2436 // Live Range Splitting
2437 //===----------------------------------------------------------------------===//
2439 /// trySplit - Try to split VirtReg or one of its interferences, making it
2441 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
2442 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
2443 SmallVectorImpl<Register> &NewVRegs,
2444 const SmallVirtRegSet &FixedRegisters) {
2445 // Ranges must be Split2 or less.
2446 if (getStage(VirtReg) >= RS_Spill)
2449 // Local intervals are handled separately.
2450 if (LIS->intervalIsInOneMBB(VirtReg)) {
2451 NamedRegionTimer T("local_split", "Local Splitting", TimerGroupName,
2452 TimerGroupDescription, TimePassesIsEnabled);
2453 SA->analyze(&VirtReg);
2454 Register PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
2455 if (PhysReg || !NewVRegs.empty())
2457 return tryInstructionSplit(VirtReg, Order, NewVRegs);
2460 NamedRegionTimer T("global_split", "Global Splitting", TimerGroupName,
2461 TimerGroupDescription, TimePassesIsEnabled);
2463 SA->analyze(&VirtReg);
2465 // FIXME: SplitAnalysis may repair broken live ranges coming from the
2466 // coalescer. That may cause the range to become allocatable which means that
2467 // tryRegionSplit won't be making progress. This check should be replaced with
2468 // an assertion when the coalescer is fixed.
2469 if (SA->didRepairRange()) {
2470 // VirtReg has changed, so all cached queries are invalid.
2471 Matrix->invalidateVirtRegs();
2472 if (Register PhysReg = tryAssign(VirtReg, Order, NewVRegs, FixedRegisters))
2476 // First try to split around a region spanning multiple blocks. RS_Split2
2477 // ranges already made dubious progress with region splitting, so they go
2478 // straight to single block splitting.
2479 if (getStage(VirtReg) < RS_Split2) {
2480 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
2481 if (PhysReg || !NewVRegs.empty())
2485 // Then isolate blocks.
2486 return tryBlockSplit(VirtReg, Order, NewVRegs);
2489 //===----------------------------------------------------------------------===//
2490 // Last Chance Recoloring
2491 //===----------------------------------------------------------------------===//
2493 /// Return true if \p reg has any tied def operand.
2494 static bool hasTiedDef(MachineRegisterInfo *MRI, unsigned reg) {
2495 for (const MachineOperand &MO : MRI->def_operands(reg))
2502 /// mayRecolorAllInterferences - Check if the virtual registers that
2503 /// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
2504 /// recolored to free \p PhysReg.
2505 /// When true is returned, \p RecoloringCandidates has been augmented with all
2506 /// the live intervals that need to be recolored in order to free \p PhysReg
2508 /// \p FixedRegisters contains all the virtual registers that cannot be
2511 RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
2512 SmallLISet &RecoloringCandidates,
2513 const SmallVirtRegSet &FixedRegisters) {
2514 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
2516 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2517 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
2518 // If there is LastChanceRecoloringMaxInterference or more interferences,
2519 // chances are one would not be recolorable.
2520 if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
2521 LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
2522 LLVM_DEBUG(dbgs() << "Early abort: too many interferences.\n");
2523 CutOffInfo |= CO_Interf;
2526 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
2527 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
2528 // If Intf is done and sit on the same register class as VirtReg,
2529 // it would not be recolorable as it is in the same state as VirtReg.
2530 // However, if VirtReg has tied defs and Intf doesn't, then
2531 // there is still a point in examining if it can be recolorable.
2532 if (((getStage(*Intf) == RS_Done &&
2533 MRI->getRegClass(Intf->reg) == CurRC) &&
2534 !(hasTiedDef(MRI, VirtReg.reg) && !hasTiedDef(MRI, Intf->reg))) ||
2535 FixedRegisters.count(Intf->reg)) {
2537 dbgs() << "Early abort: the interference is not recolorable.\n");
2540 RecoloringCandidates.insert(Intf);
2546 /// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
2547 /// its interferences.
2548 /// Last chance recoloring chooses a color for \p VirtReg and recolors every
2549 /// virtual register that was using it. The recoloring process may recursively
2550 /// use the last chance recoloring. Therefore, when a virtual register has been
2551 /// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
2552 /// be last-chance-recolored again during this recoloring "session".
2555 /// vA can use {R1, R2 }
2556 /// vB can use { R2, R3}
2557 /// vC can use {R1 }
2558 /// Where vA, vB, and vC cannot be split anymore (they are reloads for
2559 /// instance) and they all interfere.
2561 /// vA is assigned R1
2562 /// vB is assigned R2
2563 /// vC tries to evict vA but vA is already done.
2564 /// Regular register allocation fails.
2566 /// Last chance recoloring kicks in:
2567 /// vC does as if vA was evicted => vC uses R1.
2568 /// vC is marked as fixed.
2569 /// vA needs to find a color.
2570 /// None are available.
2571 /// vA cannot evict vC: vC is a fixed virtual register now.
2572 /// vA does as if vB was evicted => vA uses R2.
2573 /// vB needs to find a color.
2574 /// R3 is available.
2575 /// Recoloring => vC = R1, vA = R2, vB = R3
2577 /// \p Order defines the preferred allocation order for \p VirtReg.
2578 /// \p NewRegs will contain any new virtual register that have been created
2579 /// (split, spill) during the process and that must be assigned.
2580 /// \p FixedRegisters contains all the virtual registers that cannot be
2582 /// \p Depth gives the current depth of the last chance recoloring.
2583 /// \return a physical register that can be used for VirtReg or ~0u if none
2585 unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
2586 AllocationOrder &Order,
2587 SmallVectorImpl<Register> &NewVRegs,
2588 SmallVirtRegSet &FixedRegisters,
2590 LLVM_DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
2591 // Ranges must be Done.
2592 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
2593 "Last chance recoloring should really be last chance");
2594 // Set the max depth to LastChanceRecoloringMaxDepth.
2595 // We may want to reconsider that if we end up with a too large search space
2596 // for target with hundreds of registers.
2597 // Indeed, in that case we may want to cut the search space earlier.
2598 if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
2599 LLVM_DEBUG(dbgs() << "Abort because max depth has been reached.\n");
2600 CutOffInfo |= CO_Depth;
2604 // Set of Live intervals that will need to be recolored.
2605 SmallLISet RecoloringCandidates;
2606 // Record the original mapping virtual register to physical register in case
2607 // the recoloring fails.
2608 DenseMap<Register, Register> VirtRegToPhysReg;
2609 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
2610 // this recoloring "session".
2611 assert(!FixedRegisters.count(VirtReg.reg));
2612 FixedRegisters.insert(VirtReg.reg);
2613 SmallVector<Register, 4> CurrentNewVRegs;
2616 while (Register PhysReg = Order.next()) {
2617 LLVM_DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
2618 << printReg(PhysReg, TRI) << '\n');
2619 RecoloringCandidates.clear();
2620 VirtRegToPhysReg.clear();
2621 CurrentNewVRegs.clear();
2623 // It is only possible to recolor virtual register interference.
2624 if (Matrix->checkInterference(VirtReg, PhysReg) >
2625 LiveRegMatrix::IK_VirtReg) {
2627 dbgs() << "Some interferences are not with virtual registers.\n");
2632 // Early give up on this PhysReg if it is obvious we cannot recolor all
2633 // the interferences.
2634 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2636 LLVM_DEBUG(dbgs() << "Some interferences cannot be recolored.\n");
2640 // RecoloringCandidates contains all the virtual registers that interfer
2641 // with VirtReg on PhysReg (or one of its aliases).
2642 // Enqueue them for recoloring and perform the actual recoloring.
2643 PQueue RecoloringQueue;
2644 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2645 EndIt = RecoloringCandidates.end();
2646 It != EndIt; ++It) {
2647 Register ItVirtReg = (*It)->reg;
2648 enqueue(RecoloringQueue, *It);
2649 assert(VRM->hasPhys(ItVirtReg) &&
2650 "Interferences are supposed to be with allocated variables");
2652 // Record the current allocation.
2653 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2654 // unset the related struct.
2655 Matrix->unassign(**It);
2658 // Do as if VirtReg was assigned to PhysReg so that the underlying
2659 // recoloring has the right information about the interferes and
2660 // available colors.
2661 Matrix->assign(VirtReg, PhysReg);
2663 // Save the current recoloring state.
2664 // If we cannot recolor all the interferences, we will have to start again
2665 // at this point for the next physical register.
2666 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
2667 if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs,
2668 FixedRegisters, Depth)) {
2669 // Push the queued vregs into the main queue.
2670 for (Register NewVReg : CurrentNewVRegs)
2671 NewVRegs.push_back(NewVReg);
2672 // Do not mess up with the global assignment process.
2673 // I.e., VirtReg must be unassigned.
2674 Matrix->unassign(VirtReg);
2678 LLVM_DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2679 << printReg(PhysReg, TRI) << '\n');
2681 // The recoloring attempt failed, undo the changes.
2682 FixedRegisters = SaveFixedRegisters;
2683 Matrix->unassign(VirtReg);
2685 // For a newly created vreg which is also in RecoloringCandidates,
2686 // don't add it to NewVRegs because its physical register will be restored
2687 // below. Other vregs in CurrentNewVRegs are created by calling
2688 // selectOrSplit and should be added into NewVRegs.
2689 for (SmallVectorImpl<Register>::iterator Next = CurrentNewVRegs.begin(),
2690 End = CurrentNewVRegs.end();
2691 Next != End; ++Next) {
2692 if (RecoloringCandidates.count(&LIS->getInterval(*Next)))
2694 NewVRegs.push_back(*Next);
2697 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2698 EndIt = RecoloringCandidates.end();
2699 It != EndIt; ++It) {
2700 Register ItVirtReg = (*It)->reg;
2701 if (VRM->hasPhys(ItVirtReg))
2702 Matrix->unassign(**It);
2703 Register ItPhysReg = VirtRegToPhysReg[ItVirtReg];
2704 Matrix->assign(**It, ItPhysReg);
2708 // Last chance recoloring did not worked either, give up.
2712 /// tryRecoloringCandidates - Try to assign a new color to every register
2713 /// in \RecoloringQueue.
2714 /// \p NewRegs will contain any new virtual register created during the
2715 /// recoloring process.
2716 /// \p FixedRegisters[in/out] contains all the registers that have been
2718 /// \return true if all virtual registers in RecoloringQueue were successfully
2719 /// recolored, false otherwise.
2720 bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2721 SmallVectorImpl<Register> &NewVRegs,
2722 SmallVirtRegSet &FixedRegisters,
2724 while (!RecoloringQueue.empty()) {
2725 LiveInterval *LI = dequeue(RecoloringQueue);
2726 LLVM_DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2727 Register PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters,
2729 // When splitting happens, the live-range may actually be empty.
2730 // In that case, this is okay to continue the recoloring even
2731 // if we did not find an alternative color for it. Indeed,
2732 // there will not be anything to color for LI in the end.
2733 if (PhysReg == ~0u || (!PhysReg && !LI->empty()))
2737 assert(LI->empty() && "Only empty live-range do not require a register");
2738 LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
2739 << " succeeded. Empty LI.\n");
2742 LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
2743 << " succeeded with: " << printReg(PhysReg, TRI) << '\n');
2745 Matrix->assign(*LI, PhysReg);
2746 FixedRegisters.insert(LI->reg);
2751 //===----------------------------------------------------------------------===//
2753 //===----------------------------------------------------------------------===//
2755 Register RAGreedy::selectOrSplit(LiveInterval &VirtReg,
2756 SmallVectorImpl<Register> &NewVRegs) {
2757 CutOffInfo = CO_None;
2758 LLVMContext &Ctx = MF->getFunction().getContext();
2759 SmallVirtRegSet FixedRegisters;
2760 Register Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2761 if (Reg == ~0U && (CutOffInfo != CO_None)) {
2762 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2763 if (CutOffEncountered == CO_Depth)
2764 Ctx.emitError("register allocation failed: maximum depth for recoloring "
2765 "reached. Use -fexhaustive-register-search to skip "
2767 else if (CutOffEncountered == CO_Interf)
2768 Ctx.emitError("register allocation failed: maximum interference for "
2769 "recoloring reached. Use -fexhaustive-register-search "
2771 else if (CutOffEncountered == (CO_Depth | CO_Interf))
2772 Ctx.emitError("register allocation failed: maximum interference and "
2773 "depth for recoloring reached. Use "
2774 "-fexhaustive-register-search to skip cutoffs");
2779 /// Using a CSR for the first time has a cost because it causes push|pop
2780 /// to be added to prologue|epilogue. Splitting a cold section of the live
2781 /// range can have lower cost than using the CSR for the first time;
2782 /// Spilling a live range in the cold path can have lower cost than using
2783 /// the CSR for the first time. Returns the physical register if we decide
2784 /// to use the CSR; otherwise return 0.
2785 unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
2786 AllocationOrder &Order,
2788 unsigned &CostPerUseLimit,
2789 SmallVectorImpl<Register> &NewVRegs) {
2790 if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2791 // We choose spill over using the CSR for the first time if the spill cost
2792 // is lower than CSRCost.
2793 SA->analyze(&VirtReg);
2794 if (calcSpillCost() >= CSRCost)
2797 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2798 // we will not use a callee-saved register in tryEvict.
2799 CostPerUseLimit = 1;
2802 if (getStage(VirtReg) < RS_Split) {
2803 // We choose pre-splitting over using the CSR for the first time if
2804 // the cost of splitting is lower than CSRCost.
2805 SA->analyze(&VirtReg);
2806 unsigned NumCands = 0;
2807 BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2808 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2809 NumCands, true /*IgnoreCSR*/);
2810 if (BestCand == NoCand)
2811 // Use the CSR if we can't find a region split below CSRCost.
2814 // Perform the actual pre-splitting.
2815 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2821 void RAGreedy::aboutToRemoveInterval(LiveInterval &LI) {
2822 // Do not keep invalid information around.
2823 SetOfBrokenHints.remove(&LI);
2826 void RAGreedy::initializeCSRCost() {
2827 // We use the larger one out of the command-line option and the value report
2829 CSRCost = BlockFrequency(
2830 std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2831 if (!CSRCost.getFrequency())
2834 // Raw cost is relative to Entry == 2^14; scale it appropriately.
2835 uint64_t ActualEntry = MBFI->getEntryFreq();
2840 uint64_t FixedEntry = 1 << 14;
2841 if (ActualEntry < FixedEntry)
2842 CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2843 else if (ActualEntry <= UINT32_MAX)
2844 // Invert the fraction and divide.
2845 CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2847 // Can't use BranchProbability in general, since it takes 32-bit numbers.
2848 CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2851 /// Collect the hint info for \p Reg.
2852 /// The results are stored into \p Out.
2853 /// \p Out is not cleared before being populated.
2854 void RAGreedy::collectHintInfo(unsigned Reg, HintsInfo &Out) {
2855 for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) {
2856 if (!Instr.isFullCopy())
2858 // Look for the other end of the copy.
2859 Register OtherReg = Instr.getOperand(0).getReg();
2860 if (OtherReg == Reg) {
2861 OtherReg = Instr.getOperand(1).getReg();
2862 if (OtherReg == Reg)
2865 // Get the current assignment.
2866 Register OtherPhysReg = Register::isPhysicalRegister(OtherReg)
2868 : VRM->getPhys(OtherReg);
2869 // Push the collected information.
2870 Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
2875 /// Using the given \p List, compute the cost of the broken hints if
2876 /// \p PhysReg was used.
2877 /// \return The cost of \p List for \p PhysReg.
2878 BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
2880 BlockFrequency Cost = 0;
2881 for (const HintInfo &Info : List) {
2882 if (Info.PhysReg != PhysReg)
2888 /// Using the register assigned to \p VirtReg, try to recolor
2889 /// all the live ranges that are copy-related with \p VirtReg.
2890 /// The recoloring is then propagated to all the live-ranges that have
2891 /// been recolored and so on, until no more copies can be coalesced or
2892 /// it is not profitable.
2893 /// For a given live range, profitability is determined by the sum of the
2894 /// frequencies of the non-identity copies it would introduce with the old
2895 /// and new register.
2896 void RAGreedy::tryHintRecoloring(LiveInterval &VirtReg) {
2897 // We have a broken hint, check if it is possible to fix it by
2898 // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
2899 // some register and PhysReg may be available for the other live-ranges.
2900 SmallSet<unsigned, 4> Visited;
2901 SmallVector<unsigned, 2> RecoloringCandidates;
2903 unsigned Reg = VirtReg.reg;
2904 Register PhysReg = VRM->getPhys(Reg);
2905 // Start the recoloring algorithm from the input live-interval, then
2906 // it will propagate to the ones that are copy-related with it.
2907 Visited.insert(Reg);
2908 RecoloringCandidates.push_back(Reg);
2910 LLVM_DEBUG(dbgs() << "Trying to reconcile hints for: " << printReg(Reg, TRI)
2911 << '(' << printReg(PhysReg, TRI) << ")\n");
2914 Reg = RecoloringCandidates.pop_back_val();
2916 // We cannot recolor physical register.
2917 if (Register::isPhysicalRegister(Reg))
2920 assert(VRM->hasPhys(Reg) && "We have unallocated variable!!");
2922 // Get the live interval mapped with this virtual register to be able
2923 // to check for the interference with the new color.
2924 LiveInterval &LI = LIS->getInterval(Reg);
2925 Register CurrPhys = VRM->getPhys(Reg);
2926 // Check that the new color matches the register class constraints and
2927 // that it is free for this live range.
2928 if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) ||
2929 Matrix->checkInterference(LI, PhysReg)))
2932 LLVM_DEBUG(dbgs() << printReg(Reg, TRI) << '(' << printReg(CurrPhys, TRI)
2933 << ") is recolorable.\n");
2935 // Gather the hint info.
2937 collectHintInfo(Reg, Info);
2938 // Check if recoloring the live-range will increase the cost of the
2939 // non-identity copies.
2940 if (CurrPhys != PhysReg) {
2941 LLVM_DEBUG(dbgs() << "Checking profitability:\n");
2942 BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
2943 BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg);
2944 LLVM_DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency()
2945 << "\nNew Cost: " << NewCopiesCost.getFrequency()
2947 if (OldCopiesCost < NewCopiesCost) {
2948 LLVM_DEBUG(dbgs() << "=> Not profitable.\n");
2951 // At this point, the cost is either cheaper or equal. If it is
2952 // equal, we consider this is profitable because it may expose
2953 // more recoloring opportunities.
2954 LLVM_DEBUG(dbgs() << "=> Profitable.\n");
2955 // Recolor the live-range.
2956 Matrix->unassign(LI);
2957 Matrix->assign(LI, PhysReg);
2959 // Push all copy-related live-ranges to keep reconciling the broken
2961 for (const HintInfo &HI : Info) {
2962 if (Visited.insert(HI.Reg).second)
2963 RecoloringCandidates.push_back(HI.Reg);
2965 } while (!RecoloringCandidates.empty());
2968 /// Try to recolor broken hints.
2969 /// Broken hints may be repaired by recoloring when an evicted variable
2970 /// freed up a register for a larger live-range.
2971 /// Consider the following example:
2979 /// Let us assume b gets split:
2989 /// Because of how the allocation work, b, c, and d may be assigned different
2990 /// colors. Now, if a gets evicted later:
3000 /// e = ld SpillSlot
3002 /// This is likely that we can assign the same register for b, c, and d,
3003 /// getting rid of 2 copies.
3004 void RAGreedy::tryHintsRecoloring() {
3005 for (LiveInterval *LI : SetOfBrokenHints) {
3006 assert(Register::isVirtualRegister(LI->reg) &&
3007 "Recoloring is possible only for virtual registers");
3008 // Some dead defs may be around (e.g., because of debug uses).
3010 if (!VRM->hasPhys(LI->reg))
3012 tryHintRecoloring(*LI);
3016 Register RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
3017 SmallVectorImpl<Register> &NewVRegs,
3018 SmallVirtRegSet &FixedRegisters,
3020 unsigned CostPerUseLimit = ~0u;
3021 // First try assigning a free register.
3022 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
3023 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs, FixedRegisters)) {
3024 // If VirtReg got an assignment, the eviction info is no longre relevant.
3025 LastEvicted.clearEvicteeInfo(VirtReg.reg);
3026 // When NewVRegs is not empty, we may have made decisions such as evicting
3027 // a virtual register, go with the earlier decisions and use the physical
3029 if (CSRCost.getFrequency() && isUnusedCalleeSavedReg(PhysReg) &&
3031 Register CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
3032 CostPerUseLimit, NewVRegs);
3033 if (CSRReg || !NewVRegs.empty())
3034 // Return now if we decide to use a CSR or create new vregs due to
3041 LiveRangeStage Stage = getStage(VirtReg);
3042 LLVM_DEBUG(dbgs() << StageName[Stage] << " Cascade "
3043 << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
3045 // Try to evict a less worthy live range, but only for ranges from the primary
3046 // queue. The RS_Split ranges already failed to do this, and they should not
3047 // get a second chance until they have been split.
3048 if (Stage != RS_Split)
3049 if (Register PhysReg =
3050 tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit,
3052 Register Hint = MRI->getSimpleHint(VirtReg.reg);
3053 // If VirtReg has a hint and that hint is broken record this
3054 // virtual register as a recoloring candidate for broken hint.
3055 // Indeed, since we evicted a variable in its neighborhood it is
3056 // likely we can at least partially recolor some of the
3057 // copy-related live-ranges.
3058 if (Hint && Hint != PhysReg)
3059 SetOfBrokenHints.insert(&VirtReg);
3060 // If VirtReg eviction someone, the eviction info for it as an evictee is
3061 // no longre relevant.
3062 LastEvicted.clearEvicteeInfo(VirtReg.reg);
3066 assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs");
3068 // The first time we see a live range, don't try to split or spill.
3069 // Wait until the second time, when all smaller ranges have been allocated.
3070 // This gives a better picture of the interference to split around.
3071 if (Stage < RS_Split) {
3072 setStage(VirtReg, RS_Split);
3073 LLVM_DEBUG(dbgs() << "wait for second round\n");
3074 NewVRegs.push_back(VirtReg.reg);
3078 if (Stage < RS_Spill) {
3079 // Try splitting VirtReg or interferences.
3080 unsigned NewVRegSizeBefore = NewVRegs.size();
3081 Register PhysReg = trySplit(VirtReg, Order, NewVRegs, FixedRegisters);
3082 if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore)) {
3083 // If VirtReg got split, the eviction info is no longer relevant.
3084 LastEvicted.clearEvicteeInfo(VirtReg.reg);
3089 // If we couldn't allocate a register from spilling, there is probably some
3090 // invalid inline assembly. The base class will report it.
3091 if (Stage >= RS_Done || !VirtReg.isSpillable())
3092 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
3095 // Finally spill VirtReg itself.
3096 if (EnableDeferredSpilling && getStage(VirtReg) < RS_Memory) {
3097 // TODO: This is experimental and in particular, we do not model
3098 // the live range splitting done by spilling correctly.
3099 // We would need a deep integration with the spiller to do the
3100 // right thing here. Anyway, that is still good for early testing.
3101 setStage(VirtReg, RS_Memory);
3102 LLVM_DEBUG(dbgs() << "Do as if this register is in memory\n");
3103 NewVRegs.push_back(VirtReg.reg);
3105 NamedRegionTimer T("spill", "Spiller", TimerGroupName,
3106 TimerGroupDescription, TimePassesIsEnabled);
3107 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
3108 spiller().spill(LRE);
3109 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
3111 // Tell LiveDebugVariables about the new ranges. Ranges not being covered by
3112 // the new regs are kept in LDV (still mapping to the old register), until
3113 // we rewrite spilled locations in LDV at a later stage.
3114 DebugVars->splitRegister(VirtReg.reg, LRE.regs(), *LIS);
3117 MF->verify(this, "After spilling");
3120 // The live virtual register requesting allocation was spilled, so tell
3121 // the caller not to allocate anything during this round.
3125 void RAGreedy::reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
3126 unsigned &FoldedReloads,
3128 unsigned &FoldedSpills) {
3134 // Sum up the spill and reloads in subloops.
3135 for (MachineLoop *SubLoop : *L) {
3136 unsigned SubReloads;
3137 unsigned SubFoldedReloads;
3139 unsigned SubFoldedSpills;
3141 reportNumberOfSplillsReloads(SubLoop, SubReloads, SubFoldedReloads,
3142 SubSpills, SubFoldedSpills);
3143 Reloads += SubReloads;
3144 FoldedReloads += SubFoldedReloads;
3145 Spills += SubSpills;
3146 FoldedSpills += SubFoldedSpills;
3149 const MachineFrameInfo &MFI = MF->getFrameInfo();
3152 for (MachineBasicBlock *MBB : L->getBlocks())
3153 // Handle blocks that were not included in subloops.
3154 if (Loops->getLoopFor(MBB) == L)
3155 for (MachineInstr &MI : *MBB) {
3156 SmallVector<const MachineMemOperand *, 2> Accesses;
3157 auto isSpillSlotAccess = [&MFI](const MachineMemOperand *A) {
3158 return MFI.isSpillSlotObjectIndex(
3159 cast<FixedStackPseudoSourceValue>(A->getPseudoValue())
3163 if (TII->isLoadFromStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI))
3165 else if (TII->hasLoadFromStackSlot(MI, Accesses) &&
3166 llvm::any_of(Accesses, isSpillSlotAccess))
3168 else if (TII->isStoreToStackSlot(MI, FI) &&
3169 MFI.isSpillSlotObjectIndex(FI))
3171 else if (TII->hasStoreToStackSlot(MI, Accesses) &&
3172 llvm::any_of(Accesses, isSpillSlotAccess))
3176 if (Reloads || FoldedReloads || Spills || FoldedSpills) {
3177 using namespace ore;
3180 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReload",
3181 L->getStartLoc(), L->getHeader());
3183 R << NV("NumSpills", Spills) << " spills ";
3185 R << NV("NumFoldedSpills", FoldedSpills) << " folded spills ";
3187 R << NV("NumReloads", Reloads) << " reloads ";
3189 R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads ";
3190 R << "generated in loop";
3196 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
3197 LLVM_DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
3198 << "********** Function: " << mf.getName() << '\n');
3201 TRI = MF->getSubtarget().getRegisterInfo();
3202 TII = MF->getSubtarget().getInstrInfo();
3203 RCI.runOnMachineFunction(mf);
3205 EnableLocalReassign = EnableLocalReassignment ||
3206 MF->getSubtarget().enableRALocalReassignment(
3207 MF->getTarget().getOptLevel());
3209 EnableAdvancedRASplitCost =
3210 ConsiderLocalIntervalCost.getNumOccurrences()
3211 ? ConsiderLocalIntervalCost
3212 : MF->getSubtarget().enableAdvancedRASplitCost();
3215 MF->verify(this, "Before greedy register allocator");
3217 RegAllocBase::init(getAnalysis<VirtRegMap>(),
3218 getAnalysis<LiveIntervals>(),
3219 getAnalysis<LiveRegMatrix>());
3220 Indexes = &getAnalysis<SlotIndexes>();
3221 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
3222 DomTree = &getAnalysis<MachineDominatorTree>();
3223 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
3224 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
3225 Loops = &getAnalysis<MachineLoopInfo>();
3226 Bundles = &getAnalysis<EdgeBundles>();
3227 SpillPlacer = &getAnalysis<SpillPlacement>();
3228 DebugVars = &getAnalysis<LiveDebugVariables>();
3229 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3231 initializeCSRCost();
3233 calculateSpillWeightsAndHints(*LIS, mf, VRM, *Loops, *MBFI);
3235 LLVM_DEBUG(LIS->dump());
3237 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
3238 SE.reset(new SplitEditor(*SA, *AA, *LIS, *VRM, *DomTree, *MBFI));
3239 ExtraRegInfo.clear();
3240 ExtraRegInfo.resize(MRI->getNumVirtRegs());
3242 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
3243 GlobalCand.resize(32); // This will grow as needed.
3244 SetOfBrokenHints.clear();
3245 LastEvicted.clear();
3248 tryHintsRecoloring();
3250 reportNumberOfSplillsReloads();