[ORC] Add std::tuple support to SimplePackedSerialization.
[llvm-project.git] / llvm / lib / CodeGen / RegAllocGreedy.cpp
blob688c543ac6274b06ea6516f2d2a58d6b54fcf14f
1 //===- RegAllocGreedy.cpp - greedy register allocator ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the RAGreedy function pass for register allocation in
10 // optimized builds.
12 //===----------------------------------------------------------------------===//
14 #include "AllocationOrder.h"
15 #include "InterferenceCache.h"
16 #include "LiveDebugVariables.h"
17 #include "RegAllocBase.h"
18 #include "SpillPlacement.h"
19 #include "SplitKit.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"
72 #include "llvm/IR/DebugInfoMetadata.h"
73 #include <algorithm>
74 #include <cassert>
75 #include <cstdint>
76 #include <memory>
77 #include <queue>
78 #include <tuple>
79 #include <utility>
81 using namespace llvm;
83 #define DEBUG_TYPE "regalloc"
85 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
86 STATISTIC(NumLocalSplits, "Number of split local live ranges");
87 STATISTIC(NumEvicted, "Number of interferences evicted");
89 static cl::opt<SplitEditor::ComplementSpillMode> SplitSpillMode(
90 "split-spill-mode", cl::Hidden,
91 cl::desc("Spill mode for splitting live ranges"),
92 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
93 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
94 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed")),
95 cl::init(SplitEditor::SM_Speed));
97 static cl::opt<unsigned>
98 LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
99 cl::desc("Last chance recoloring max depth"),
100 cl::init(5));
102 static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
103 "lcr-max-interf", cl::Hidden,
104 cl::desc("Last chance recoloring maximum number of considered"
105 " interference at a time"),
106 cl::init(8));
108 static cl::opt<bool> ExhaustiveSearch(
109 "exhaustive-register-search", cl::NotHidden,
110 cl::desc("Exhaustive Search for registers bypassing the depth "
111 "and interference cutoffs of last chance recoloring"),
112 cl::Hidden);
114 static cl::opt<bool> EnableLocalReassignment(
115 "enable-local-reassign", cl::Hidden,
116 cl::desc("Local reassignment can yield better allocation decisions, but "
117 "may be compile time intensive"),
118 cl::init(false));
120 static cl::opt<bool> EnableDeferredSpilling(
121 "enable-deferred-spilling", cl::Hidden,
122 cl::desc("Instead of spilling a variable right away, defer the actual "
123 "code insertion to the end of the allocation. That way the "
124 "allocator might still find a suitable coloring for this "
125 "variable because of other evicted variables."),
126 cl::init(false));
128 // FIXME: Find a good default for this flag and remove the flag.
129 static cl::opt<unsigned>
130 CSRFirstTimeCost("regalloc-csr-first-time-cost",
131 cl::desc("Cost for first time use of callee-saved register."),
132 cl::init(0), cl::Hidden);
134 static cl::opt<bool> ConsiderLocalIntervalCost(
135 "consider-local-interval-cost", cl::Hidden,
136 cl::desc("Consider the cost of local intervals created by a split "
137 "candidate when choosing the best split candidate."),
138 cl::init(false));
140 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
141 createGreedyRegisterAllocator);
143 namespace {
145 class RAGreedy : public MachineFunctionPass,
146 public RegAllocBase,
147 private LiveRangeEdit::Delegate {
148 // Convenient shortcuts.
149 using PQueue = std::priority_queue<std::pair<unsigned, unsigned>>;
150 using SmallLISet = SmallPtrSet<LiveInterval *, 4>;
151 using SmallVirtRegSet = SmallSet<Register, 16>;
153 // context
154 MachineFunction *MF;
156 // Shortcuts to some useful interface.
157 const TargetInstrInfo *TII;
158 const TargetRegisterInfo *TRI;
159 RegisterClassInfo RCI;
161 // analyses
162 SlotIndexes *Indexes;
163 MachineBlockFrequencyInfo *MBFI;
164 MachineDominatorTree *DomTree;
165 MachineLoopInfo *Loops;
166 MachineOptimizationRemarkEmitter *ORE;
167 EdgeBundles *Bundles;
168 SpillPlacement *SpillPlacer;
169 LiveDebugVariables *DebugVars;
170 AliasAnalysis *AA;
172 // state
173 std::unique_ptr<Spiller> SpillerInstance;
174 PQueue Queue;
175 unsigned NextCascade;
176 std::unique_ptr<VirtRegAuxInfo> VRAI;
178 // Live ranges pass through a number of stages as we try to allocate them.
179 // Some of the stages may also create new live ranges:
181 // - Region splitting.
182 // - Per-block splitting.
183 // - Local splitting.
184 // - Spilling.
186 // Ranges produced by one of the stages skip the previous stages when they are
187 // dequeued. This improves performance because we can skip interference checks
188 // that are unlikely to give any results. It also guarantees that the live
189 // range splitting algorithm terminates, something that is otherwise hard to
190 // ensure.
191 enum LiveRangeStage {
192 /// Newly created live range that has never been queued.
193 RS_New,
195 /// Only attempt assignment and eviction. Then requeue as RS_Split.
196 RS_Assign,
198 /// Attempt live range splitting if assignment is impossible.
199 RS_Split,
201 /// Attempt more aggressive live range splitting that is guaranteed to make
202 /// progress. This is used for split products that may not be making
203 /// progress.
204 RS_Split2,
206 /// Live range will be spilled. No more splitting will be attempted.
207 RS_Spill,
210 /// Live range is in memory. Because of other evictions, it might get moved
211 /// in a register in the end.
212 RS_Memory,
214 /// There is nothing more we can do to this live range. Abort compilation
215 /// if it can't be assigned.
216 RS_Done
219 // Enum CutOffStage to keep a track whether the register allocation failed
220 // because of the cutoffs encountered in last chance recoloring.
221 // Note: This is used as bitmask. New value should be next power of 2.
222 enum CutOffStage {
223 // No cutoffs encountered
224 CO_None = 0,
226 // lcr-max-depth cutoff encountered
227 CO_Depth = 1,
229 // lcr-max-interf cutoff encountered
230 CO_Interf = 2
233 uint8_t CutOffInfo;
235 #ifndef NDEBUG
236 static const char *const StageName[];
237 #endif
239 // RegInfo - Keep additional information about each live range.
240 struct RegInfo {
241 LiveRangeStage Stage = RS_New;
243 // Cascade - Eviction loop prevention. See canEvictInterference().
244 unsigned Cascade = 0;
246 RegInfo() = default;
249 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
251 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
252 return ExtraRegInfo[VirtReg.reg()].Stage;
255 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
256 ExtraRegInfo.resize(MRI->getNumVirtRegs());
257 ExtraRegInfo[VirtReg.reg()].Stage = Stage;
260 template<typename Iterator>
261 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
262 ExtraRegInfo.resize(MRI->getNumVirtRegs());
263 for (;Begin != End; ++Begin) {
264 Register Reg = *Begin;
265 if (ExtraRegInfo[Reg].Stage == RS_New)
266 ExtraRegInfo[Reg].Stage = NewStage;
270 /// Cost of evicting interference.
271 struct EvictionCost {
272 unsigned BrokenHints = 0; ///< Total number of broken hints.
273 float MaxWeight = 0; ///< Maximum spill weight evicted.
275 EvictionCost() = default;
277 bool isMax() const { return BrokenHints == ~0u; }
279 void setMax() { BrokenHints = ~0u; }
281 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
283 bool operator<(const EvictionCost &O) const {
284 return std::tie(BrokenHints, MaxWeight) <
285 std::tie(O.BrokenHints, O.MaxWeight);
289 /// EvictionTrack - Keeps track of past evictions in order to optimize region
290 /// split decision.
291 class EvictionTrack {
293 public:
294 using EvictorInfo =
295 std::pair<Register /* evictor */, MCRegister /* physreg */>;
296 using EvicteeInfo = llvm::DenseMap<Register /* evictee */, EvictorInfo>;
298 private:
299 /// Each Vreg that has been evicted in the last stage of selectOrSplit will
300 /// be mapped to the evictor Vreg and the PhysReg it was evicted from.
301 EvicteeInfo Evictees;
303 public:
304 /// Clear all eviction information.
305 void clear() { Evictees.clear(); }
307 /// Clear eviction information for the given evictee Vreg.
308 /// E.g. when Vreg get's a new allocation, the old eviction info is no
309 /// longer relevant.
310 /// \param Evictee The evictee Vreg for whom we want to clear collected
311 /// eviction info.
312 void clearEvicteeInfo(Register Evictee) { Evictees.erase(Evictee); }
314 /// Track new eviction.
315 /// The Evictor vreg has evicted the Evictee vreg from Physreg.
316 /// \param PhysReg The physical register Evictee was evicted from.
317 /// \param Evictor The evictor Vreg that evicted Evictee.
318 /// \param Evictee The evictee Vreg.
319 void addEviction(MCRegister PhysReg, Register Evictor, Register Evictee) {
320 Evictees[Evictee].first = Evictor;
321 Evictees[Evictee].second = PhysReg;
324 /// Return the Evictor Vreg which evicted Evictee Vreg from PhysReg.
325 /// \param Evictee The evictee vreg.
326 /// \return The Evictor vreg which evicted Evictee vreg from PhysReg. 0 if
327 /// nobody has evicted Evictee from PhysReg.
328 EvictorInfo getEvictor(Register Evictee) {
329 if (Evictees.count(Evictee)) {
330 return Evictees[Evictee];
333 return EvictorInfo(0, 0);
337 // Keeps track of past evictions in order to optimize region split decision.
338 EvictionTrack LastEvicted;
340 // splitting state.
341 std::unique_ptr<SplitAnalysis> SA;
342 std::unique_ptr<SplitEditor> SE;
344 /// Cached per-block interference maps
345 InterferenceCache IntfCache;
347 /// All basic blocks where the current register has uses.
348 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
350 /// Global live range splitting candidate info.
351 struct GlobalSplitCandidate {
352 // Register intended for assignment, or 0.
353 MCRegister PhysReg;
355 // SplitKit interval index for this candidate.
356 unsigned IntvIdx;
358 // Interference for PhysReg.
359 InterferenceCache::Cursor Intf;
361 // Bundles where this candidate should be live.
362 BitVector LiveBundles;
363 SmallVector<unsigned, 8> ActiveBlocks;
365 void reset(InterferenceCache &Cache, MCRegister Reg) {
366 PhysReg = Reg;
367 IntvIdx = 0;
368 Intf.setPhysReg(Cache, Reg);
369 LiveBundles.clear();
370 ActiveBlocks.clear();
373 // Set B[I] = C for every live bundle where B[I] was NoCand.
374 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
375 unsigned Count = 0;
376 for (unsigned I : LiveBundles.set_bits())
377 if (B[I] == NoCand) {
378 B[I] = C;
379 Count++;
381 return Count;
385 /// Candidate info for each PhysReg in AllocationOrder.
386 /// This vector never shrinks, but grows to the size of the largest register
387 /// class.
388 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
390 enum : unsigned { NoCand = ~0u };
392 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
393 /// NoCand which indicates the stack interval.
394 SmallVector<unsigned, 32> BundleCand;
396 /// Callee-save register cost, calculated once per machine function.
397 BlockFrequency CSRCost;
399 /// Run or not the local reassignment heuristic. This information is
400 /// obtained from the TargetSubtargetInfo.
401 bool EnableLocalReassign;
403 /// Enable or not the consideration of the cost of local intervals created
404 /// by a split candidate when choosing the best split candidate.
405 bool EnableAdvancedRASplitCost;
407 /// Set of broken hints that may be reconciled later because of eviction.
408 SmallSetVector<LiveInterval *, 8> SetOfBrokenHints;
410 /// The register cost values. This list will be recreated for each Machine
411 /// Function
412 ArrayRef<uint8_t> RegCosts;
414 public:
415 RAGreedy(const RegClassFilterFunc F = allocateAllRegClasses);
417 /// Return the pass name.
418 StringRef getPassName() const override { return "Greedy Register Allocator"; }
420 /// RAGreedy analysis usage.
421 void getAnalysisUsage(AnalysisUsage &AU) const override;
422 void releaseMemory() override;
423 Spiller &spiller() override { return *SpillerInstance; }
424 void enqueueImpl(LiveInterval *LI) override;
425 LiveInterval *dequeue() override;
426 MCRegister selectOrSplit(LiveInterval &,
427 SmallVectorImpl<Register> &) override;
428 void aboutToRemoveInterval(LiveInterval &) override;
430 /// Perform register allocation.
431 bool runOnMachineFunction(MachineFunction &mf) override;
433 MachineFunctionProperties getRequiredProperties() const override {
434 return MachineFunctionProperties().set(
435 MachineFunctionProperties::Property::NoPHIs);
438 MachineFunctionProperties getClearedProperties() const override {
439 return MachineFunctionProperties().set(
440 MachineFunctionProperties::Property::IsSSA);
443 static char ID;
445 private:
446 MCRegister selectOrSplitImpl(LiveInterval &, SmallVectorImpl<Register> &,
447 SmallVirtRegSet &, unsigned = 0);
449 bool LRE_CanEraseVirtReg(Register) override;
450 void LRE_WillShrinkVirtReg(Register) override;
451 void LRE_DidCloneVirtReg(Register, Register) override;
452 void enqueue(PQueue &CurQueue, LiveInterval *LI);
453 LiveInterval *dequeue(PQueue &CurQueue);
455 BlockFrequency calcSpillCost();
456 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
457 bool addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
458 bool growRegion(GlobalSplitCandidate &Cand);
459 bool splitCanCauseEvictionChain(Register Evictee, GlobalSplitCandidate &Cand,
460 unsigned BBNumber,
461 const AllocationOrder &Order);
462 bool splitCanCauseLocalSpill(unsigned VirtRegToSplit,
463 GlobalSplitCandidate &Cand, unsigned BBNumber,
464 const AllocationOrder &Order);
465 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate &,
466 const AllocationOrder &Order,
467 bool *CanCauseEvictionChain);
468 bool calcCompactRegion(GlobalSplitCandidate&);
469 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
470 void calcGapWeights(MCRegister, SmallVectorImpl<float> &);
471 Register canReassign(LiveInterval &VirtReg, Register PrevReg) const;
472 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool) const;
473 bool canEvictInterference(LiveInterval &, MCRegister, bool, EvictionCost &,
474 const SmallVirtRegSet &) const;
475 bool canEvictInterferenceInRange(const LiveInterval &VirtReg,
476 MCRegister PhysReg, SlotIndex Start,
477 SlotIndex End, EvictionCost &MaxCost) const;
478 MCRegister getCheapestEvicteeWeight(const AllocationOrder &Order,
479 const LiveInterval &VirtReg,
480 SlotIndex Start, SlotIndex End,
481 float *BestEvictWeight) const;
482 void evictInterference(LiveInterval &, MCRegister,
483 SmallVectorImpl<Register> &);
484 bool mayRecolorAllInterferences(MCRegister PhysReg, LiveInterval &VirtReg,
485 SmallLISet &RecoloringCandidates,
486 const SmallVirtRegSet &FixedRegisters);
488 MCRegister tryAssign(LiveInterval&, AllocationOrder&,
489 SmallVectorImpl<Register>&,
490 const SmallVirtRegSet&);
491 MCRegister tryEvict(LiveInterval &, AllocationOrder &,
492 SmallVectorImpl<Register> &, uint8_t,
493 const SmallVirtRegSet &);
494 MCRegister tryRegionSplit(LiveInterval &, AllocationOrder &,
495 SmallVectorImpl<Register> &);
496 /// Calculate cost of region splitting.
497 unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
498 AllocationOrder &Order,
499 BlockFrequency &BestCost,
500 unsigned &NumCands, bool IgnoreCSR,
501 bool *CanCauseEvictionChain = nullptr);
502 /// Perform region splitting.
503 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
504 bool HasCompact,
505 SmallVectorImpl<Register> &NewVRegs);
506 /// Check other options before using a callee-saved register for the first
507 /// time.
508 MCRegister tryAssignCSRFirstTime(LiveInterval &VirtReg,
509 AllocationOrder &Order, MCRegister PhysReg,
510 uint8_t &CostPerUseLimit,
511 SmallVectorImpl<Register> &NewVRegs);
512 void initializeCSRCost();
513 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
514 SmallVectorImpl<Register>&);
515 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
516 SmallVectorImpl<Register>&);
517 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
518 SmallVectorImpl<Register>&);
519 unsigned trySplit(LiveInterval&, AllocationOrder&,
520 SmallVectorImpl<Register>&,
521 const SmallVirtRegSet&);
522 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
523 SmallVectorImpl<Register> &,
524 SmallVirtRegSet &, unsigned);
525 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<Register> &,
526 SmallVirtRegSet &, unsigned);
527 void tryHintRecoloring(LiveInterval &);
528 void tryHintsRecoloring();
530 /// Model the information carried by one end of a copy.
531 struct HintInfo {
532 /// The frequency of the copy.
533 BlockFrequency Freq;
534 /// The virtual register or physical register.
535 Register Reg;
536 /// Its currently assigned register.
537 /// In case of a physical register Reg == PhysReg.
538 MCRegister PhysReg;
540 HintInfo(BlockFrequency Freq, Register Reg, MCRegister PhysReg)
541 : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {}
543 using HintsInfo = SmallVector<HintInfo, 4>;
545 BlockFrequency getBrokenHintFreq(const HintsInfo &, MCRegister);
546 void collectHintInfo(Register, HintsInfo &);
548 bool isUnusedCalleeSavedReg(MCRegister PhysReg) const;
550 /// Greedy RA statistic to remark.
551 struct RAGreedyStats {
552 unsigned Reloads = 0;
553 unsigned FoldedReloads = 0;
554 unsigned ZeroCostFoldedReloads = 0;
555 unsigned Spills = 0;
556 unsigned FoldedSpills = 0;
557 unsigned Copies = 0;
558 float ReloadsCost = 0.0f;
559 float FoldedReloadsCost = 0.0f;
560 float SpillsCost = 0.0f;
561 float FoldedSpillsCost = 0.0f;
562 float CopiesCost = 0.0f;
564 bool isEmpty() {
565 return !(Reloads || FoldedReloads || Spills || FoldedSpills ||
566 ZeroCostFoldedReloads || Copies);
569 void add(RAGreedyStats other) {
570 Reloads += other.Reloads;
571 FoldedReloads += other.FoldedReloads;
572 ZeroCostFoldedReloads += other.ZeroCostFoldedReloads;
573 Spills += other.Spills;
574 FoldedSpills += other.FoldedSpills;
575 Copies += other.Copies;
576 ReloadsCost += other.ReloadsCost;
577 FoldedReloadsCost += other.FoldedReloadsCost;
578 SpillsCost += other.SpillsCost;
579 FoldedSpillsCost += other.FoldedSpillsCost;
580 CopiesCost += other.CopiesCost;
583 void report(MachineOptimizationRemarkMissed &R);
586 /// Compute statistic for a basic block.
587 RAGreedyStats computeStats(MachineBasicBlock &MBB);
589 /// Compute and report statistic through a remark.
590 RAGreedyStats reportStats(MachineLoop *L);
592 /// Report the statistic for each loop.
593 void reportStats();
596 } // end anonymous namespace
598 char RAGreedy::ID = 0;
599 char &llvm::RAGreedyID = RAGreedy::ID;
601 INITIALIZE_PASS_BEGIN(RAGreedy, "greedy",
602 "Greedy Register Allocator", false, false)
603 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
604 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
605 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
606 INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
607 INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
608 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
609 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
610 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
611 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
612 INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
613 INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
614 INITIALIZE_PASS_DEPENDENCY(SpillPlacement)
615 INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
616 INITIALIZE_PASS_END(RAGreedy, "greedy",
617 "Greedy Register Allocator", false, false)
619 #ifndef NDEBUG
620 const char *const RAGreedy::StageName[] = {
621 "RS_New",
622 "RS_Assign",
623 "RS_Split",
624 "RS_Split2",
625 "RS_Spill",
626 "RS_Memory",
627 "RS_Done"
629 #endif
631 // Hysteresis to use when comparing floats.
632 // This helps stabilize decisions based on float comparisons.
633 const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
635 FunctionPass* llvm::createGreedyRegisterAllocator() {
636 return new RAGreedy();
639 namespace llvm {
640 FunctionPass* createGreedyRegisterAllocator(
641 std::function<bool(const TargetRegisterInfo &TRI,
642 const TargetRegisterClass &RC)> Ftor);
646 FunctionPass* llvm::createGreedyRegisterAllocator(
647 std::function<bool(const TargetRegisterInfo &TRI,
648 const TargetRegisterClass &RC)> Ftor) {
649 return new RAGreedy(Ftor);
652 RAGreedy::RAGreedy(RegClassFilterFunc F):
653 MachineFunctionPass(ID),
654 RegAllocBase(F) {
657 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
658 AU.setPreservesCFG();
659 AU.addRequired<MachineBlockFrequencyInfo>();
660 AU.addPreserved<MachineBlockFrequencyInfo>();
661 AU.addRequired<AAResultsWrapperPass>();
662 AU.addPreserved<AAResultsWrapperPass>();
663 AU.addRequired<LiveIntervals>();
664 AU.addPreserved<LiveIntervals>();
665 AU.addRequired<SlotIndexes>();
666 AU.addPreserved<SlotIndexes>();
667 AU.addRequired<LiveDebugVariables>();
668 AU.addPreserved<LiveDebugVariables>();
669 AU.addRequired<LiveStacks>();
670 AU.addPreserved<LiveStacks>();
671 AU.addRequired<MachineDominatorTree>();
672 AU.addPreserved<MachineDominatorTree>();
673 AU.addRequired<MachineLoopInfo>();
674 AU.addPreserved<MachineLoopInfo>();
675 AU.addRequired<VirtRegMap>();
676 AU.addPreserved<VirtRegMap>();
677 AU.addRequired<LiveRegMatrix>();
678 AU.addPreserved<LiveRegMatrix>();
679 AU.addRequired<EdgeBundles>();
680 AU.addRequired<SpillPlacement>();
681 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
682 MachineFunctionPass::getAnalysisUsage(AU);
685 //===----------------------------------------------------------------------===//
686 // LiveRangeEdit delegate methods
687 //===----------------------------------------------------------------------===//
689 bool RAGreedy::LRE_CanEraseVirtReg(Register VirtReg) {
690 LiveInterval &LI = LIS->getInterval(VirtReg);
691 if (VRM->hasPhys(VirtReg)) {
692 Matrix->unassign(LI);
693 aboutToRemoveInterval(LI);
694 return true;
696 // Unassigned virtreg is probably in the priority queue.
697 // RegAllocBase will erase it after dequeueing.
698 // Nonetheless, clear the live-range so that the debug
699 // dump will show the right state for that VirtReg.
700 LI.clear();
701 return false;
704 void RAGreedy::LRE_WillShrinkVirtReg(Register VirtReg) {
705 if (!VRM->hasPhys(VirtReg))
706 return;
708 // Register is assigned, put it back on the queue for reassignment.
709 LiveInterval &LI = LIS->getInterval(VirtReg);
710 Matrix->unassign(LI);
711 RegAllocBase::enqueue(&LI);
714 void RAGreedy::LRE_DidCloneVirtReg(Register New, Register Old) {
715 // Cloning a register we haven't even heard about yet? Just ignore it.
716 if (!ExtraRegInfo.inBounds(Old))
717 return;
719 // LRE may clone a virtual register because dead code elimination causes it to
720 // be split into connected components. The new components are much smaller
721 // than the original, so they should get a new chance at being assigned.
722 // same stage as the parent.
723 ExtraRegInfo[Old].Stage = RS_Assign;
724 ExtraRegInfo.grow(New);
725 ExtraRegInfo[New] = ExtraRegInfo[Old];
728 void RAGreedy::releaseMemory() {
729 SpillerInstance.reset();
730 ExtraRegInfo.clear();
731 GlobalCand.clear();
734 void RAGreedy::enqueueImpl(LiveInterval *LI) { enqueue(Queue, LI); }
736 void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
737 // Prioritize live ranges by size, assigning larger ranges first.
738 // The queue holds (size, reg) pairs.
739 const unsigned Size = LI->getSize();
740 const Register Reg = LI->reg();
741 assert(Reg.isVirtual() && "Can only enqueue virtual registers");
742 unsigned Prio;
744 ExtraRegInfo.grow(Reg);
745 if (ExtraRegInfo[Reg].Stage == RS_New)
746 ExtraRegInfo[Reg].Stage = RS_Assign;
748 if (ExtraRegInfo[Reg].Stage == RS_Split) {
749 // Unsplit ranges that couldn't be allocated immediately are deferred until
750 // everything else has been allocated.
751 Prio = Size;
752 } else if (ExtraRegInfo[Reg].Stage == RS_Memory) {
753 // Memory operand should be considered last.
754 // Change the priority such that Memory operand are assigned in
755 // the reverse order that they came in.
756 // TODO: Make this a member variable and probably do something about hints.
757 static unsigned MemOp = 0;
758 Prio = MemOp++;
759 } else {
760 // Giant live ranges fall back to the global assignment heuristic, which
761 // prevents excessive spilling in pathological cases.
762 bool ReverseLocal = TRI->reverseLocalAssignment();
763 const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
764 bool ForceGlobal = !ReverseLocal &&
765 (Size / SlotIndex::InstrDist) > (2 * RC.getNumRegs());
767 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
768 LIS->intervalIsInOneMBB(*LI)) {
769 // Allocate original local ranges in linear instruction order. Since they
770 // are singly defined, this produces optimal coloring in the absence of
771 // global interference and other constraints.
772 if (!ReverseLocal)
773 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
774 else {
775 // Allocating bottom up may allow many short LRGs to be assigned first
776 // to one of the cheap registers. This could be much faster for very
777 // large blocks on targets with many physical registers.
778 Prio = Indexes->getZeroIndex().getInstrDistance(LI->endIndex());
780 Prio |= RC.AllocationPriority << 24;
781 } else {
782 // Allocate global and split ranges in long->short order. Long ranges that
783 // don't fit should be spilled (or split) ASAP so they don't create
784 // interference. Mark a bit to prioritize global above local ranges.
785 Prio = (1u << 29) + Size;
787 Prio |= RC.AllocationPriority << 24;
789 // Mark a higher bit to prioritize global and local above RS_Split.
790 Prio |= (1u << 31);
792 // Boost ranges that have a physical register hint.
793 if (VRM->hasKnownPreference(Reg))
794 Prio |= (1u << 30);
796 // The virtual register number is a tie breaker for same-sized ranges.
797 // Give lower vreg numbers higher priority to assign them first.
798 CurQueue.push(std::make_pair(Prio, ~Reg));
801 LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
803 LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
804 if (CurQueue.empty())
805 return nullptr;
806 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
807 CurQueue.pop();
808 return LI;
811 //===----------------------------------------------------------------------===//
812 // Direct Assignment
813 //===----------------------------------------------------------------------===//
815 /// tryAssign - Try to assign VirtReg to an available register.
816 MCRegister RAGreedy::tryAssign(LiveInterval &VirtReg,
817 AllocationOrder &Order,
818 SmallVectorImpl<Register> &NewVRegs,
819 const SmallVirtRegSet &FixedRegisters) {
820 MCRegister PhysReg;
821 for (auto I = Order.begin(), E = Order.end(); I != E && !PhysReg; ++I) {
822 assert(*I);
823 if (!Matrix->checkInterference(VirtReg, *I)) {
824 if (I.isHint())
825 return *I;
826 else
827 PhysReg = *I;
830 if (!PhysReg.isValid())
831 return PhysReg;
833 // PhysReg is available, but there may be a better choice.
835 // If we missed a simple hint, try to cheaply evict interference from the
836 // preferred register.
837 if (Register Hint = MRI->getSimpleHint(VirtReg.reg()))
838 if (Order.isHint(Hint)) {
839 MCRegister PhysHint = Hint.asMCReg();
840 LLVM_DEBUG(dbgs() << "missed hint " << printReg(PhysHint, TRI) << '\n');
841 EvictionCost MaxCost;
842 MaxCost.setBrokenHints(1);
843 if (canEvictInterference(VirtReg, PhysHint, true, MaxCost,
844 FixedRegisters)) {
845 evictInterference(VirtReg, PhysHint, NewVRegs);
846 return PhysHint;
848 // Record the missed hint, we may be able to recover
849 // at the end if the surrounding allocation changed.
850 SetOfBrokenHints.insert(&VirtReg);
853 // Try to evict interference from a cheaper alternative.
854 uint8_t Cost = RegCosts[PhysReg];
856 // Most registers have 0 additional cost.
857 if (!Cost)
858 return PhysReg;
860 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is available at cost "
861 << Cost << '\n');
862 MCRegister CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost, FixedRegisters);
863 return CheapReg ? CheapReg : PhysReg;
866 //===----------------------------------------------------------------------===//
867 // Interference eviction
868 //===----------------------------------------------------------------------===//
870 Register RAGreedy::canReassign(LiveInterval &VirtReg, Register PrevReg) const {
871 auto Order =
872 AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
873 MCRegister PhysReg;
874 for (auto I = Order.begin(), E = Order.end(); I != E && !PhysReg; ++I) {
875 if ((*I).id() == PrevReg.id())
876 continue;
878 MCRegUnitIterator Units(*I, TRI);
879 for (; Units.isValid(); ++Units) {
880 // Instantiate a "subquery", not to be confused with the Queries array.
881 LiveIntervalUnion::Query subQ(VirtReg, Matrix->getLiveUnions()[*Units]);
882 if (subQ.checkInterference())
883 break;
885 // If no units have interference, break out with the current PhysReg.
886 if (!Units.isValid())
887 PhysReg = *I;
889 if (PhysReg)
890 LLVM_DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
891 << printReg(PrevReg, TRI) << " to "
892 << printReg(PhysReg, TRI) << '\n');
893 return PhysReg;
896 /// shouldEvict - determine if A should evict the assigned live range B. The
897 /// eviction policy defined by this function together with the allocation order
898 /// defined by enqueue() decides which registers ultimately end up being split
899 /// and spilled.
901 /// Cascade numbers are used to prevent infinite loops if this function is a
902 /// cyclic relation.
904 /// @param A The live range to be assigned.
905 /// @param IsHint True when A is about to be assigned to its preferred
906 /// register.
907 /// @param B The live range to be evicted.
908 /// @param BreaksHint True when B is already assigned to its preferred register.
909 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
910 LiveInterval &B, bool BreaksHint) const {
911 bool CanSplit = getStage(B) < RS_Spill;
913 // Be fairly aggressive about following hints as long as the evictee can be
914 // split.
915 if (CanSplit && IsHint && !BreaksHint)
916 return true;
918 if (A.weight() > B.weight()) {
919 LLVM_DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight() << '\n');
920 return true;
922 return false;
925 /// canEvictInterference - Return true if all interferences between VirtReg and
926 /// PhysReg can be evicted.
928 /// @param VirtReg Live range that is about to be assigned.
929 /// @param PhysReg Desired register for assignment.
930 /// @param IsHint True when PhysReg is VirtReg's preferred register.
931 /// @param MaxCost Only look for cheaper candidates and update with new cost
932 /// when returning true.
933 /// @returns True when interference can be evicted cheaper than MaxCost.
934 bool RAGreedy::canEvictInterference(
935 LiveInterval &VirtReg, MCRegister PhysReg, bool IsHint,
936 EvictionCost &MaxCost, const SmallVirtRegSet &FixedRegisters) const {
937 // It is only possible to evict virtual register interference.
938 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
939 return false;
941 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
943 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
944 // involved in an eviction before. If a cascade number was assigned, deny
945 // evicting anything with the same or a newer cascade number. This prevents
946 // infinite eviction loops.
948 // This works out so a register without a cascade number is allowed to evict
949 // anything, and it can be evicted by anything.
950 unsigned Cascade = ExtraRegInfo[VirtReg.reg()].Cascade;
951 if (!Cascade)
952 Cascade = NextCascade;
954 EvictionCost Cost;
955 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
956 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
957 // If there is 10 or more interferences, chances are one is heavier.
958 if (Q.collectInterferingVRegs(10) >= 10)
959 return false;
961 // Check if any interfering live range is heavier than MaxWeight.
962 for (LiveInterval *Intf : reverse(Q.interferingVRegs())) {
963 assert(Register::isVirtualRegister(Intf->reg()) &&
964 "Only expecting virtual register interference from query");
966 // Do not allow eviction of a virtual register if we are in the middle
967 // of last-chance recoloring and this virtual register is one that we
968 // have scavenged a physical register for.
969 if (FixedRegisters.count(Intf->reg()))
970 return false;
972 // Never evict spill products. They cannot split or spill.
973 if (getStage(*Intf) == RS_Done)
974 return false;
975 // Once a live range becomes small enough, it is urgent that we find a
976 // register for it. This is indicated by an infinite spill weight. These
977 // urgent live ranges get to evict almost anything.
979 // Also allow urgent evictions of unspillable ranges from a strictly
980 // larger allocation order.
981 bool Urgent =
982 !VirtReg.isSpillable() &&
983 (Intf->isSpillable() ||
984 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg())) <
985 RegClassInfo.getNumAllocatableRegs(
986 MRI->getRegClass(Intf->reg())));
987 // Only evict older cascades or live ranges without a cascade.
988 unsigned IntfCascade = ExtraRegInfo[Intf->reg()].Cascade;
989 if (Cascade <= IntfCascade) {
990 if (!Urgent)
991 return false;
992 // We permit breaking cascades for urgent evictions. It should be the
993 // last resort, though, so make it really expensive.
994 Cost.BrokenHints += 10;
996 // Would this break a satisfied hint?
997 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg());
998 // Update eviction cost.
999 Cost.BrokenHints += BreaksHint;
1000 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight());
1001 // Abort if this would be too expensive.
1002 if (!(Cost < MaxCost))
1003 return false;
1004 if (Urgent)
1005 continue;
1006 // Apply the eviction policy for non-urgent evictions.
1007 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
1008 return false;
1009 // If !MaxCost.isMax(), then we're just looking for a cheap register.
1010 // Evicting another local live range in this case could lead to suboptimal
1011 // coloring.
1012 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
1013 (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) {
1014 return false;
1018 MaxCost = Cost;
1019 return true;
1022 /// Return true if all interferences between VirtReg and PhysReg between
1023 /// Start and End can be evicted.
1025 /// \param VirtReg Live range that is about to be assigned.
1026 /// \param PhysReg Desired register for assignment.
1027 /// \param Start Start of range to look for interferences.
1028 /// \param End End of range to look for interferences.
1029 /// \param MaxCost Only look for cheaper candidates and update with new cost
1030 /// when returning true.
1031 /// \return True when interference can be evicted cheaper than MaxCost.
1032 bool RAGreedy::canEvictInterferenceInRange(const LiveInterval &VirtReg,
1033 MCRegister PhysReg, SlotIndex Start,
1034 SlotIndex End,
1035 EvictionCost &MaxCost) const {
1036 EvictionCost Cost;
1038 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1039 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
1040 Q.collectInterferingVRegs();
1042 // Check if any interfering live range is heavier than MaxWeight.
1043 for (const LiveInterval *Intf : reverse(Q.interferingVRegs())) {
1044 // Check if interference overlast the segment in interest.
1045 if (!Intf->overlaps(Start, End))
1046 continue;
1048 // Cannot evict non virtual reg interference.
1049 if (!Register::isVirtualRegister(Intf->reg()))
1050 return false;
1051 // Never evict spill products. They cannot split or spill.
1052 if (getStage(*Intf) == RS_Done)
1053 return false;
1055 // Would this break a satisfied hint?
1056 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg());
1057 // Update eviction cost.
1058 Cost.BrokenHints += BreaksHint;
1059 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight());
1060 // Abort if this would be too expensive.
1061 if (!(Cost < MaxCost))
1062 return false;
1066 if (Cost.MaxWeight == 0)
1067 return false;
1069 MaxCost = Cost;
1070 return true;
1073 /// Return the physical register that will be best
1074 /// candidate for eviction by a local split interval that will be created
1075 /// between Start and End.
1077 /// \param Order The allocation order
1078 /// \param VirtReg Live range that is about to be assigned.
1079 /// \param Start Start of range to look for interferences
1080 /// \param End End of range to look for interferences
1081 /// \param BestEvictweight The eviction cost of that eviction
1082 /// \return The PhysReg which is the best candidate for eviction and the
1083 /// eviction cost in BestEvictweight
1084 MCRegister RAGreedy::getCheapestEvicteeWeight(const AllocationOrder &Order,
1085 const LiveInterval &VirtReg,
1086 SlotIndex Start, SlotIndex End,
1087 float *BestEvictweight) const {
1088 EvictionCost BestEvictCost;
1089 BestEvictCost.setMax();
1090 BestEvictCost.MaxWeight = VirtReg.weight();
1091 MCRegister BestEvicteePhys;
1093 // Go over all physical registers and find the best candidate for eviction
1094 for (MCRegister PhysReg : Order.getOrder()) {
1096 if (!canEvictInterferenceInRange(VirtReg, PhysReg, Start, End,
1097 BestEvictCost))
1098 continue;
1100 // Best so far.
1101 BestEvicteePhys = PhysReg;
1103 *BestEvictweight = BestEvictCost.MaxWeight;
1104 return BestEvicteePhys;
1107 /// evictInterference - Evict any interferring registers that prevent VirtReg
1108 /// from being assigned to Physreg. This assumes that canEvictInterference
1109 /// returned true.
1110 void RAGreedy::evictInterference(LiveInterval &VirtReg, MCRegister PhysReg,
1111 SmallVectorImpl<Register> &NewVRegs) {
1112 // Make sure that VirtReg has a cascade number, and assign that cascade
1113 // number to every evicted register. These live ranges than then only be
1114 // evicted by a newer cascade, preventing infinite loops.
1115 unsigned Cascade = ExtraRegInfo[VirtReg.reg()].Cascade;
1116 if (!Cascade)
1117 Cascade = ExtraRegInfo[VirtReg.reg()].Cascade = NextCascade++;
1119 LLVM_DEBUG(dbgs() << "evicting " << printReg(PhysReg, TRI)
1120 << " interference: Cascade " << Cascade << '\n');
1122 // Collect all interfering virtregs first.
1123 SmallVector<LiveInterval*, 8> Intfs;
1124 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1125 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
1126 // We usually have the interfering VRegs cached so collectInterferingVRegs()
1127 // should be fast, we may need to recalculate if when different physregs
1128 // overlap the same register unit so we had different SubRanges queried
1129 // against it.
1130 Q.collectInterferingVRegs();
1131 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
1132 Intfs.append(IVR.begin(), IVR.end());
1135 // Evict them second. This will invalidate the queries.
1136 for (LiveInterval *Intf : Intfs) {
1137 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
1138 if (!VRM->hasPhys(Intf->reg()))
1139 continue;
1141 LastEvicted.addEviction(PhysReg, VirtReg.reg(), Intf->reg());
1143 Matrix->unassign(*Intf);
1144 assert((ExtraRegInfo[Intf->reg()].Cascade < Cascade ||
1145 VirtReg.isSpillable() < Intf->isSpillable()) &&
1146 "Cannot decrease cascade number, illegal eviction");
1147 ExtraRegInfo[Intf->reg()].Cascade = Cascade;
1148 ++NumEvicted;
1149 NewVRegs.push_back(Intf->reg());
1153 /// Returns true if the given \p PhysReg is a callee saved register and has not
1154 /// been used for allocation yet.
1155 bool RAGreedy::isUnusedCalleeSavedReg(MCRegister PhysReg) const {
1156 MCRegister CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
1157 if (!CSR)
1158 return false;
1160 return !Matrix->isPhysRegUsed(PhysReg);
1163 /// tryEvict - Try to evict all interferences for a physreg.
1164 /// @param VirtReg Currently unassigned virtual register.
1165 /// @param Order Physregs to try.
1166 /// @return Physreg to assign VirtReg, or 0.
1167 MCRegister RAGreedy::tryEvict(LiveInterval &VirtReg, AllocationOrder &Order,
1168 SmallVectorImpl<Register> &NewVRegs,
1169 uint8_t CostPerUseLimit,
1170 const SmallVirtRegSet &FixedRegisters) {
1171 NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription,
1172 TimePassesIsEnabled);
1174 // Keep track of the cheapest interference seen so far.
1175 EvictionCost BestCost;
1176 BestCost.setMax();
1177 MCRegister BestPhys;
1178 unsigned OrderLimit = Order.getOrder().size();
1180 // When we are just looking for a reduced cost per use, don't break any
1181 // hints, and only evict smaller spill weights.
1182 if (CostPerUseLimit < uint8_t(~0u)) {
1183 BestCost.BrokenHints = 0;
1184 BestCost.MaxWeight = VirtReg.weight();
1186 // Check of any registers in RC are below CostPerUseLimit.
1187 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg());
1188 uint8_t MinCost = RegClassInfo.getMinCost(RC);
1189 if (MinCost >= CostPerUseLimit) {
1190 LLVM_DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = "
1191 << MinCost << ", no cheaper registers to be found.\n");
1192 return 0;
1195 // It is normal for register classes to have a long tail of registers with
1196 // the same cost. We don't need to look at them if they're too expensive.
1197 if (RegCosts[Order.getOrder().back()] >= CostPerUseLimit) {
1198 OrderLimit = RegClassInfo.getLastCostChange(RC);
1199 LLVM_DEBUG(dbgs() << "Only trying the first " << OrderLimit
1200 << " regs.\n");
1204 for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit); I != E;
1205 ++I) {
1206 MCRegister PhysReg = *I;
1207 assert(PhysReg);
1208 if (RegCosts[PhysReg] >= CostPerUseLimit)
1209 continue;
1210 // The first use of a callee-saved register in a function has cost 1.
1211 // Don't start using a CSR when the CostPerUseLimit is low.
1212 if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
1213 LLVM_DEBUG(
1214 dbgs() << printReg(PhysReg, TRI) << " would clobber CSR "
1215 << printReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
1216 << '\n');
1217 continue;
1220 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost,
1221 FixedRegisters))
1222 continue;
1224 // Best so far.
1225 BestPhys = PhysReg;
1227 // Stop if the hint can be used.
1228 if (I.isHint())
1229 break;
1232 if (BestPhys.isValid())
1233 evictInterference(VirtReg, BestPhys, NewVRegs);
1234 return BestPhys;
1237 //===----------------------------------------------------------------------===//
1238 // Region Splitting
1239 //===----------------------------------------------------------------------===//
1241 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
1242 /// interference pattern in Physreg and its aliases. Add the constraints to
1243 /// SpillPlacement and return the static cost of this split in Cost, assuming
1244 /// that all preferences in SplitConstraints are met.
1245 /// Return false if there are no bundles with positive bias.
1246 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
1247 BlockFrequency &Cost) {
1248 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1250 // Reset interference dependent info.
1251 SplitConstraints.resize(UseBlocks.size());
1252 BlockFrequency StaticCost = 0;
1253 for (unsigned I = 0; I != UseBlocks.size(); ++I) {
1254 const SplitAnalysis::BlockInfo &BI = UseBlocks[I];
1255 SpillPlacement::BlockConstraint &BC = SplitConstraints[I];
1257 BC.Number = BI.MBB->getNumber();
1258 Intf.moveToBlock(BC.Number);
1259 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
1260 BC.Exit = (BI.LiveOut &&
1261 !LIS->getInstructionFromIndex(BI.LastInstr)->isImplicitDef())
1262 ? SpillPlacement::PrefReg
1263 : SpillPlacement::DontCare;
1264 BC.ChangesValue = BI.FirstDef.isValid();
1266 if (!Intf.hasInterference())
1267 continue;
1269 // Number of spill code instructions to insert.
1270 unsigned Ins = 0;
1272 // Interference for the live-in value.
1273 if (BI.LiveIn) {
1274 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number)) {
1275 BC.Entry = SpillPlacement::MustSpill;
1276 ++Ins;
1277 } else if (Intf.first() < BI.FirstInstr) {
1278 BC.Entry = SpillPlacement::PrefSpill;
1279 ++Ins;
1280 } else if (Intf.first() < BI.LastInstr) {
1281 ++Ins;
1284 // Abort if the spill cannot be inserted at the MBB' start
1285 if (((BC.Entry == SpillPlacement::MustSpill) ||
1286 (BC.Entry == SpillPlacement::PrefSpill)) &&
1287 SlotIndex::isEarlierInstr(BI.FirstInstr,
1288 SA->getFirstSplitPoint(BC.Number)))
1289 return false;
1292 // Interference for the live-out value.
1293 if (BI.LiveOut) {
1294 if (Intf.last() >= SA->getLastSplitPoint(BC.Number)) {
1295 BC.Exit = SpillPlacement::MustSpill;
1296 ++Ins;
1297 } else if (Intf.last() > BI.LastInstr) {
1298 BC.Exit = SpillPlacement::PrefSpill;
1299 ++Ins;
1300 } else if (Intf.last() > BI.FirstInstr) {
1301 ++Ins;
1305 // Accumulate the total frequency of inserted spill code.
1306 while (Ins--)
1307 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
1309 Cost = StaticCost;
1311 // Add constraints for use-blocks. Note that these are the only constraints
1312 // that may add a positive bias, it is downhill from here.
1313 SpillPlacer->addConstraints(SplitConstraints);
1314 return SpillPlacer->scanActiveBundles();
1317 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
1318 /// live-through blocks in Blocks.
1319 bool RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
1320 ArrayRef<unsigned> Blocks) {
1321 const unsigned GroupSize = 8;
1322 SpillPlacement::BlockConstraint BCS[GroupSize];
1323 unsigned TBS[GroupSize];
1324 unsigned B = 0, T = 0;
1326 for (unsigned Number : Blocks) {
1327 Intf.moveToBlock(Number);
1329 if (!Intf.hasInterference()) {
1330 assert(T < GroupSize && "Array overflow");
1331 TBS[T] = Number;
1332 if (++T == GroupSize) {
1333 SpillPlacer->addLinks(makeArrayRef(TBS, T));
1334 T = 0;
1336 continue;
1339 assert(B < GroupSize && "Array overflow");
1340 BCS[B].Number = Number;
1342 // Abort if the spill cannot be inserted at the MBB' start
1343 MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
1344 auto FirstNonDebugInstr = MBB->getFirstNonDebugInstr();
1345 if (FirstNonDebugInstr != MBB->end() &&
1346 SlotIndex::isEarlierInstr(LIS->getInstructionIndex(*FirstNonDebugInstr),
1347 SA->getFirstSplitPoint(Number)))
1348 return false;
1349 // Interference for the live-in value.
1350 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
1351 BCS[B].Entry = SpillPlacement::MustSpill;
1352 else
1353 BCS[B].Entry = SpillPlacement::PrefSpill;
1355 // Interference for the live-out value.
1356 if (Intf.last() >= SA->getLastSplitPoint(Number))
1357 BCS[B].Exit = SpillPlacement::MustSpill;
1358 else
1359 BCS[B].Exit = SpillPlacement::PrefSpill;
1361 if (++B == GroupSize) {
1362 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
1363 B = 0;
1367 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
1368 SpillPlacer->addLinks(makeArrayRef(TBS, T));
1369 return true;
1372 bool RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
1373 // Keep track of through blocks that have not been added to SpillPlacer.
1374 BitVector Todo = SA->getThroughBlocks();
1375 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
1376 unsigned AddedTo = 0;
1377 #ifndef NDEBUG
1378 unsigned Visited = 0;
1379 #endif
1381 while (true) {
1382 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
1383 // Find new through blocks in the periphery of PrefRegBundles.
1384 for (unsigned Bundle : NewBundles) {
1385 // Look at all blocks connected to Bundle in the full graph.
1386 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
1387 for (unsigned Block : Blocks) {
1388 if (!Todo.test(Block))
1389 continue;
1390 Todo.reset(Block);
1391 // This is a new through block. Add it to SpillPlacer later.
1392 ActiveBlocks.push_back(Block);
1393 #ifndef NDEBUG
1394 ++Visited;
1395 #endif
1398 // Any new blocks to add?
1399 if (ActiveBlocks.size() == AddedTo)
1400 break;
1402 // Compute through constraints from the interference, or assume that all
1403 // through blocks prefer spilling when forming compact regions.
1404 auto NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
1405 if (Cand.PhysReg) {
1406 if (!addThroughConstraints(Cand.Intf, NewBlocks))
1407 return false;
1408 } else
1409 // Provide a strong negative bias on through blocks to prevent unwanted
1410 // liveness on loop backedges.
1411 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
1412 AddedTo = ActiveBlocks.size();
1414 // Perhaps iterating can enable more bundles?
1415 SpillPlacer->iterate();
1417 LLVM_DEBUG(dbgs() << ", v=" << Visited);
1418 return true;
1421 /// calcCompactRegion - Compute the set of edge bundles that should be live
1422 /// when splitting the current live range into compact regions. Compact
1423 /// regions can be computed without looking at interference. They are the
1424 /// regions formed by removing all the live-through blocks from the live range.
1426 /// Returns false if the current live range is already compact, or if the
1427 /// compact regions would form single block regions anyway.
1428 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1429 // Without any through blocks, the live range is already compact.
1430 if (!SA->getNumThroughBlocks())
1431 return false;
1433 // Compact regions don't correspond to any physreg.
1434 Cand.reset(IntfCache, MCRegister::NoRegister);
1436 LLVM_DEBUG(dbgs() << "Compact region bundles");
1438 // Use the spill placer to determine the live bundles. GrowRegion pretends
1439 // that all the through blocks have interference when PhysReg is unset.
1440 SpillPlacer->prepare(Cand.LiveBundles);
1442 // The static split cost will be zero since Cand.Intf reports no interference.
1443 BlockFrequency Cost;
1444 if (!addSplitConstraints(Cand.Intf, Cost)) {
1445 LLVM_DEBUG(dbgs() << ", none.\n");
1446 return false;
1449 if (!growRegion(Cand)) {
1450 LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n");
1451 return false;
1454 SpillPlacer->finish();
1456 if (!Cand.LiveBundles.any()) {
1457 LLVM_DEBUG(dbgs() << ", none.\n");
1458 return false;
1461 LLVM_DEBUG({
1462 for (int I : Cand.LiveBundles.set_bits())
1463 dbgs() << " EB#" << I;
1464 dbgs() << ".\n";
1466 return true;
1469 /// calcSpillCost - Compute how expensive it would be to split the live range in
1470 /// SA around all use blocks instead of forming bundle regions.
1471 BlockFrequency RAGreedy::calcSpillCost() {
1472 BlockFrequency Cost = 0;
1473 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1474 for (const SplitAnalysis::BlockInfo &BI : UseBlocks) {
1475 unsigned Number = BI.MBB->getNumber();
1476 // We normally only need one spill instruction - a load or a store.
1477 Cost += SpillPlacer->getBlockFrequency(Number);
1479 // Unless the value is redefined in the block.
1480 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1481 Cost += SpillPlacer->getBlockFrequency(Number);
1483 return Cost;
1486 /// Check if splitting Evictee will create a local split interval in
1487 /// basic block number BBNumber that may cause a bad eviction chain. This is
1488 /// intended to prevent bad eviction sequences like:
1489 /// movl %ebp, 8(%esp) # 4-byte Spill
1490 /// movl %ecx, %ebp
1491 /// movl %ebx, %ecx
1492 /// movl %edi, %ebx
1493 /// movl %edx, %edi
1494 /// cltd
1495 /// idivl %esi
1496 /// movl %edi, %edx
1497 /// movl %ebx, %edi
1498 /// movl %ecx, %ebx
1499 /// movl %ebp, %ecx
1500 /// movl 16(%esp), %ebp # 4 - byte Reload
1502 /// Such sequences are created in 2 scenarios:
1504 /// Scenario #1:
1505 /// %0 is evicted from physreg0 by %1.
1506 /// Evictee %0 is intended for region splitting with split candidate
1507 /// physreg0 (the reg %0 was evicted from).
1508 /// Region splitting creates a local interval because of interference with the
1509 /// evictor %1 (normally region splitting creates 2 interval, the "by reg"
1510 /// and "by stack" intervals and local interval created when interference
1511 /// occurs).
1512 /// One of the split intervals ends up evicting %2 from physreg1.
1513 /// Evictee %2 is intended for region splitting with split candidate
1514 /// physreg1.
1515 /// One of the split intervals ends up evicting %3 from physreg2, etc.
1517 /// Scenario #2
1518 /// %0 is evicted from physreg0 by %1.
1519 /// %2 is evicted from physreg2 by %3 etc.
1520 /// Evictee %0 is intended for region splitting with split candidate
1521 /// physreg1.
1522 /// Region splitting creates a local interval because of interference with the
1523 /// evictor %1.
1524 /// One of the split intervals ends up evicting back original evictor %1
1525 /// from physreg0 (the reg %0 was evicted from).
1526 /// Another evictee %2 is intended for region splitting with split candidate
1527 /// physreg1.
1528 /// One of the split intervals ends up evicting %3 from physreg2, etc.
1530 /// \param Evictee The register considered to be split.
1531 /// \param Cand The split candidate that determines the physical register
1532 /// we are splitting for and the interferences.
1533 /// \param BBNumber The number of a BB for which the region split process will
1534 /// create a local split interval.
1535 /// \param Order The physical registers that may get evicted by a split
1536 /// artifact of Evictee.
1537 /// \return True if splitting Evictee may cause a bad eviction chain, false
1538 /// otherwise.
1539 bool RAGreedy::splitCanCauseEvictionChain(Register Evictee,
1540 GlobalSplitCandidate &Cand,
1541 unsigned BBNumber,
1542 const AllocationOrder &Order) {
1543 EvictionTrack::EvictorInfo VregEvictorInfo = LastEvicted.getEvictor(Evictee);
1544 unsigned Evictor = VregEvictorInfo.first;
1545 MCRegister PhysReg = VregEvictorInfo.second;
1547 // No actual evictor.
1548 if (!Evictor || !PhysReg)
1549 return false;
1551 float MaxWeight = 0;
1552 MCRegister FutureEvictedPhysReg =
1553 getCheapestEvicteeWeight(Order, LIS->getInterval(Evictee),
1554 Cand.Intf.first(), Cand.Intf.last(), &MaxWeight);
1556 // The bad eviction chain occurs when either the split candidate is the
1557 // evicting reg or one of the split artifact will evict the evicting reg.
1558 if ((PhysReg != Cand.PhysReg) && (PhysReg != FutureEvictedPhysReg))
1559 return false;
1561 Cand.Intf.moveToBlock(BBNumber);
1563 // Check to see if the Evictor contains interference (with Evictee) in the
1564 // given BB. If so, this interference caused the eviction of Evictee from
1565 // PhysReg. This suggest that we will create a local interval during the
1566 // region split to avoid this interference This local interval may cause a bad
1567 // eviction chain.
1568 if (!LIS->hasInterval(Evictor))
1569 return false;
1570 LiveInterval &EvictorLI = LIS->getInterval(Evictor);
1571 if (EvictorLI.FindSegmentContaining(Cand.Intf.first()) == EvictorLI.end())
1572 return false;
1574 // Now, check to see if the local interval we will create is going to be
1575 // expensive enough to evict somebody If so, this may cause a bad eviction
1576 // chain.
1577 float splitArtifactWeight =
1578 VRAI->futureWeight(LIS->getInterval(Evictee),
1579 Cand.Intf.first().getPrevIndex(), Cand.Intf.last());
1580 if (splitArtifactWeight >= 0 && splitArtifactWeight < MaxWeight)
1581 return false;
1583 return true;
1586 /// Check if splitting VirtRegToSplit will create a local split interval
1587 /// in basic block number BBNumber that may cause a spill.
1589 /// \param VirtRegToSplit The register considered to be split.
1590 /// \param Cand The split candidate that determines the physical
1591 /// register we are splitting for and the interferences.
1592 /// \param BBNumber The number of a BB for which the region split process
1593 /// will create a local split interval.
1594 /// \param Order The physical registers that may get evicted by a
1595 /// split artifact of VirtRegToSplit.
1596 /// \return True if splitting VirtRegToSplit may cause a spill, false
1597 /// otherwise.
1598 bool RAGreedy::splitCanCauseLocalSpill(unsigned VirtRegToSplit,
1599 GlobalSplitCandidate &Cand,
1600 unsigned BBNumber,
1601 const AllocationOrder &Order) {
1602 Cand.Intf.moveToBlock(BBNumber);
1604 // Check if the local interval will find a non interfereing assignment.
1605 for (auto PhysReg : Order.getOrder()) {
1606 if (!Matrix->checkInterference(Cand.Intf.first().getPrevIndex(),
1607 Cand.Intf.last(), PhysReg))
1608 return false;
1611 // The local interval is not able to find non interferencing assignment
1612 // and not able to evict a less worthy interval, therfore, it can cause a
1613 // spill.
1614 return true;
1617 /// calcGlobalSplitCost - Return the global split cost of following the split
1618 /// pattern in LiveBundles. This cost should be added to the local cost of the
1619 /// interference pattern in SplitConstraints.
1621 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand,
1622 const AllocationOrder &Order,
1623 bool *CanCauseEvictionChain) {
1624 BlockFrequency GlobalCost = 0;
1625 const BitVector &LiveBundles = Cand.LiveBundles;
1626 Register VirtRegToSplit = SA->getParent().reg();
1627 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1628 for (unsigned I = 0; I != UseBlocks.size(); ++I) {
1629 const SplitAnalysis::BlockInfo &BI = UseBlocks[I];
1630 SpillPlacement::BlockConstraint &BC = SplitConstraints[I];
1631 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, false)];
1632 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, true)];
1633 unsigned Ins = 0;
1635 Cand.Intf.moveToBlock(BC.Number);
1636 // Check wheather a local interval is going to be created during the region
1637 // split. Calculate adavanced spilt cost (cost of local intervals) if option
1638 // is enabled.
1639 if (EnableAdvancedRASplitCost && Cand.Intf.hasInterference() && BI.LiveIn &&
1640 BI.LiveOut && RegIn && RegOut) {
1642 if (CanCauseEvictionChain &&
1643 splitCanCauseEvictionChain(VirtRegToSplit, Cand, BC.Number, Order)) {
1644 // This interference causes our eviction from this assignment, we might
1645 // evict somebody else and eventually someone will spill, add that cost.
1646 // See splitCanCauseEvictionChain for detailed description of scenarios.
1647 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1648 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1650 *CanCauseEvictionChain = true;
1652 } else if (splitCanCauseLocalSpill(VirtRegToSplit, Cand, BC.Number,
1653 Order)) {
1654 // This interference causes local interval to spill, add that cost.
1655 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1656 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1660 if (BI.LiveIn)
1661 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1662 if (BI.LiveOut)
1663 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
1664 while (Ins--)
1665 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1668 for (unsigned Number : Cand.ActiveBlocks) {
1669 bool RegIn = LiveBundles[Bundles->getBundle(Number, false)];
1670 bool RegOut = LiveBundles[Bundles->getBundle(Number, true)];
1671 if (!RegIn && !RegOut)
1672 continue;
1673 if (RegIn && RegOut) {
1674 // We need double spill code if this block has interference.
1675 Cand.Intf.moveToBlock(Number);
1676 if (Cand.Intf.hasInterference()) {
1677 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1678 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1680 // Check wheather a local interval is going to be created during the
1681 // region split.
1682 if (EnableAdvancedRASplitCost && CanCauseEvictionChain &&
1683 splitCanCauseEvictionChain(VirtRegToSplit, Cand, Number, Order)) {
1684 // This interference cause our eviction from this assignment, we might
1685 // evict somebody else, add that cost.
1686 // See splitCanCauseEvictionChain for detailed description of
1687 // scenarios.
1688 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1689 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1691 *CanCauseEvictionChain = true;
1694 continue;
1696 // live-in / stack-out or stack-in live-out.
1697 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1699 return GlobalCost;
1702 /// splitAroundRegion - Split the current live range around the regions
1703 /// determined by BundleCand and GlobalCand.
1705 /// Before calling this function, GlobalCand and BundleCand must be initialized
1706 /// so each bundle is assigned to a valid candidate, or NoCand for the
1707 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1708 /// objects must be initialized for the current live range, and intervals
1709 /// created for the used candidates.
1711 /// @param LREdit The LiveRangeEdit object handling the current split.
1712 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1713 /// must appear in this list.
1714 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1715 ArrayRef<unsigned> UsedCands) {
1716 // These are the intervals created for new global ranges. We may create more
1717 // intervals for local ranges.
1718 const unsigned NumGlobalIntvs = LREdit.size();
1719 LLVM_DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs
1720 << " globals.\n");
1721 assert(NumGlobalIntvs && "No global intervals configured");
1723 // Isolate even single instructions when dealing with a proper sub-class.
1724 // That guarantees register class inflation for the stack interval because it
1725 // is all copies.
1726 Register Reg = SA->getParent().reg();
1727 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1729 // First handle all the blocks with uses.
1730 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1731 for (const SplitAnalysis::BlockInfo &BI : UseBlocks) {
1732 unsigned Number = BI.MBB->getNumber();
1733 unsigned IntvIn = 0, IntvOut = 0;
1734 SlotIndex IntfIn, IntfOut;
1735 if (BI.LiveIn) {
1736 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
1737 if (CandIn != NoCand) {
1738 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1739 IntvIn = Cand.IntvIdx;
1740 Cand.Intf.moveToBlock(Number);
1741 IntfIn = Cand.Intf.first();
1744 if (BI.LiveOut) {
1745 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
1746 if (CandOut != NoCand) {
1747 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1748 IntvOut = Cand.IntvIdx;
1749 Cand.Intf.moveToBlock(Number);
1750 IntfOut = Cand.Intf.last();
1754 // Create separate intervals for isolated blocks with multiple uses.
1755 if (!IntvIn && !IntvOut) {
1756 LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " isolated.\n");
1757 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1758 SE->splitSingleBlock(BI);
1759 continue;
1762 if (IntvIn && IntvOut)
1763 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1764 else if (IntvIn)
1765 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1766 else
1767 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1770 // Handle live-through blocks. The relevant live-through blocks are stored in
1771 // the ActiveBlocks list with each candidate. We need to filter out
1772 // duplicates.
1773 BitVector Todo = SA->getThroughBlocks();
1774 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1775 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1776 for (unsigned Number : Blocks) {
1777 if (!Todo.test(Number))
1778 continue;
1779 Todo.reset(Number);
1781 unsigned IntvIn = 0, IntvOut = 0;
1782 SlotIndex IntfIn, IntfOut;
1784 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
1785 if (CandIn != NoCand) {
1786 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1787 IntvIn = Cand.IntvIdx;
1788 Cand.Intf.moveToBlock(Number);
1789 IntfIn = Cand.Intf.first();
1792 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
1793 if (CandOut != NoCand) {
1794 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1795 IntvOut = Cand.IntvIdx;
1796 Cand.Intf.moveToBlock(Number);
1797 IntfOut = Cand.Intf.last();
1799 if (!IntvIn && !IntvOut)
1800 continue;
1801 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1805 ++NumGlobalSplits;
1807 SmallVector<unsigned, 8> IntvMap;
1808 SE->finish(&IntvMap);
1809 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
1811 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1812 unsigned OrigBlocks = SA->getNumLiveBlocks();
1814 // Sort out the new intervals created by splitting. We get four kinds:
1815 // - Remainder intervals should not be split again.
1816 // - Candidate intervals can be assigned to Cand.PhysReg.
1817 // - Block-local splits are candidates for local splitting.
1818 // - DCE leftovers should go back on the queue.
1819 for (unsigned I = 0, E = LREdit.size(); I != E; ++I) {
1820 LiveInterval &Reg = LIS->getInterval(LREdit.get(I));
1822 // Ignore old intervals from DCE.
1823 if (getStage(Reg) != RS_New)
1824 continue;
1826 // Remainder interval. Don't try splitting again, spill if it doesn't
1827 // allocate.
1828 if (IntvMap[I] == 0) {
1829 setStage(Reg, RS_Spill);
1830 continue;
1833 // Global intervals. Allow repeated splitting as long as the number of live
1834 // blocks is strictly decreasing.
1835 if (IntvMap[I] < NumGlobalIntvs) {
1836 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1837 LLVM_DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1838 << " blocks as original.\n");
1839 // Don't allow repeated splitting as a safe guard against looping.
1840 setStage(Reg, RS_Split2);
1842 continue;
1845 // Other intervals are treated as new. This includes local intervals created
1846 // for blocks with multiple uses, and anything created by DCE.
1849 if (VerifyEnabled)
1850 MF->verify(this, "After splitting live range around region");
1853 MCRegister RAGreedy::tryRegionSplit(LiveInterval &VirtReg,
1854 AllocationOrder &Order,
1855 SmallVectorImpl<Register> &NewVRegs) {
1856 if (!TRI->shouldRegionSplitForVirtReg(*MF, VirtReg))
1857 return MCRegister::NoRegister;
1858 unsigned NumCands = 0;
1859 BlockFrequency SpillCost = calcSpillCost();
1860 BlockFrequency BestCost;
1862 // Check if we can split this live range around a compact region.
1863 bool HasCompact = calcCompactRegion(GlobalCand.front());
1864 if (HasCompact) {
1865 // Yes, keep GlobalCand[0] as the compact region candidate.
1866 NumCands = 1;
1867 BestCost = BlockFrequency::getMaxFrequency();
1868 } else {
1869 // No benefit from the compact region, our fallback will be per-block
1870 // splitting. Make sure we find a solution that is cheaper than spilling.
1871 BestCost = SpillCost;
1872 LLVM_DEBUG(dbgs() << "Cost of isolating all blocks = ";
1873 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
1876 bool CanCauseEvictionChain = false;
1877 unsigned BestCand =
1878 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1879 false /*IgnoreCSR*/, &CanCauseEvictionChain);
1881 // Split candidates with compact regions can cause a bad eviction sequence.
1882 // See splitCanCauseEvictionChain for detailed description of scenarios.
1883 // To avoid it, we need to comapre the cost with the spill cost and not the
1884 // current max frequency.
1885 if (HasCompact && (BestCost > SpillCost) && (BestCand != NoCand) &&
1886 CanCauseEvictionChain) {
1887 return MCRegister::NoRegister;
1890 // No solutions found, fall back to single block splitting.
1891 if (!HasCompact && BestCand == NoCand)
1892 return MCRegister::NoRegister;
1894 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1897 unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1898 AllocationOrder &Order,
1899 BlockFrequency &BestCost,
1900 unsigned &NumCands, bool IgnoreCSR,
1901 bool *CanCauseEvictionChain) {
1902 unsigned BestCand = NoCand;
1903 for (MCPhysReg PhysReg : Order) {
1904 assert(PhysReg);
1905 if (IgnoreCSR && isUnusedCalleeSavedReg(PhysReg))
1906 continue;
1908 // Discard bad candidates before we run out of interference cache cursors.
1909 // This will only affect register classes with a lot of registers (>32).
1910 if (NumCands == IntfCache.getMaxCursors()) {
1911 unsigned WorstCount = ~0u;
1912 unsigned Worst = 0;
1913 for (unsigned CandIndex = 0; CandIndex != NumCands; ++CandIndex) {
1914 if (CandIndex == BestCand || !GlobalCand[CandIndex].PhysReg)
1915 continue;
1916 unsigned Count = GlobalCand[CandIndex].LiveBundles.count();
1917 if (Count < WorstCount) {
1918 Worst = CandIndex;
1919 WorstCount = Count;
1922 --NumCands;
1923 GlobalCand[Worst] = GlobalCand[NumCands];
1924 if (BestCand == NumCands)
1925 BestCand = Worst;
1928 if (GlobalCand.size() <= NumCands)
1929 GlobalCand.resize(NumCands+1);
1930 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1931 Cand.reset(IntfCache, PhysReg);
1933 SpillPlacer->prepare(Cand.LiveBundles);
1934 BlockFrequency Cost;
1935 if (!addSplitConstraints(Cand.Intf, Cost)) {
1936 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tno positive bundles\n");
1937 continue;
1939 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tstatic = ";
1940 MBFI->printBlockFreq(dbgs(), Cost));
1941 if (Cost >= BestCost) {
1942 LLVM_DEBUG({
1943 if (BestCand == NoCand)
1944 dbgs() << " worse than no bundles\n";
1945 else
1946 dbgs() << " worse than "
1947 << printReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1949 continue;
1951 if (!growRegion(Cand)) {
1952 LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n");
1953 continue;
1956 SpillPlacer->finish();
1958 // No live bundles, defer to splitSingleBlocks().
1959 if (!Cand.LiveBundles.any()) {
1960 LLVM_DEBUG(dbgs() << " no bundles.\n");
1961 continue;
1964 bool HasEvictionChain = false;
1965 Cost += calcGlobalSplitCost(Cand, Order, &HasEvictionChain);
1966 LLVM_DEBUG({
1967 dbgs() << ", total = ";
1968 MBFI->printBlockFreq(dbgs(), Cost) << " with bundles";
1969 for (int I : Cand.LiveBundles.set_bits())
1970 dbgs() << " EB#" << I;
1971 dbgs() << ".\n";
1973 if (Cost < BestCost) {
1974 BestCand = NumCands;
1975 BestCost = Cost;
1976 // See splitCanCauseEvictionChain for detailed description of bad
1977 // eviction chain scenarios.
1978 if (CanCauseEvictionChain)
1979 *CanCauseEvictionChain = HasEvictionChain;
1981 ++NumCands;
1984 if (CanCauseEvictionChain && BestCand != NoCand) {
1985 // See splitCanCauseEvictionChain for detailed description of bad
1986 // eviction chain scenarios.
1987 LLVM_DEBUG(dbgs() << "Best split candidate of vreg "
1988 << printReg(VirtReg.reg(), TRI) << " may ");
1989 if (!(*CanCauseEvictionChain))
1990 LLVM_DEBUG(dbgs() << "not ");
1991 LLVM_DEBUG(dbgs() << "cause bad eviction chain\n");
1994 return BestCand;
1997 unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1998 bool HasCompact,
1999 SmallVectorImpl<Register> &NewVRegs) {
2000 SmallVector<unsigned, 8> UsedCands;
2001 // Prepare split editor.
2002 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
2003 SE->reset(LREdit, SplitSpillMode);
2005 // Assign all edge bundles to the preferred candidate, or NoCand.
2006 BundleCand.assign(Bundles->getNumBundles(), NoCand);
2008 // Assign bundles for the best candidate region.
2009 if (BestCand != NoCand) {
2010 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
2011 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
2012 UsedCands.push_back(BestCand);
2013 Cand.IntvIdx = SE->openIntv();
2014 LLVM_DEBUG(dbgs() << "Split for " << printReg(Cand.PhysReg, TRI) << " in "
2015 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
2016 (void)B;
2020 // Assign bundles for the compact region.
2021 if (HasCompact) {
2022 GlobalSplitCandidate &Cand = GlobalCand.front();
2023 assert(!Cand.PhysReg && "Compact region has no physreg");
2024 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
2025 UsedCands.push_back(0);
2026 Cand.IntvIdx = SE->openIntv();
2027 LLVM_DEBUG(dbgs() << "Split for compact region in " << B
2028 << " bundles, intv " << Cand.IntvIdx << ".\n");
2029 (void)B;
2033 splitAroundRegion(LREdit, UsedCands);
2034 return 0;
2037 //===----------------------------------------------------------------------===//
2038 // Per-Block Splitting
2039 //===----------------------------------------------------------------------===//
2041 /// tryBlockSplit - Split a global live range around every block with uses. This
2042 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
2043 /// they don't allocate.
2044 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
2045 SmallVectorImpl<Register> &NewVRegs) {
2046 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
2047 Register Reg = VirtReg.reg();
2048 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
2049 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
2050 SE->reset(LREdit, SplitSpillMode);
2051 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
2052 for (const SplitAnalysis::BlockInfo &BI : UseBlocks) {
2053 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
2054 SE->splitSingleBlock(BI);
2056 // No blocks were split.
2057 if (LREdit.empty())
2058 return 0;
2060 // We did split for some blocks.
2061 SmallVector<unsigned, 8> IntvMap;
2062 SE->finish(&IntvMap);
2064 // Tell LiveDebugVariables about the new ranges.
2065 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
2067 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2069 // Sort out the new intervals created by splitting. The remainder interval
2070 // goes straight to spilling, the new local ranges get to stay RS_New.
2071 for (unsigned I = 0, E = LREdit.size(); I != E; ++I) {
2072 LiveInterval &LI = LIS->getInterval(LREdit.get(I));
2073 if (getStage(LI) == RS_New && IntvMap[I] == 0)
2074 setStage(LI, RS_Spill);
2077 if (VerifyEnabled)
2078 MF->verify(this, "After splitting live range around basic blocks");
2079 return 0;
2082 //===----------------------------------------------------------------------===//
2083 // Per-Instruction Splitting
2084 //===----------------------------------------------------------------------===//
2086 /// Get the number of allocatable registers that match the constraints of \p Reg
2087 /// on \p MI and that are also in \p SuperRC.
2088 static unsigned getNumAllocatableRegsForConstraints(
2089 const MachineInstr *MI, Register Reg, const TargetRegisterClass *SuperRC,
2090 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
2091 const RegisterClassInfo &RCI) {
2092 assert(SuperRC && "Invalid register class");
2094 const TargetRegisterClass *ConstrainedRC =
2095 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
2096 /* ExploreBundle */ true);
2097 if (!ConstrainedRC)
2098 return 0;
2099 return RCI.getNumAllocatableRegs(ConstrainedRC);
2102 /// tryInstructionSplit - Split a live range around individual instructions.
2103 /// This is normally not worthwhile since the spiller is doing essentially the
2104 /// same thing. However, when the live range is in a constrained register
2105 /// class, it may help to insert copies such that parts of the live range can
2106 /// be moved to a larger register class.
2108 /// This is similar to spilling to a larger register class.
2109 unsigned
2110 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
2111 SmallVectorImpl<Register> &NewVRegs) {
2112 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg());
2113 // There is no point to this if there are no larger sub-classes.
2114 if (!RegClassInfo.isProperSubClass(CurRC))
2115 return 0;
2117 // Always enable split spill mode, since we're effectively spilling to a
2118 // register.
2119 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
2120 SE->reset(LREdit, SplitEditor::SM_Size);
2122 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
2123 if (Uses.size() <= 1)
2124 return 0;
2126 LLVM_DEBUG(dbgs() << "Split around " << Uses.size()
2127 << " individual instrs.\n");
2129 const TargetRegisterClass *SuperRC =
2130 TRI->getLargestLegalSuperClass(CurRC, *MF);
2131 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
2132 // Split around every non-copy instruction if this split will relax
2133 // the constraints on the virtual register.
2134 // Otherwise, splitting just inserts uncoalescable copies that do not help
2135 // the allocation.
2136 for (const auto &Use : Uses) {
2137 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Use))
2138 if (MI->isFullCopy() ||
2139 SuperRCNumAllocatableRegs ==
2140 getNumAllocatableRegsForConstraints(MI, VirtReg.reg(), SuperRC,
2141 TII, TRI, RCI)) {
2142 LLVM_DEBUG(dbgs() << " skip:\t" << Use << '\t' << *MI);
2143 continue;
2145 SE->openIntv();
2146 SlotIndex SegStart = SE->enterIntvBefore(Use);
2147 SlotIndex SegStop = SE->leaveIntvAfter(Use);
2148 SE->useIntv(SegStart, SegStop);
2151 if (LREdit.empty()) {
2152 LLVM_DEBUG(dbgs() << "All uses were copies.\n");
2153 return 0;
2156 SmallVector<unsigned, 8> IntvMap;
2157 SE->finish(&IntvMap);
2158 DebugVars->splitRegister(VirtReg.reg(), LREdit.regs(), *LIS);
2159 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2161 // Assign all new registers to RS_Spill. This was the last chance.
2162 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
2163 return 0;
2166 //===----------------------------------------------------------------------===//
2167 // Local Splitting
2168 //===----------------------------------------------------------------------===//
2170 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
2171 /// in order to use PhysReg between two entries in SA->UseSlots.
2173 /// GapWeight[I] represents the gap between UseSlots[I] and UseSlots[I + 1].
2175 void RAGreedy::calcGapWeights(MCRegister PhysReg,
2176 SmallVectorImpl<float> &GapWeight) {
2177 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
2178 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
2179 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
2180 const unsigned NumGaps = Uses.size()-1;
2182 // Start and end points for the interference check.
2183 SlotIndex StartIdx =
2184 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
2185 SlotIndex StopIdx =
2186 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
2188 GapWeight.assign(NumGaps, 0.0f);
2190 // Add interference from each overlapping register.
2191 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2192 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
2193 .checkInterference())
2194 continue;
2196 // We know that VirtReg is a continuous interval from FirstInstr to
2197 // LastInstr, so we don't need InterferenceQuery.
2199 // Interference that overlaps an instruction is counted in both gaps
2200 // surrounding the instruction. The exception is interference before
2201 // StartIdx and after StopIdx.
2203 LiveIntervalUnion::SegmentIter IntI =
2204 Matrix->getLiveUnions()[*Units] .find(StartIdx);
2205 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
2206 // Skip the gaps before IntI.
2207 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
2208 if (++Gap == NumGaps)
2209 break;
2210 if (Gap == NumGaps)
2211 break;
2213 // Update the gaps covered by IntI.
2214 const float weight = IntI.value()->weight();
2215 for (; Gap != NumGaps; ++Gap) {
2216 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
2217 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
2218 break;
2220 if (Gap == NumGaps)
2221 break;
2225 // Add fixed interference.
2226 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2227 const LiveRange &LR = LIS->getRegUnit(*Units);
2228 LiveRange::const_iterator I = LR.find(StartIdx);
2229 LiveRange::const_iterator E = LR.end();
2231 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
2232 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
2233 while (Uses[Gap+1].getBoundaryIndex() < I->start)
2234 if (++Gap == NumGaps)
2235 break;
2236 if (Gap == NumGaps)
2237 break;
2239 for (; Gap != NumGaps; ++Gap) {
2240 GapWeight[Gap] = huge_valf;
2241 if (Uses[Gap+1].getBaseIndex() >= I->end)
2242 break;
2244 if (Gap == NumGaps)
2245 break;
2250 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
2251 /// basic block.
2253 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
2254 SmallVectorImpl<Register> &NewVRegs) {
2255 // TODO: the function currently only handles a single UseBlock; it should be
2256 // possible to generalize.
2257 if (SA->getUseBlocks().size() != 1)
2258 return 0;
2260 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
2262 // Note that it is possible to have an interval that is live-in or live-out
2263 // while only covering a single block - A phi-def can use undef values from
2264 // predecessors, and the block could be a single-block loop.
2265 // We don't bother doing anything clever about such a case, we simply assume
2266 // that the interval is continuous from FirstInstr to LastInstr. We should
2267 // make sure that we don't do anything illegal to such an interval, though.
2269 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
2270 if (Uses.size() <= 2)
2271 return 0;
2272 const unsigned NumGaps = Uses.size()-1;
2274 LLVM_DEBUG({
2275 dbgs() << "tryLocalSplit: ";
2276 for (const auto &Use : Uses)
2277 dbgs() << ' ' << Use;
2278 dbgs() << '\n';
2281 // If VirtReg is live across any register mask operands, compute a list of
2282 // gaps with register masks.
2283 SmallVector<unsigned, 8> RegMaskGaps;
2284 if (Matrix->checkRegMaskInterference(VirtReg)) {
2285 // Get regmask slots for the whole block.
2286 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
2287 LLVM_DEBUG(dbgs() << RMS.size() << " regmasks in block:");
2288 // Constrain to VirtReg's live range.
2289 unsigned RI =
2290 llvm::lower_bound(RMS, Uses.front().getRegSlot()) - RMS.begin();
2291 unsigned RE = RMS.size();
2292 for (unsigned I = 0; I != NumGaps && RI != RE; ++I) {
2293 // Look for Uses[I] <= RMS <= Uses[I + 1].
2294 assert(!SlotIndex::isEarlierInstr(RMS[RI], Uses[I]));
2295 if (SlotIndex::isEarlierInstr(Uses[I + 1], RMS[RI]))
2296 continue;
2297 // Skip a regmask on the same instruction as the last use. It doesn't
2298 // overlap the live range.
2299 if (SlotIndex::isSameInstr(Uses[I + 1], RMS[RI]) && I + 1 == NumGaps)
2300 break;
2301 LLVM_DEBUG(dbgs() << ' ' << RMS[RI] << ':' << Uses[I] << '-'
2302 << Uses[I + 1]);
2303 RegMaskGaps.push_back(I);
2304 // Advance ri to the next gap. A regmask on one of the uses counts in
2305 // both gaps.
2306 while (RI != RE && SlotIndex::isEarlierInstr(RMS[RI], Uses[I + 1]))
2307 ++RI;
2309 LLVM_DEBUG(dbgs() << '\n');
2312 // Since we allow local split results to be split again, there is a risk of
2313 // creating infinite loops. It is tempting to require that the new live
2314 // ranges have less instructions than the original. That would guarantee
2315 // convergence, but it is too strict. A live range with 3 instructions can be
2316 // split 2+3 (including the COPY), and we want to allow that.
2318 // Instead we use these rules:
2320 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
2321 // noop split, of course).
2322 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
2323 // the new ranges must have fewer instructions than before the split.
2324 // 3. New ranges with the same number of instructions are marked RS_Split2,
2325 // smaller ranges are marked RS_New.
2327 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
2328 // excessive splitting and infinite loops.
2330 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
2332 // Best split candidate.
2333 unsigned BestBefore = NumGaps;
2334 unsigned BestAfter = 0;
2335 float BestDiff = 0;
2337 const float blockFreq =
2338 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
2339 (1.0f / MBFI->getEntryFreq());
2340 SmallVector<float, 8> GapWeight;
2342 for (MCPhysReg PhysReg : Order) {
2343 assert(PhysReg);
2344 // Keep track of the largest spill weight that would need to be evicted in
2345 // order to make use of PhysReg between UseSlots[I] and UseSlots[I + 1].
2346 calcGapWeights(PhysReg, GapWeight);
2348 // Remove any gaps with regmask clobbers.
2349 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
2350 for (unsigned I = 0, E = RegMaskGaps.size(); I != E; ++I)
2351 GapWeight[RegMaskGaps[I]] = huge_valf;
2353 // Try to find the best sequence of gaps to close.
2354 // The new spill weight must be larger than any gap interference.
2356 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
2357 unsigned SplitBefore = 0, SplitAfter = 1;
2359 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
2360 // It is the spill weight that needs to be evicted.
2361 float MaxGap = GapWeight[0];
2363 while (true) {
2364 // Live before/after split?
2365 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
2366 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
2368 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << ' ' << Uses[SplitBefore]
2369 << '-' << Uses[SplitAfter] << " I=" << MaxGap);
2371 // Stop before the interval gets so big we wouldn't be making progress.
2372 if (!LiveBefore && !LiveAfter) {
2373 LLVM_DEBUG(dbgs() << " all\n");
2374 break;
2376 // Should the interval be extended or shrunk?
2377 bool Shrink = true;
2379 // How many gaps would the new range have?
2380 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
2382 // Legally, without causing looping?
2383 bool Legal = !ProgressRequired || NewGaps < NumGaps;
2385 if (Legal && MaxGap < huge_valf) {
2386 // Estimate the new spill weight. Each instruction reads or writes the
2387 // register. Conservatively assume there are no read-modify-write
2388 // instructions.
2390 // Try to guess the size of the new interval.
2391 const float EstWeight = normalizeSpillWeight(
2392 blockFreq * (NewGaps + 1),
2393 Uses[SplitBefore].distance(Uses[SplitAfter]) +
2394 (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
2396 // Would this split be possible to allocate?
2397 // Never allocate all gaps, we wouldn't be making progress.
2398 LLVM_DEBUG(dbgs() << " w=" << EstWeight);
2399 if (EstWeight * Hysteresis >= MaxGap) {
2400 Shrink = false;
2401 float Diff = EstWeight - MaxGap;
2402 if (Diff > BestDiff) {
2403 LLVM_DEBUG(dbgs() << " (best)");
2404 BestDiff = Hysteresis * Diff;
2405 BestBefore = SplitBefore;
2406 BestAfter = SplitAfter;
2411 // Try to shrink.
2412 if (Shrink) {
2413 if (++SplitBefore < SplitAfter) {
2414 LLVM_DEBUG(dbgs() << " shrink\n");
2415 // Recompute the max when necessary.
2416 if (GapWeight[SplitBefore - 1] >= MaxGap) {
2417 MaxGap = GapWeight[SplitBefore];
2418 for (unsigned I = SplitBefore + 1; I != SplitAfter; ++I)
2419 MaxGap = std::max(MaxGap, GapWeight[I]);
2421 continue;
2423 MaxGap = 0;
2426 // Try to extend the interval.
2427 if (SplitAfter >= NumGaps) {
2428 LLVM_DEBUG(dbgs() << " end\n");
2429 break;
2432 LLVM_DEBUG(dbgs() << " extend\n");
2433 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
2437 // Didn't find any candidates?
2438 if (BestBefore == NumGaps)
2439 return 0;
2441 LLVM_DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore] << '-'
2442 << Uses[BestAfter] << ", " << BestDiff << ", "
2443 << (BestAfter - BestBefore + 1) << " instrs\n");
2445 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
2446 SE->reset(LREdit);
2448 SE->openIntv();
2449 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
2450 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
2451 SE->useIntv(SegStart, SegStop);
2452 SmallVector<unsigned, 8> IntvMap;
2453 SE->finish(&IntvMap);
2454 DebugVars->splitRegister(VirtReg.reg(), LREdit.regs(), *LIS);
2456 // If the new range has the same number of instructions as before, mark it as
2457 // RS_Split2 so the next split will be forced to make progress. Otherwise,
2458 // leave the new intervals as RS_New so they can compete.
2459 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
2460 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
2461 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
2462 if (NewGaps >= NumGaps) {
2463 LLVM_DEBUG(dbgs() << "Tagging non-progress ranges:");
2464 assert(!ProgressRequired && "Didn't make progress when it was required.");
2465 for (unsigned I = 0, E = IntvMap.size(); I != E; ++I)
2466 if (IntvMap[I] == 1) {
2467 setStage(LIS->getInterval(LREdit.get(I)), RS_Split2);
2468 LLVM_DEBUG(dbgs() << ' ' << printReg(LREdit.get(I)));
2470 LLVM_DEBUG(dbgs() << '\n');
2472 ++NumLocalSplits;
2474 return 0;
2477 //===----------------------------------------------------------------------===//
2478 // Live Range Splitting
2479 //===----------------------------------------------------------------------===//
2481 /// trySplit - Try to split VirtReg or one of its interferences, making it
2482 /// assignable.
2483 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
2484 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
2485 SmallVectorImpl<Register> &NewVRegs,
2486 const SmallVirtRegSet &FixedRegisters) {
2487 // Ranges must be Split2 or less.
2488 if (getStage(VirtReg) >= RS_Spill)
2489 return 0;
2491 // Local intervals are handled separately.
2492 if (LIS->intervalIsInOneMBB(VirtReg)) {
2493 NamedRegionTimer T("local_split", "Local Splitting", TimerGroupName,
2494 TimerGroupDescription, TimePassesIsEnabled);
2495 SA->analyze(&VirtReg);
2496 Register PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
2497 if (PhysReg || !NewVRegs.empty())
2498 return PhysReg;
2499 return tryInstructionSplit(VirtReg, Order, NewVRegs);
2502 NamedRegionTimer T("global_split", "Global Splitting", TimerGroupName,
2503 TimerGroupDescription, TimePassesIsEnabled);
2505 SA->analyze(&VirtReg);
2507 // FIXME: SplitAnalysis may repair broken live ranges coming from the
2508 // coalescer. That may cause the range to become allocatable which means that
2509 // tryRegionSplit won't be making progress. This check should be replaced with
2510 // an assertion when the coalescer is fixed.
2511 if (SA->didRepairRange()) {
2512 // VirtReg has changed, so all cached queries are invalid.
2513 Matrix->invalidateVirtRegs();
2514 if (Register PhysReg = tryAssign(VirtReg, Order, NewVRegs, FixedRegisters))
2515 return PhysReg;
2518 // First try to split around a region spanning multiple blocks. RS_Split2
2519 // ranges already made dubious progress with region splitting, so they go
2520 // straight to single block splitting.
2521 if (getStage(VirtReg) < RS_Split2) {
2522 MCRegister PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
2523 if (PhysReg || !NewVRegs.empty())
2524 return PhysReg;
2527 // Then isolate blocks.
2528 return tryBlockSplit(VirtReg, Order, NewVRegs);
2531 //===----------------------------------------------------------------------===//
2532 // Last Chance Recoloring
2533 //===----------------------------------------------------------------------===//
2535 /// Return true if \p reg has any tied def operand.
2536 static bool hasTiedDef(MachineRegisterInfo *MRI, unsigned reg) {
2537 for (const MachineOperand &MO : MRI->def_operands(reg))
2538 if (MO.isTied())
2539 return true;
2541 return false;
2544 /// mayRecolorAllInterferences - Check if the virtual registers that
2545 /// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
2546 /// recolored to free \p PhysReg.
2547 /// When true is returned, \p RecoloringCandidates has been augmented with all
2548 /// the live intervals that need to be recolored in order to free \p PhysReg
2549 /// for \p VirtReg.
2550 /// \p FixedRegisters contains all the virtual registers that cannot be
2551 /// recolored.
2552 bool RAGreedy::mayRecolorAllInterferences(
2553 MCRegister PhysReg, LiveInterval &VirtReg, SmallLISet &RecoloringCandidates,
2554 const SmallVirtRegSet &FixedRegisters) {
2555 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg());
2557 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2558 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
2559 // If there is LastChanceRecoloringMaxInterference or more interferences,
2560 // chances are one would not be recolorable.
2561 if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
2562 LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
2563 LLVM_DEBUG(dbgs() << "Early abort: too many interferences.\n");
2564 CutOffInfo |= CO_Interf;
2565 return false;
2567 for (LiveInterval *Intf : reverse(Q.interferingVRegs())) {
2568 // If Intf is done and sit on the same register class as VirtReg,
2569 // it would not be recolorable as it is in the same state as VirtReg.
2570 // However, if VirtReg has tied defs and Intf doesn't, then
2571 // there is still a point in examining if it can be recolorable.
2572 if (((getStage(*Intf) == RS_Done &&
2573 MRI->getRegClass(Intf->reg()) == CurRC) &&
2574 !(hasTiedDef(MRI, VirtReg.reg()) &&
2575 !hasTiedDef(MRI, Intf->reg()))) ||
2576 FixedRegisters.count(Intf->reg())) {
2577 LLVM_DEBUG(
2578 dbgs() << "Early abort: the interference is not recolorable.\n");
2579 return false;
2581 RecoloringCandidates.insert(Intf);
2584 return true;
2587 /// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
2588 /// its interferences.
2589 /// Last chance recoloring chooses a color for \p VirtReg and recolors every
2590 /// virtual register that was using it. The recoloring process may recursively
2591 /// use the last chance recoloring. Therefore, when a virtual register has been
2592 /// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
2593 /// be last-chance-recolored again during this recoloring "session".
2594 /// E.g.,
2595 /// Let
2596 /// vA can use {R1, R2 }
2597 /// vB can use { R2, R3}
2598 /// vC can use {R1 }
2599 /// Where vA, vB, and vC cannot be split anymore (they are reloads for
2600 /// instance) and they all interfere.
2602 /// vA is assigned R1
2603 /// vB is assigned R2
2604 /// vC tries to evict vA but vA is already done.
2605 /// Regular register allocation fails.
2607 /// Last chance recoloring kicks in:
2608 /// vC does as if vA was evicted => vC uses R1.
2609 /// vC is marked as fixed.
2610 /// vA needs to find a color.
2611 /// None are available.
2612 /// vA cannot evict vC: vC is a fixed virtual register now.
2613 /// vA does as if vB was evicted => vA uses R2.
2614 /// vB needs to find a color.
2615 /// R3 is available.
2616 /// Recoloring => vC = R1, vA = R2, vB = R3
2618 /// \p Order defines the preferred allocation order for \p VirtReg.
2619 /// \p NewRegs will contain any new virtual register that have been created
2620 /// (split, spill) during the process and that must be assigned.
2621 /// \p FixedRegisters contains all the virtual registers that cannot be
2622 /// recolored.
2623 /// \p Depth gives the current depth of the last chance recoloring.
2624 /// \return a physical register that can be used for VirtReg or ~0u if none
2625 /// exists.
2626 unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
2627 AllocationOrder &Order,
2628 SmallVectorImpl<Register> &NewVRegs,
2629 SmallVirtRegSet &FixedRegisters,
2630 unsigned Depth) {
2631 if (!TRI->shouldUseLastChanceRecoloringForVirtReg(*MF, VirtReg))
2632 return ~0u;
2634 LLVM_DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
2635 // Ranges must be Done.
2636 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
2637 "Last chance recoloring should really be last chance");
2638 // Set the max depth to LastChanceRecoloringMaxDepth.
2639 // We may want to reconsider that if we end up with a too large search space
2640 // for target with hundreds of registers.
2641 // Indeed, in that case we may want to cut the search space earlier.
2642 if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
2643 LLVM_DEBUG(dbgs() << "Abort because max depth has been reached.\n");
2644 CutOffInfo |= CO_Depth;
2645 return ~0u;
2648 // Set of Live intervals that will need to be recolored.
2649 SmallLISet RecoloringCandidates;
2650 // Record the original mapping virtual register to physical register in case
2651 // the recoloring fails.
2652 DenseMap<Register, MCRegister> VirtRegToPhysReg;
2653 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
2654 // this recoloring "session".
2655 assert(!FixedRegisters.count(VirtReg.reg()));
2656 FixedRegisters.insert(VirtReg.reg());
2657 SmallVector<Register, 4> CurrentNewVRegs;
2659 for (MCRegister PhysReg : Order) {
2660 assert(PhysReg.isValid());
2661 LLVM_DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
2662 << printReg(PhysReg, TRI) << '\n');
2663 RecoloringCandidates.clear();
2664 VirtRegToPhysReg.clear();
2665 CurrentNewVRegs.clear();
2667 // It is only possible to recolor virtual register interference.
2668 if (Matrix->checkInterference(VirtReg, PhysReg) >
2669 LiveRegMatrix::IK_VirtReg) {
2670 LLVM_DEBUG(
2671 dbgs() << "Some interferences are not with virtual registers.\n");
2673 continue;
2676 // Early give up on this PhysReg if it is obvious we cannot recolor all
2677 // the interferences.
2678 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2679 FixedRegisters)) {
2680 LLVM_DEBUG(dbgs() << "Some interferences cannot be recolored.\n");
2681 continue;
2684 // RecoloringCandidates contains all the virtual registers that interfer
2685 // with VirtReg on PhysReg (or one of its aliases).
2686 // Enqueue them for recoloring and perform the actual recoloring.
2687 PQueue RecoloringQueue;
2688 for (LiveInterval *RC : RecoloringCandidates) {
2689 Register ItVirtReg = RC->reg();
2690 enqueue(RecoloringQueue, RC);
2691 assert(VRM->hasPhys(ItVirtReg) &&
2692 "Interferences are supposed to be with allocated variables");
2694 // Record the current allocation.
2695 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2696 // unset the related struct.
2697 Matrix->unassign(*RC);
2700 // Do as if VirtReg was assigned to PhysReg so that the underlying
2701 // recoloring has the right information about the interferes and
2702 // available colors.
2703 Matrix->assign(VirtReg, PhysReg);
2705 // Save the current recoloring state.
2706 // If we cannot recolor all the interferences, we will have to start again
2707 // at this point for the next physical register.
2708 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
2709 if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs,
2710 FixedRegisters, Depth)) {
2711 // Push the queued vregs into the main queue.
2712 for (Register NewVReg : CurrentNewVRegs)
2713 NewVRegs.push_back(NewVReg);
2714 // Do not mess up with the global assignment process.
2715 // I.e., VirtReg must be unassigned.
2716 Matrix->unassign(VirtReg);
2717 return PhysReg;
2720 LLVM_DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2721 << printReg(PhysReg, TRI) << '\n');
2723 // The recoloring attempt failed, undo the changes.
2724 FixedRegisters = SaveFixedRegisters;
2725 Matrix->unassign(VirtReg);
2727 // For a newly created vreg which is also in RecoloringCandidates,
2728 // don't add it to NewVRegs because its physical register will be restored
2729 // below. Other vregs in CurrentNewVRegs are created by calling
2730 // selectOrSplit and should be added into NewVRegs.
2731 for (Register &R : CurrentNewVRegs) {
2732 if (RecoloringCandidates.count(&LIS->getInterval(R)))
2733 continue;
2734 NewVRegs.push_back(R);
2737 for (LiveInterval *RC : RecoloringCandidates) {
2738 Register ItVirtReg = RC->reg();
2739 if (VRM->hasPhys(ItVirtReg))
2740 Matrix->unassign(*RC);
2741 MCRegister ItPhysReg = VirtRegToPhysReg[ItVirtReg];
2742 Matrix->assign(*RC, ItPhysReg);
2746 // Last chance recoloring did not worked either, give up.
2747 return ~0u;
2750 /// tryRecoloringCandidates - Try to assign a new color to every register
2751 /// in \RecoloringQueue.
2752 /// \p NewRegs will contain any new virtual register created during the
2753 /// recoloring process.
2754 /// \p FixedRegisters[in/out] contains all the registers that have been
2755 /// recolored.
2756 /// \return true if all virtual registers in RecoloringQueue were successfully
2757 /// recolored, false otherwise.
2758 bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2759 SmallVectorImpl<Register> &NewVRegs,
2760 SmallVirtRegSet &FixedRegisters,
2761 unsigned Depth) {
2762 while (!RecoloringQueue.empty()) {
2763 LiveInterval *LI = dequeue(RecoloringQueue);
2764 LLVM_DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2765 MCRegister PhysReg =
2766 selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
2767 // When splitting happens, the live-range may actually be empty.
2768 // In that case, this is okay to continue the recoloring even
2769 // if we did not find an alternative color for it. Indeed,
2770 // there will not be anything to color for LI in the end.
2771 if (PhysReg == ~0u || (!PhysReg && !LI->empty()))
2772 return false;
2774 if (!PhysReg) {
2775 assert(LI->empty() && "Only empty live-range do not require a register");
2776 LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
2777 << " succeeded. Empty LI.\n");
2778 continue;
2780 LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
2781 << " succeeded with: " << printReg(PhysReg, TRI) << '\n');
2783 Matrix->assign(*LI, PhysReg);
2784 FixedRegisters.insert(LI->reg());
2786 return true;
2789 //===----------------------------------------------------------------------===//
2790 // Main Entry Point
2791 //===----------------------------------------------------------------------===//
2793 MCRegister RAGreedy::selectOrSplit(LiveInterval &VirtReg,
2794 SmallVectorImpl<Register> &NewVRegs) {
2795 CutOffInfo = CO_None;
2796 LLVMContext &Ctx = MF->getFunction().getContext();
2797 SmallVirtRegSet FixedRegisters;
2798 MCRegister Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2799 if (Reg == ~0U && (CutOffInfo != CO_None)) {
2800 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2801 if (CutOffEncountered == CO_Depth)
2802 Ctx.emitError("register allocation failed: maximum depth for recoloring "
2803 "reached. Use -fexhaustive-register-search to skip "
2804 "cutoffs");
2805 else if (CutOffEncountered == CO_Interf)
2806 Ctx.emitError("register allocation failed: maximum interference for "
2807 "recoloring reached. Use -fexhaustive-register-search "
2808 "to skip cutoffs");
2809 else if (CutOffEncountered == (CO_Depth | CO_Interf))
2810 Ctx.emitError("register allocation failed: maximum interference and "
2811 "depth for recoloring reached. Use "
2812 "-fexhaustive-register-search to skip cutoffs");
2814 return Reg;
2817 /// Using a CSR for the first time has a cost because it causes push|pop
2818 /// to be added to prologue|epilogue. Splitting a cold section of the live
2819 /// range can have lower cost than using the CSR for the first time;
2820 /// Spilling a live range in the cold path can have lower cost than using
2821 /// the CSR for the first time. Returns the physical register if we decide
2822 /// to use the CSR; otherwise return 0.
2823 MCRegister
2824 RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
2825 MCRegister PhysReg, uint8_t &CostPerUseLimit,
2826 SmallVectorImpl<Register> &NewVRegs) {
2827 if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2828 // We choose spill over using the CSR for the first time if the spill cost
2829 // is lower than CSRCost.
2830 SA->analyze(&VirtReg);
2831 if (calcSpillCost() >= CSRCost)
2832 return PhysReg;
2834 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2835 // we will not use a callee-saved register in tryEvict.
2836 CostPerUseLimit = 1;
2837 return 0;
2839 if (getStage(VirtReg) < RS_Split) {
2840 // We choose pre-splitting over using the CSR for the first time if
2841 // the cost of splitting is lower than CSRCost.
2842 SA->analyze(&VirtReg);
2843 unsigned NumCands = 0;
2844 BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2845 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2846 NumCands, true /*IgnoreCSR*/);
2847 if (BestCand == NoCand)
2848 // Use the CSR if we can't find a region split below CSRCost.
2849 return PhysReg;
2851 // Perform the actual pre-splitting.
2852 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2853 return 0;
2855 return PhysReg;
2858 void RAGreedy::aboutToRemoveInterval(LiveInterval &LI) {
2859 // Do not keep invalid information around.
2860 SetOfBrokenHints.remove(&LI);
2863 void RAGreedy::initializeCSRCost() {
2864 // We use the larger one out of the command-line option and the value report
2865 // by TRI.
2866 CSRCost = BlockFrequency(
2867 std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2868 if (!CSRCost.getFrequency())
2869 return;
2871 // Raw cost is relative to Entry == 2^14; scale it appropriately.
2872 uint64_t ActualEntry = MBFI->getEntryFreq();
2873 if (!ActualEntry) {
2874 CSRCost = 0;
2875 return;
2877 uint64_t FixedEntry = 1 << 14;
2878 if (ActualEntry < FixedEntry)
2879 CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2880 else if (ActualEntry <= UINT32_MAX)
2881 // Invert the fraction and divide.
2882 CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2883 else
2884 // Can't use BranchProbability in general, since it takes 32-bit numbers.
2885 CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2888 /// Collect the hint info for \p Reg.
2889 /// The results are stored into \p Out.
2890 /// \p Out is not cleared before being populated.
2891 void RAGreedy::collectHintInfo(Register Reg, HintsInfo &Out) {
2892 for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) {
2893 if (!Instr.isFullCopy())
2894 continue;
2895 // Look for the other end of the copy.
2896 Register OtherReg = Instr.getOperand(0).getReg();
2897 if (OtherReg == Reg) {
2898 OtherReg = Instr.getOperand(1).getReg();
2899 if (OtherReg == Reg)
2900 continue;
2902 // Get the current assignment.
2903 MCRegister OtherPhysReg =
2904 OtherReg.isPhysical() ? OtherReg.asMCReg() : VRM->getPhys(OtherReg);
2905 // Push the collected information.
2906 Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
2907 OtherPhysReg));
2911 /// Using the given \p List, compute the cost of the broken hints if
2912 /// \p PhysReg was used.
2913 /// \return The cost of \p List for \p PhysReg.
2914 BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
2915 MCRegister PhysReg) {
2916 BlockFrequency Cost = 0;
2917 for (const HintInfo &Info : List) {
2918 if (Info.PhysReg != PhysReg)
2919 Cost += Info.Freq;
2921 return Cost;
2924 /// Using the register assigned to \p VirtReg, try to recolor
2925 /// all the live ranges that are copy-related with \p VirtReg.
2926 /// The recoloring is then propagated to all the live-ranges that have
2927 /// been recolored and so on, until no more copies can be coalesced or
2928 /// it is not profitable.
2929 /// For a given live range, profitability is determined by the sum of the
2930 /// frequencies of the non-identity copies it would introduce with the old
2931 /// and new register.
2932 void RAGreedy::tryHintRecoloring(LiveInterval &VirtReg) {
2933 // We have a broken hint, check if it is possible to fix it by
2934 // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
2935 // some register and PhysReg may be available for the other live-ranges.
2936 SmallSet<Register, 4> Visited;
2937 SmallVector<unsigned, 2> RecoloringCandidates;
2938 HintsInfo Info;
2939 Register Reg = VirtReg.reg();
2940 MCRegister PhysReg = VRM->getPhys(Reg);
2941 // Start the recoloring algorithm from the input live-interval, then
2942 // it will propagate to the ones that are copy-related with it.
2943 Visited.insert(Reg);
2944 RecoloringCandidates.push_back(Reg);
2946 LLVM_DEBUG(dbgs() << "Trying to reconcile hints for: " << printReg(Reg, TRI)
2947 << '(' << printReg(PhysReg, TRI) << ")\n");
2949 do {
2950 Reg = RecoloringCandidates.pop_back_val();
2952 // We cannot recolor physical register.
2953 if (Register::isPhysicalRegister(Reg))
2954 continue;
2956 // This may be a skipped class
2957 if (!VRM->hasPhys(Reg)) {
2958 assert(!ShouldAllocateClass(*TRI, *MRI->getRegClass(Reg)) &&
2959 "We have an unallocated variable which should have been handled");
2960 continue;
2963 // Get the live interval mapped with this virtual register to be able
2964 // to check for the interference with the new color.
2965 LiveInterval &LI = LIS->getInterval(Reg);
2966 MCRegister CurrPhys = VRM->getPhys(Reg);
2967 // Check that the new color matches the register class constraints and
2968 // that it is free for this live range.
2969 if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) ||
2970 Matrix->checkInterference(LI, PhysReg)))
2971 continue;
2973 LLVM_DEBUG(dbgs() << printReg(Reg, TRI) << '(' << printReg(CurrPhys, TRI)
2974 << ") is recolorable.\n");
2976 // Gather the hint info.
2977 Info.clear();
2978 collectHintInfo(Reg, Info);
2979 // Check if recoloring the live-range will increase the cost of the
2980 // non-identity copies.
2981 if (CurrPhys != PhysReg) {
2982 LLVM_DEBUG(dbgs() << "Checking profitability:\n");
2983 BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
2984 BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg);
2985 LLVM_DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency()
2986 << "\nNew Cost: " << NewCopiesCost.getFrequency()
2987 << '\n');
2988 if (OldCopiesCost < NewCopiesCost) {
2989 LLVM_DEBUG(dbgs() << "=> Not profitable.\n");
2990 continue;
2992 // At this point, the cost is either cheaper or equal. If it is
2993 // equal, we consider this is profitable because it may expose
2994 // more recoloring opportunities.
2995 LLVM_DEBUG(dbgs() << "=> Profitable.\n");
2996 // Recolor the live-range.
2997 Matrix->unassign(LI);
2998 Matrix->assign(LI, PhysReg);
3000 // Push all copy-related live-ranges to keep reconciling the broken
3001 // hints.
3002 for (const HintInfo &HI : Info) {
3003 if (Visited.insert(HI.Reg).second)
3004 RecoloringCandidates.push_back(HI.Reg);
3006 } while (!RecoloringCandidates.empty());
3009 /// Try to recolor broken hints.
3010 /// Broken hints may be repaired by recoloring when an evicted variable
3011 /// freed up a register for a larger live-range.
3012 /// Consider the following example:
3013 /// BB1:
3014 /// a =
3015 /// b =
3016 /// BB2:
3017 /// ...
3018 /// = b
3019 /// = a
3020 /// Let us assume b gets split:
3021 /// BB1:
3022 /// a =
3023 /// b =
3024 /// BB2:
3025 /// c = b
3026 /// ...
3027 /// d = c
3028 /// = d
3029 /// = a
3030 /// Because of how the allocation work, b, c, and d may be assigned different
3031 /// colors. Now, if a gets evicted later:
3032 /// BB1:
3033 /// a =
3034 /// st a, SpillSlot
3035 /// b =
3036 /// BB2:
3037 /// c = b
3038 /// ...
3039 /// d = c
3040 /// = d
3041 /// e = ld SpillSlot
3042 /// = e
3043 /// This is likely that we can assign the same register for b, c, and d,
3044 /// getting rid of 2 copies.
3045 void RAGreedy::tryHintsRecoloring() {
3046 for (LiveInterval *LI : SetOfBrokenHints) {
3047 assert(Register::isVirtualRegister(LI->reg()) &&
3048 "Recoloring is possible only for virtual registers");
3049 // Some dead defs may be around (e.g., because of debug uses).
3050 // Ignore those.
3051 if (!VRM->hasPhys(LI->reg()))
3052 continue;
3053 tryHintRecoloring(*LI);
3057 MCRegister RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
3058 SmallVectorImpl<Register> &NewVRegs,
3059 SmallVirtRegSet &FixedRegisters,
3060 unsigned Depth) {
3061 uint8_t CostPerUseLimit = uint8_t(~0u);
3062 // First try assigning a free register.
3063 auto Order =
3064 AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
3065 if (MCRegister PhysReg =
3066 tryAssign(VirtReg, Order, NewVRegs, FixedRegisters)) {
3067 // If VirtReg got an assignment, the eviction info is no longer relevant.
3068 LastEvicted.clearEvicteeInfo(VirtReg.reg());
3069 // When NewVRegs is not empty, we may have made decisions such as evicting
3070 // a virtual register, go with the earlier decisions and use the physical
3071 // register.
3072 if (CSRCost.getFrequency() && isUnusedCalleeSavedReg(PhysReg) &&
3073 NewVRegs.empty()) {
3074 MCRegister CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
3075 CostPerUseLimit, NewVRegs);
3076 if (CSRReg || !NewVRegs.empty())
3077 // Return now if we decide to use a CSR or create new vregs due to
3078 // pre-splitting.
3079 return CSRReg;
3080 } else
3081 return PhysReg;
3084 LiveRangeStage Stage = getStage(VirtReg);
3085 LLVM_DEBUG(dbgs() << StageName[Stage] << " Cascade "
3086 << ExtraRegInfo[VirtReg.reg()].Cascade << '\n');
3088 // Try to evict a less worthy live range, but only for ranges from the primary
3089 // queue. The RS_Split ranges already failed to do this, and they should not
3090 // get a second chance until they have been split.
3091 if (Stage != RS_Split)
3092 if (Register PhysReg =
3093 tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit,
3094 FixedRegisters)) {
3095 Register Hint = MRI->getSimpleHint(VirtReg.reg());
3096 // If VirtReg has a hint and that hint is broken record this
3097 // virtual register as a recoloring candidate for broken hint.
3098 // Indeed, since we evicted a variable in its neighborhood it is
3099 // likely we can at least partially recolor some of the
3100 // copy-related live-ranges.
3101 if (Hint && Hint != PhysReg)
3102 SetOfBrokenHints.insert(&VirtReg);
3103 // If VirtReg eviction someone, the eviction info for it as an evictee is
3104 // no longer relevant.
3105 LastEvicted.clearEvicteeInfo(VirtReg.reg());
3106 return PhysReg;
3109 assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs");
3111 // The first time we see a live range, don't try to split or spill.
3112 // Wait until the second time, when all smaller ranges have been allocated.
3113 // This gives a better picture of the interference to split around.
3114 if (Stage < RS_Split) {
3115 setStage(VirtReg, RS_Split);
3116 LLVM_DEBUG(dbgs() << "wait for second round\n");
3117 NewVRegs.push_back(VirtReg.reg());
3118 return 0;
3121 if (Stage < RS_Spill) {
3122 // Try splitting VirtReg or interferences.
3123 unsigned NewVRegSizeBefore = NewVRegs.size();
3124 Register PhysReg = trySplit(VirtReg, Order, NewVRegs, FixedRegisters);
3125 if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore)) {
3126 // If VirtReg got split, the eviction info is no longer relevant.
3127 LastEvicted.clearEvicteeInfo(VirtReg.reg());
3128 return PhysReg;
3132 // If we couldn't allocate a register from spilling, there is probably some
3133 // invalid inline assembly. The base class will report it.
3134 if (Stage >= RS_Done || !VirtReg.isSpillable())
3135 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
3136 Depth);
3138 // Finally spill VirtReg itself.
3139 if ((EnableDeferredSpilling ||
3140 TRI->shouldUseDeferredSpillingForVirtReg(*MF, VirtReg)) &&
3141 getStage(VirtReg) < RS_Memory) {
3142 // TODO: This is experimental and in particular, we do not model
3143 // the live range splitting done by spilling correctly.
3144 // We would need a deep integration with the spiller to do the
3145 // right thing here. Anyway, that is still good for early testing.
3146 setStage(VirtReg, RS_Memory);
3147 LLVM_DEBUG(dbgs() << "Do as if this register is in memory\n");
3148 NewVRegs.push_back(VirtReg.reg());
3149 } else {
3150 NamedRegionTimer T("spill", "Spiller", TimerGroupName,
3151 TimerGroupDescription, TimePassesIsEnabled);
3152 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
3153 spiller().spill(LRE);
3154 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
3156 // Tell LiveDebugVariables about the new ranges. Ranges not being covered by
3157 // the new regs are kept in LDV (still mapping to the old register), until
3158 // we rewrite spilled locations in LDV at a later stage.
3159 DebugVars->splitRegister(VirtReg.reg(), LRE.regs(), *LIS);
3161 if (VerifyEnabled)
3162 MF->verify(this, "After spilling");
3165 // The live virtual register requesting allocation was spilled, so tell
3166 // the caller not to allocate anything during this round.
3167 return 0;
3170 void RAGreedy::RAGreedyStats::report(MachineOptimizationRemarkMissed &R) {
3171 using namespace ore;
3172 if (Spills) {
3173 R << NV("NumSpills", Spills) << " spills ";
3174 R << NV("TotalSpillsCost", SpillsCost) << " total spills cost ";
3176 if (FoldedSpills) {
3177 R << NV("NumFoldedSpills", FoldedSpills) << " folded spills ";
3178 R << NV("TotalFoldedSpillsCost", FoldedSpillsCost)
3179 << " total folded spills cost ";
3181 if (Reloads) {
3182 R << NV("NumReloads", Reloads) << " reloads ";
3183 R << NV("TotalReloadsCost", ReloadsCost) << " total reloads cost ";
3185 if (FoldedReloads) {
3186 R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads ";
3187 R << NV("TotalFoldedReloadsCost", FoldedReloadsCost)
3188 << " total folded reloads cost ";
3190 if (ZeroCostFoldedReloads)
3191 R << NV("NumZeroCostFoldedReloads", ZeroCostFoldedReloads)
3192 << " zero cost folded reloads ";
3193 if (Copies) {
3194 R << NV("NumVRCopies", Copies) << " virtual registers copies ";
3195 R << NV("TotalCopiesCost", CopiesCost) << " total copies cost ";
3199 RAGreedy::RAGreedyStats RAGreedy::computeStats(MachineBasicBlock &MBB) {
3200 RAGreedyStats Stats;
3201 const MachineFrameInfo &MFI = MF->getFrameInfo();
3202 int FI;
3204 auto isSpillSlotAccess = [&MFI](const MachineMemOperand *A) {
3205 return MFI.isSpillSlotObjectIndex(cast<FixedStackPseudoSourceValue>(
3206 A->getPseudoValue())->getFrameIndex());
3208 auto isPatchpointInstr = [](const MachineInstr &MI) {
3209 return MI.getOpcode() == TargetOpcode::PATCHPOINT ||
3210 MI.getOpcode() == TargetOpcode::STACKMAP ||
3211 MI.getOpcode() == TargetOpcode::STATEPOINT;
3213 for (MachineInstr &MI : MBB) {
3214 if (MI.isCopy()) {
3215 MachineOperand &Dest = MI.getOperand(0);
3216 MachineOperand &Src = MI.getOperand(1);
3217 if (Dest.isReg() && Src.isReg() && Dest.getReg().isVirtual() &&
3218 Src.getReg().isVirtual())
3219 ++Stats.Copies;
3220 continue;
3223 SmallVector<const MachineMemOperand *, 2> Accesses;
3224 if (TII->isLoadFromStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI)) {
3225 ++Stats.Reloads;
3226 continue;
3228 if (TII->isStoreToStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI)) {
3229 ++Stats.Spills;
3230 continue;
3232 if (TII->hasLoadFromStackSlot(MI, Accesses) &&
3233 llvm::any_of(Accesses, isSpillSlotAccess)) {
3234 if (!isPatchpointInstr(MI)) {
3235 Stats.FoldedReloads += Accesses.size();
3236 continue;
3238 // For statepoint there may be folded and zero cost folded stack reloads.
3239 std::pair<unsigned, unsigned> NonZeroCostRange =
3240 TII->getPatchpointUnfoldableRange(MI);
3241 SmallSet<unsigned, 16> FoldedReloads;
3242 SmallSet<unsigned, 16> ZeroCostFoldedReloads;
3243 for (unsigned Idx = 0, E = MI.getNumOperands(); Idx < E; ++Idx) {
3244 MachineOperand &MO = MI.getOperand(Idx);
3245 if (!MO.isFI() || !MFI.isSpillSlotObjectIndex(MO.getIndex()))
3246 continue;
3247 if (Idx >= NonZeroCostRange.first && Idx < NonZeroCostRange.second)
3248 FoldedReloads.insert(MO.getIndex());
3249 else
3250 ZeroCostFoldedReloads.insert(MO.getIndex());
3252 // If stack slot is used in folded reload it is not zero cost then.
3253 for (unsigned Slot : FoldedReloads)
3254 ZeroCostFoldedReloads.erase(Slot);
3255 Stats.FoldedReloads += FoldedReloads.size();
3256 Stats.ZeroCostFoldedReloads += ZeroCostFoldedReloads.size();
3257 continue;
3259 Accesses.clear();
3260 if (TII->hasStoreToStackSlot(MI, Accesses) &&
3261 llvm::any_of(Accesses, isSpillSlotAccess)) {
3262 Stats.FoldedSpills += Accesses.size();
3265 // Set cost of collected statistic by multiplication to relative frequency of
3266 // this basic block.
3267 float RelFreq = MBFI->getBlockFreqRelativeToEntryBlock(&MBB);
3268 Stats.ReloadsCost = RelFreq * Stats.Reloads;
3269 Stats.FoldedReloadsCost = RelFreq * Stats.FoldedReloads;
3270 Stats.SpillsCost = RelFreq * Stats.Spills;
3271 Stats.FoldedSpillsCost = RelFreq * Stats.FoldedSpills;
3272 Stats.CopiesCost = RelFreq * Stats.Copies;
3273 return Stats;
3276 RAGreedy::RAGreedyStats RAGreedy::reportStats(MachineLoop *L) {
3277 RAGreedyStats Stats;
3279 // Sum up the spill and reloads in subloops.
3280 for (MachineLoop *SubLoop : *L)
3281 Stats.add(reportStats(SubLoop));
3283 for (MachineBasicBlock *MBB : L->getBlocks())
3284 // Handle blocks that were not included in subloops.
3285 if (Loops->getLoopFor(MBB) == L)
3286 Stats.add(computeStats(*MBB));
3288 if (!Stats.isEmpty()) {
3289 using namespace ore;
3291 ORE->emit([&]() {
3292 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReloadCopies",
3293 L->getStartLoc(), L->getHeader());
3294 Stats.report(R);
3295 R << "generated in loop";
3296 return R;
3299 return Stats;
3302 void RAGreedy::reportStats() {
3303 if (!ORE->allowExtraAnalysis(DEBUG_TYPE))
3304 return;
3305 RAGreedyStats Stats;
3306 for (MachineLoop *L : *Loops)
3307 Stats.add(reportStats(L));
3308 // Process non-loop blocks.
3309 for (MachineBasicBlock &MBB : *MF)
3310 if (!Loops->getLoopFor(&MBB))
3311 Stats.add(computeStats(MBB));
3312 if (!Stats.isEmpty()) {
3313 using namespace ore;
3315 ORE->emit([&]() {
3316 DebugLoc Loc;
3317 if (auto *SP = MF->getFunction().getSubprogram())
3318 Loc = DILocation::get(SP->getContext(), SP->getLine(), 1, SP);
3319 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "SpillReloadCopies", Loc,
3320 &MF->front());
3321 Stats.report(R);
3322 R << "generated in function";
3323 return R;
3328 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
3329 LLVM_DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
3330 << "********** Function: " << mf.getName() << '\n');
3332 MF = &mf;
3333 TRI = MF->getSubtarget().getRegisterInfo();
3334 TII = MF->getSubtarget().getInstrInfo();
3335 RCI.runOnMachineFunction(mf);
3337 EnableLocalReassign = EnableLocalReassignment ||
3338 MF->getSubtarget().enableRALocalReassignment(
3339 MF->getTarget().getOptLevel());
3341 EnableAdvancedRASplitCost =
3342 ConsiderLocalIntervalCost.getNumOccurrences()
3343 ? ConsiderLocalIntervalCost
3344 : MF->getSubtarget().enableAdvancedRASplitCost();
3346 if (VerifyEnabled)
3347 MF->verify(this, "Before greedy register allocator");
3349 RegAllocBase::init(getAnalysis<VirtRegMap>(),
3350 getAnalysis<LiveIntervals>(),
3351 getAnalysis<LiveRegMatrix>());
3352 Indexes = &getAnalysis<SlotIndexes>();
3353 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
3354 DomTree = &getAnalysis<MachineDominatorTree>();
3355 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
3356 Loops = &getAnalysis<MachineLoopInfo>();
3357 Bundles = &getAnalysis<EdgeBundles>();
3358 SpillPlacer = &getAnalysis<SpillPlacement>();
3359 DebugVars = &getAnalysis<LiveDebugVariables>();
3360 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3362 initializeCSRCost();
3364 RegCosts = TRI->getRegisterCosts(*MF);
3366 VRAI = std::make_unique<VirtRegAuxInfo>(*MF, *LIS, *VRM, *Loops, *MBFI);
3367 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM, *VRAI));
3369 VRAI->calculateSpillWeightsAndHints();
3371 LLVM_DEBUG(LIS->dump());
3373 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
3374 SE.reset(new SplitEditor(*SA, *AA, *LIS, *VRM, *DomTree, *MBFI, *VRAI));
3375 ExtraRegInfo.clear();
3376 ExtraRegInfo.resize(MRI->getNumVirtRegs());
3377 NextCascade = 1;
3378 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
3379 GlobalCand.resize(32); // This will grow as needed.
3380 SetOfBrokenHints.clear();
3381 LastEvicted.clear();
3383 allocatePhysRegs();
3384 tryHintsRecoloring();
3386 if (VerifyEnabled)
3387 MF->verify(this, "Before post optimization");
3388 postOptimization();
3389 reportStats();
3391 releaseMemory();
3392 return true;