LLVM 24.0.0git
RegBankSelect.cpp
Go to the documentation of this file.
1//==- llvm/CodeGen/GlobalISel/RegBankSelect.cpp - RegBankSelect --*- C++ -*-==//
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/// \file
9/// This file implements the RegBankSelect class.
10//===----------------------------------------------------------------------===//
11
14#include "llvm/ADT/STLExtras.h"
35#include "llvm/Config/llvm-config.h"
36#include "llvm/IR/Analysis.h"
37#include "llvm/IR/Function.h"
39#include "llvm/Pass.h"
43#include "llvm/Support/Debug.h"
47#include <algorithm>
48#include <cassert>
49#include <cstdint>
50#include <limits>
51#include <memory>
52#include <optional>
53#include <utility>
54
55#define DEBUG_TYPE "reg-bank-select"
56
57using namespace llvm;
58
59/// Cost value representing an impossible or invalid repairing.
60/// This matches the value returned by RegisterBankInfo::copyCost() and
61/// RegisterBankInfo::getBreakDownCost() when the cost cannot be computed.
62static constexpr unsigned ImpossibleRepairCost =
63 std::numeric_limits<unsigned>::max();
64
66 cl::desc("Mode of the RegBankSelect pass"), cl::Hidden, cl::Optional,
67 cl::values(clEnumValN(RegBankSelectMode::Fast, "regbankselect-fast",
68 "Run the Fast mode (default mapping)"),
69 clEnumValN(RegBankSelectMode::Greedy, "regbankselect-greedy",
70 "Use the Greedy mode (best local mapping)")));
71
73
75 "Assign register bank of generic virtual registers",
76 false, false);
81 "Assign register bank of generic virtual registers", false,
82 false)
83
84static RegBankSelectMode computeOptMode(RegBankSelectMode RequestedMode) {
85 if (RegBankSelectModeOption.getNumOccurrences() != 0) {
86 if (RegBankSelectModeOption != RequestedMode)
87 LLVM_DEBUG(dbgs() << "RegBankSelect mode overrided by command line\n");
88 return RegBankSelectModeOption;
89 }
90 return RequestedMode;
91}
92
93namespace {
94
95class RegBankSelectImpl {
96 /// Abstract class used to represent an insertion point in a CFG.
97 /// This class records an insertion point and materializes it on
98 /// demand.
99 /// It allows to reason about the frequency of this insertion point,
100 /// without having to logically materialize it (e.g., on an edge),
101 /// before we actually need to insert something.
102 class InsertPoint {
103 protected:
104 /// Tell if the insert point has already been materialized.
105 bool WasMaterialized = false;
106
107 /// Materialize the insertion point.
108 ///
109 /// If isSplit() is true, this involves actually splitting
110 /// the block or edge.
111 ///
112 /// \post getPointImpl() returns a valid iterator.
113 /// \post getInsertMBBImpl() returns a valid basic block.
114 /// \post isSplit() == false ; no more splitting should be required.
115 virtual void materialize() = 0;
116
117 /// Return the materialized insertion basic block.
118 /// Code will be inserted into that basic block.
119 ///
120 /// \pre ::materialize has been called.
121 virtual MachineBasicBlock &getInsertMBBImpl() = 0;
122
123 /// Return the materialized insertion point.
124 /// Code will be inserted before that point.
125 ///
126 /// \pre ::materialize has been called.
127 virtual MachineBasicBlock::iterator getPointImpl() = 0;
128
129 public:
130 virtual ~InsertPoint() = default;
131
132 /// The first call to this method will cause the splitting to
133 /// happen if need be, then sub sequent calls just return
134 /// the iterator to that point. I.e., no more splitting will
135 /// occur.
136 ///
137 /// \return The iterator that should be used with
138 /// MachineBasicBlock::insert. I.e., additional code happens
139 /// before that point.
140 MachineBasicBlock::iterator getPoint() {
141 if (!WasMaterialized) {
142 WasMaterialized = true;
143 assert(canMaterialize() && "Impossible to materialize this point");
144 materialize();
145 }
146 // When we materialized the point we should have done the splitting.
147 assert(!isSplit() && "Wrong pre-condition");
148 return getPointImpl();
149 }
150
151 /// The first call to this method will cause the splitting to
152 /// happen if need be, then sub sequent calls just return
153 /// the basic block that contains the insertion point.
154 /// I.e., no more splitting will occur.
155 ///
156 /// \return The basic block should be used with
157 /// MachineBasicBlock::insert and ::getPoint. The new code should
158 /// happen before that point.
159 MachineBasicBlock &getInsertMBB() {
160 if (!WasMaterialized) {
161 WasMaterialized = true;
162 assert(canMaterialize() && "Impossible to materialize this point");
163 materialize();
164 }
165 // When we materialized the point we should have done the splitting.
166 assert(!isSplit() && "Wrong pre-condition");
167 return getInsertMBBImpl();
168 }
169
170 /// Insert \p MI in the just before ::getPoint()
171 MachineBasicBlock::iterator insert(MachineInstr &MI) {
172 return getInsertMBB().insert(getPoint(), &MI);
173 }
174
175 /// Does this point involve splitting an edge or block?
176 /// As soon as ::getPoint is called and thus, the point
177 /// materialized, the point will not require splitting anymore,
178 /// i.e., this will return false.
179 virtual bool isSplit() const { return false; }
180
181 /// Frequency of the insertion point.
182 /// \p P is used to access the various analysis that will help to
183 /// get that information, like MachineBlockFrequencyInfo. If \p P
184 /// does not contain enough to return the actual frequency,
185 /// this returns 1.
186 virtual uint64_t frequency(
187 function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
188 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI) const {
189 return 1;
190 }
191
192 /// Check whether this insertion point can be materialized.
193 /// As soon as ::getPoint is called and thus, the point materialized
194 /// calling this method does not make sense.
195 virtual bool canMaterialize() const { return false; }
196 };
197
198 /// Insertion point before or after an instruction.
199 class LLVM_ABI InstrInsertPoint : public InsertPoint {
200 private:
201 /// Insertion point.
202 MachineInstr &Instr;
203
204 /// Does the insertion point is before or after Instr.
205 bool Before;
206
207 void materialize() override;
208
209 MachineBasicBlock::iterator getPointImpl() override {
210 if (Before)
211 return Instr;
212 return Instr.getNextNode() ? *Instr.getNextNode()
213 : Instr.getParent()->end();
214 }
215
216 MachineBasicBlock &getInsertMBBImpl() override {
217 return *Instr.getParent();
218 }
219
220 public:
221 /// Create an insertion point before (\p Before=true) or after \p Instr.
222 InstrInsertPoint(MachineInstr &Instr, bool Before = true);
223
224 bool isSplit() const override;
226 frequency(function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
227 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI)
228 const override;
229
230 // Worst case, we need to slice the basic block, but that is still doable.
231 bool canMaterialize() const override { return true; }
232 };
233
234 /// Insertion point at the beginning or end of a basic block.
235 class LLVM_ABI MBBInsertPoint : public InsertPoint {
236 private:
237 /// Insertion point.
238 MachineBasicBlock &MBB;
239
240 /// Does the insertion point is at the beginning or end of MBB.
241 bool Beginning;
242
243 void materialize() override { /*Nothing to do to materialize*/ }
244
245 MachineBasicBlock::iterator getPointImpl() override {
246 return Beginning ? MBB.begin() : MBB.end();
247 }
248
249 MachineBasicBlock &getInsertMBBImpl() override { return MBB; }
250
251 public:
252 MBBInsertPoint(MachineBasicBlock &MBB, bool Beginning = true)
253 : MBB(MBB), Beginning(Beginning) {
254 // If we try to insert before phis, we should use the insertion
255 // points on the incoming edges.
256 assert((!Beginning || MBB.getFirstNonPHI() == MBB.begin()) &&
257 "Invalid beginning point");
258 // If we try to insert after the terminators, we should use the
259 // points on the outcoming edges.
260 assert((Beginning || MBB.getFirstTerminator() == MBB.end()) &&
261 "Invalid end point");
262 }
263
264 bool isSplit() const override { return false; }
266 frequency(function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
267 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI)
268 const override;
269 bool canMaterialize() const override { return true; };
270 };
271
272 /// Insertion point on an edge.
273 class LLVM_ABI EdgeInsertPoint : public InsertPoint {
274 private:
275 /// Source of the edge.
276 MachineBasicBlock &Src;
277
278 /// Destination of the edge.
279 /// After the materialization is done, this hold the basic block
280 /// that resulted from the splitting.
281 MachineBasicBlock *DstOrSplit;
282
283 /// P/MFAM is used to update the analysis passes as applicable when
284 /// splitting critical edges.
285 Pass *P;
287
288 void materialize() override;
289
290 MachineBasicBlock::iterator getPointImpl() override {
291 // DstOrSplit should be the Split block at this point.
292 // I.e., it should have one predecessor, Src, and one successor,
293 // the original Dst.
294 assert(DstOrSplit && DstOrSplit->isPredecessor(&Src) &&
295 DstOrSplit->pred_size() == 1 && DstOrSplit->succ_size() == 1 &&
296 "Did not split?!");
297 return DstOrSplit->begin();
298 }
299
300 MachineBasicBlock &getInsertMBBImpl() override { return *DstOrSplit; }
301
302 public:
303 EdgeInsertPoint(MachineBasicBlock &Src, MachineBasicBlock &Dst, Pass *P,
305 : Src(Src), DstOrSplit(&Dst), P(P), MFAM(MFAM) {}
306
307 bool isSplit() const override {
308 return Src.succ_size() > 1 && DstOrSplit->pred_size() > 1;
309 }
310
312 frequency(function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
313 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI)
314 const override;
315 bool canMaterialize() const override;
316 };
317
318 /// Struct used to represent the placement of a repairing point for
319 /// a given operand.
320 class RepairingPlacement {
321 public:
322 /// Define the kind of action this repairing needs.
323 enum RepairingKind {
324 /// Nothing to repair, just drop this action.
325 None,
326 /// Reparing code needs to happen before InsertPoints.
327 Insert,
328 /// (Re)assign the register bank of the operand.
329 Reassign,
330 /// Mark this repairing placement as impossible.
331 Impossible
332 };
333
334 /// \name Convenient types for a list of insertion points.
335 /// @{
336 using InsertionPoints = SmallVector<std::unique_ptr<InsertPoint>, 2>;
337 using insertpt_iterator = InsertionPoints::iterator;
338 using const_insertpt_iterator = InsertionPoints::const_iterator;
339 /// @}
340
341 private:
342 /// Kind of repairing.
343 RepairingKind Kind;
344 /// Index of the operand that will be repaired.
345 unsigned OpIdx;
346 /// Are all the insert points materializeable?
347 bool CanMaterialize;
348 /// Is there any of the insert points needing splitting?
349 bool HasSplit = false;
350 /// Insertion point for the repair code.
351 /// The repairing code needs to happen just before these points.
352 InsertionPoints InsertPoints;
353 /// Some insertion points may need to update the liveness and such.
354 Pass *P;
356
357 public:
358 /// Create a repairing placement for the \p OpIdx-th operand of
359 /// \p MI. \p TRI is used to make some checks on the register aliases
360 /// if the machine operand is a physical register. \p P is used to
361 /// to update liveness information and such when materializing the
362 /// points.
363 LLVM_ABI RepairingPlacement(MachineInstr &MI, unsigned OpIdx,
364 const TargetRegisterInfo &TRI, Pass *P,
366 RepairingKind Kind = RepairingKind::Insert);
367
368 /// \name Getters.
369 /// @{
370 RepairingKind getKind() const { return Kind; }
371 unsigned getOpIdx() const { return OpIdx; }
372 bool canMaterialize() const { return CanMaterialize; }
373 bool hasSplit() { return HasSplit; }
374 /// @}
375
376 /// \name Overloaded methods to add an insertion point.
377 /// @{
378 /// Add a MBBInsertionPoint to the list of InsertPoints.
379 LLVM_ABI void addInsertPoint(MachineBasicBlock &MBB, bool Beginning);
380 /// Add a InstrInsertionPoint to the list of InsertPoints.
381 LLVM_ABI void addInsertPoint(MachineInstr &MI, bool Before);
382 /// Add an EdgeInsertionPoint (\p Src, \p Dst) to the list of InsertPoints.
383 LLVM_ABI void addInsertPoint(MachineBasicBlock &Src,
384 MachineBasicBlock &Dst);
385 /// Add an InsertPoint to the list of insert points.
386 /// This method takes the ownership of &\p Point.
387 LLVM_ABI void addInsertPoint(InsertPoint &Point);
388 /// @}
389
390 /// \name Accessors related to the insertion points.
391 /// @{
392 insertpt_iterator begin() { return InsertPoints.begin(); }
393 insertpt_iterator end() { return InsertPoints.end(); }
394
395 const_insertpt_iterator begin() const { return InsertPoints.begin(); }
396 const_insertpt_iterator end() const { return InsertPoints.end(); }
397
398 unsigned getNumInsertPoints() const { return InsertPoints.size(); }
399 /// @}
400
401 /// Change the type of this repairing placement to \p NewKind.
402 /// It is not possible to switch a repairing placement to the
403 /// RepairingKind::Insert. There is no fundamental problem with
404 /// that, but no uses as well, so do not support it for now.
405 ///
406 /// \pre NewKind != RepairingKind::Insert
407 /// \post getKind() == NewKind
408 void switchTo(RepairingKind NewKind) {
409 assert(NewKind != Kind && "Already of the right Kind");
410 Kind = NewKind;
411 InsertPoints.clear();
412 CanMaterialize = NewKind != RepairingKind::Impossible;
413 HasSplit = false;
414 assert(NewKind != RepairingKind::Insert &&
415 "We would need more MI to switch to Insert");
416 }
417 };
418
419protected:
420 /// Helper class used to represent the cost for mapping an instruction.
421 /// When mapping an instruction, we may introduce some repairing code.
422 /// In most cases, the repairing code is local to the instruction,
423 /// thus, we can omit the basic block frequency from the cost.
424 /// However, some alternatives may produce non-local cost, e.g., when
425 /// repairing a phi, and thus we then need to scale the local cost
426 /// to the non-local cost. This class does this for us.
427 /// \note: We could simply always scale the cost. The problem is that
428 /// there are higher chances that we saturate the cost easier and end
429 /// up having the same cost for actually different alternatives.
430 /// Another option would be to use APInt everywhere.
431 class MappingCost {
432 private:
433 /// Cost of the local instructions.
434 /// This cost is free of basic block frequency.
435 uint64_t LocalCost = 0;
436 /// Cost of the non-local instructions.
437 /// This cost should include the frequency of the related blocks.
438 uint64_t NonLocalCost = 0;
439 /// Frequency of the block where the local instructions live.
440 uint64_t LocalFreq;
441
442 MappingCost(uint64_t LocalCost, uint64_t NonLocalCost, uint64_t LocalFreq)
443 : LocalCost(LocalCost), NonLocalCost(NonLocalCost),
444 LocalFreq(LocalFreq) {}
445
446 /// Check if this cost is saturated.
447 bool isSaturated() const;
448
449 public:
450 /// Create a MappingCost assuming that most of the instructions
451 /// will occur in a basic block with \p LocalFreq frequency.
452 LLVM_ABI MappingCost(BlockFrequency LocalFreq);
453
454 /// Add \p Cost to the local cost.
455 /// \return true if this cost is saturated, false otherwise.
456 LLVM_ABI bool addLocalCost(uint64_t Cost);
457
458 /// Add \p Cost to the non-local cost.
459 /// Non-local cost should reflect the frequency of their placement.
460 /// \return true if this cost is saturated, false otherwise.
461 LLVM_ABI bool addNonLocalCost(uint64_t Cost);
462
463 /// Saturate the cost to the maximal representable value.
464 LLVM_ABI void saturate();
465
466 /// Return an instance of MappingCost that represents an
467 /// impossible mapping.
468 LLVM_ABI static MappingCost ImpossibleCost();
469
470 /// Check if this is less than \p Cost.
471 LLVM_ABI bool operator<(const MappingCost &Cost) const;
472 /// Check if this is equal to \p Cost.
473 LLVM_ABI bool operator==(const MappingCost &Cost) const;
474 /// Check if this is not equal to \p Cost.
475 bool operator!=(const MappingCost &Cost) const { return !(*this == Cost); }
476 /// Check if this is greater than \p Cost.
477 bool operator>(const MappingCost &Cost) const {
478 return *this != Cost && Cost < *this;
479 }
480
481 /// Print this on dbgs() stream.
482 LLVM_ABI void dump() const;
483
484 /// Print this on \p OS;
485 LLVM_ABI void print(raw_ostream &OS) const;
486
487 /// Overload the stream operator for easy debug printing.
488 [[maybe_unused]] friend raw_ostream &operator<<(raw_ostream &OS,
489 const MappingCost &Cost) {
490 Cost.print(OS);
491 return OS;
492 }
493 };
494
495 /// Interface to the target lowering info related
496 /// to register banks.
497 const RegisterBankInfo *RBI = nullptr;
498
499 /// MRI contains all the register class/bank information that this
500 /// pass uses and updates.
501 MachineRegisterInfo *MRI = nullptr;
502
503 /// Information on the register classes for the current function.
504 const TargetRegisterInfo *TRI = nullptr;
505
506 /// Get the frequency of blocks.
507 /// This is required for non-fast mode.
508 MachineBlockFrequencyInfo *MBFI = nullptr;
509
510 /// Get the frequency of the edges.
511 /// This is required for non-fast mode.
512 MachineBranchProbabilityInfo *MBPI = nullptr;
513
514 /// Current optimization remark emitter. Used to report failures.
515 std::unique_ptr<MachineOptimizationRemarkEmitter> MORE;
516
517 /// Helper class used for every code morphing.
518 MachineIRBuilder MIRBuilder;
519
520 /// Optimization mode of the pass.
521 RegBankSelectMode OptMode;
522
523 /// The current Pass/MFAM reference to enable updating analyses.
524 Pass *P = nullptr;
525 MachineFunctionAnalysisManager *MFAM = nullptr;
526
527 /// Assign the register bank of each operand of \p MI.
528 /// \return True on success, false otherwise.
529 bool
530 assignInstr(MachineInstr &MI,
531 function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
532 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI);
533
534 /// Initialize the field members using \p MF.
535 void init(MachineFunction &MF,
536 function_ref<MachineBlockFrequencyInfo *()> GetMBFI,
537 function_ref<MachineBranchProbabilityInfo *()> GetMBPI);
538
539 /// Check if \p Reg is already assigned what is described by \p ValMapping.
540 /// \p OnlyAssign == true means that \p Reg just needs to be assigned a
541 /// register bank. I.e., no repairing is necessary to have the
542 /// assignment match.
543 bool assignmentMatch(Register Reg,
544 const RegisterBankInfo::ValueMapping &ValMapping,
545 bool &OnlyAssign) const;
546
547 /// Insert repairing code for \p Reg as specified by \p ValMapping.
548 /// The repairing placement is specified by \p RepairPt.
549 /// \p NewVRegs contains all the registers required to remap \p Reg.
550 /// In other words, the number of registers in NewVRegs must be equal
551 /// to ValMapping.BreakDown.size().
552 ///
553 /// The transformation could be sketched as:
554 /// \code
555 /// ... = op Reg
556 /// \endcode
557 /// Becomes
558 /// \code
559 /// <NewRegs> = COPY or extract Reg
560 /// ... = op Reg
561 /// \endcode
562 ///
563 /// and
564 /// \code
565 /// Reg = op ...
566 /// \endcode
567 /// Becomes
568 /// \code
569 /// Reg = op ...
570 /// Reg = COPY or build_sequence <NewRegs>
571 /// \endcode
572 ///
573 /// \pre NewVRegs.size() == ValMapping.BreakDown.size()
574 ///
575 /// \note The caller is supposed to do the rewriting of op if need be.
576 /// I.e., Reg = op ... => <NewRegs> = NewOp ...
577 ///
578 /// \return True if the repairing worked, false otherwise.
579 bool repairReg(MachineOperand &MO,
580 const RegisterBankInfo::ValueMapping &ValMapping,
581 RegBankSelectImpl::RepairingPlacement &RepairPt,
583 &NewVRegs);
584
585 /// Return the cost of the instruction needed to map \p MO to \p ValMapping.
586 /// The cost is free of basic block frequencies.
587 /// \pre MO.isReg()
588 /// \pre MO is assigned to a register bank.
589 /// \pre ValMapping is a valid mapping for MO.
591 getRepairCost(const MachineOperand &MO,
592 const RegisterBankInfo::ValueMapping &ValMapping) const;
593
594 /// Find the best mapping for \p MI from \p PossibleMappings.
595 /// \return a reference on the best mapping in \p PossibleMappings.
596 const RegisterBankInfo::InstructionMapping &
597 findBestMapping(MachineInstr &MI,
599 SmallVectorImpl<RepairingPlacement> &RepairPts,
600 function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
601 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI);
602
603 /// Compute the cost of mapping \p MI with \p InstrMapping and
604 /// compute the repairing placement for such mapping in \p
605 /// RepairPts.
606 /// \p BestCost is used to specify when the cost becomes too high
607 /// and thus it is not worth computing the RepairPts. Moreover if
608 /// \p BestCost == nullptr, the mapping cost is actually not
609 /// computed.
610 MappingCost
611 computeMapping(MachineInstr &MI,
612 const RegisterBankInfo::InstructionMapping &InstrMapping,
613 SmallVectorImpl<RepairingPlacement> &RepairPts,
614 function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
615 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI,
616 const MappingCost *BestCost = nullptr);
617
618 /// When \p RepairPt involves splitting to repair \p MO for the
619 /// given \p ValMapping, try to change the way we repair such that
620 /// the splitting is not required anymore.
621 ///
622 /// \pre \p RepairPt.hasSplit()
623 /// \pre \p MO == MO.getParent()->getOperand(\p RepairPt.getOpIdx())
624 /// \pre \p ValMapping is the mapping of \p MO for MO.getParent()
625 /// that implied \p RepairPt.
626 void tryAvoidingSplit(RegBankSelectImpl::RepairingPlacement &RepairPt,
627 const MachineOperand &MO,
628 const RegisterBankInfo::ValueMapping &ValMapping) const;
629
630 /// Apply \p Mapping to \p MI. \p RepairPts represents the different
631 /// mapping action that need to happen for the mapping to be
632 /// applied.
633 /// \return True if the mapping was applied sucessfully, false otherwise.
634 bool applyMapping(MachineInstr &MI,
635 const RegisterBankInfo::InstructionMapping &InstrMapping,
636 SmallVectorImpl<RepairingPlacement> &RepairPts);
637
638public:
639 /// Create a RegBankSelect pass with the specified \p RunningMode.
640 RegBankSelectImpl(RegBankSelectMode RunningMode);
641
642 /// Check that our input is fully legal: we require the function to have the
643 /// Legalized property, so it should be.
644 ///
645 /// FIXME: This should be in the MachineVerifier.
646 bool checkFunctionIsLegal(MachineFunction &MF) const;
647
648 /// Walk through \p MF and assign a register bank to every virtual register
649 /// that are still mapped to nothing.
650 /// The target needs to provide a RegisterBankInfo and in particular
651 /// override RegisterBankInfo::getInstrMapping.
652 ///
653 /// Simplified algo:
654 /// \code
655 /// RBI = MF.subtarget.getRegBankInfo()
656 /// MIRBuilder.setMF(MF)
657 /// for each bb in MF
658 /// for each inst in bb
659 /// MIRBuilder.setInstr(inst)
660 /// MappingCosts = RBI.getMapping(inst);
661 /// Idx = findIdxOfMinCost(MappingCosts)
662 /// CurRegBank = MappingCosts[Idx].RegBank
663 /// MRI.setRegBank(inst.getOperand(0).getReg(), CurRegBank)
664 /// for each argument in inst
665 /// if (CurRegBank != argument.RegBank)
666 /// ArgReg = argument.getReg()
667 /// Tmp = MRI.createNewVirtual(MRI.getSize(ArgReg), CurRegBank)
668 /// MIRBuilder.buildInstr(COPY, Tmp, ArgReg)
669 /// inst.getOperand(argument.getOperandNo()).setReg(Tmp)
670 /// \endcode
671 bool assignRegisterBanks(
672 MachineFunction &MF,
673 function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
674 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI);
675
676 bool runOnMachineFunction(
677 MachineFunction &MF, Pass *PassRef,
679 function_ref<MachineBlockFrequencyInfo *()> GetMBFI,
680 function_ref<MachineBranchProbabilityInfo *()> GetMBPI,
681 function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
682 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI);
683};
684
685} // namespace
686
687RegBankSelectImpl::RegBankSelectImpl(RegBankSelectMode RunningMode)
688 : OptMode(RunningMode) {}
689
691 : MachineFunctionPass(ID), OptMode(computeOptMode(RunningMode)) {}
692
693void RegBankSelectImpl::init(
696 RBI = MF.getSubtarget().getRegBankInfo();
697 assert(RBI && "Cannot work without RegisterBankInfo");
698 MRI = &MF.getRegInfo();
700 if (OptMode != RegBankSelectMode::Fast) {
701 MBFI = GetMBFI();
702 MBPI = GetMBPI();
703 } else {
704 MBFI = nullptr;
705 MBPI = nullptr;
706 }
707 MIRBuilder.setMF(MF);
708 MORE = std::make_unique<MachineOptimizationRemarkEmitter>(MF, MBFI);
709}
710
712 if (OptMode != RegBankSelectMode::Fast) {
713 // We could preserve the information from these two analysis but
714 // the APIs do not allow to do so yet.
717 }
721}
722
723bool RegBankSelectImpl::assignmentMatch(
724 Register Reg, const RegisterBankInfo::ValueMapping &ValMapping,
725 bool &OnlyAssign) const {
726 // By default we assume we will have to repair something.
727 OnlyAssign = false;
728 // Each part of a break down needs to end up in a different register.
729 // In other word, Reg assignment does not match.
730 if (ValMapping.NumBreakDowns != 1)
731 return false;
732
733 const RegisterBank *CurRegBank = RBI->getRegBank(Reg, *MRI, *TRI);
734 const RegisterBank *DesiredRegBank = ValMapping.BreakDown[0].RegBank;
735 // Reg is free of assignment, a simple assignment will make the
736 // register bank to match.
737 OnlyAssign = CurRegBank == nullptr;
738 LLVM_DEBUG(dbgs() << "Does assignment already match: ";
739 if (CurRegBank) dbgs() << *CurRegBank; else dbgs() << "none";
740 dbgs() << " against ";
741 assert(DesiredRegBank && "The mapping must be valid");
742 dbgs() << *DesiredRegBank << '\n';);
743 return CurRegBank == DesiredRegBank;
744}
745
746bool RegBankSelectImpl::repairReg(
747 MachineOperand &MO, const RegisterBankInfo::ValueMapping &ValMapping,
748 RegBankSelectImpl::RepairingPlacement &RepairPt,
750
751 assert(ValMapping.NumBreakDowns == (unsigned)size(NewVRegs) &&
752 "need new vreg for each breakdown");
753
754 // An empty range of new register means no repairing.
755 assert(!NewVRegs.empty() && "We should not have to repair");
756
758 if (ValMapping.NumBreakDowns == 1) {
759 // Assume we are repairing a use and thus, the original reg will be
760 // the source of the repairing.
761 Register Src = MO.getReg();
762 Register Dst = *NewVRegs.begin();
763
764 // If we repair a definition, swap the source and destination for
765 // the repairing.
766 if (MO.isDef())
767 std::swap(Src, Dst);
768
769 assert((RepairPt.getNumInsertPoints() == 1 || Dst.isPhysical()) &&
770 "We are about to create several defs for Dst");
771
772 // Build the instruction used to repair, then clone it at the right
773 // places. Avoiding buildCopy bypasses the check that Src and Dst have the
774 // same types because the type is a placeholder when this function is called.
775 MI = MIRBuilder.buildInstrNoInsert(TargetOpcode::COPY)
776 .addDef(Dst)
777 .addUse(Src);
778 LLVM_DEBUG(dbgs() << "Copy: " << printReg(Src) << ':'
779 << printRegClassOrBank(Src, *MRI, TRI)
780 << " to: " << printReg(Dst) << ':'
781 << printRegClassOrBank(Dst, *MRI, TRI) << '\n');
782 } else {
783 // TODO: Support with G_IMPLICIT_DEF + G_INSERT sequence or G_EXTRACT
784 // sequence.
785 assert(ValMapping.partsAllUniform() && "irregular breakdowns not supported");
786
787 LLT RegTy = MRI->getType(MO.getReg());
788 if (MO.isDef()) {
789 unsigned MergeOp;
790 if (RegTy.isVector()) {
791 if (ValMapping.NumBreakDowns == RegTy.getNumElements())
792 MergeOp = TargetOpcode::G_BUILD_VECTOR;
793 else {
794 assert(
795 (ValMapping.BreakDown[0].Length * ValMapping.NumBreakDowns ==
796 RegTy.getSizeInBits()) &&
797 (ValMapping.BreakDown[0].Length % RegTy.getScalarSizeInBits() ==
798 0) &&
799 "don't understand this value breakdown");
800
801 MergeOp = TargetOpcode::G_CONCAT_VECTORS;
802 }
803 } else
804 MergeOp = TargetOpcode::G_MERGE_VALUES;
805
806 auto MergeBuilder =
807 MIRBuilder.buildInstrNoInsert(MergeOp)
808 .addDef(MO.getReg());
809
810 for (Register SrcReg : NewVRegs)
811 MergeBuilder.addUse(SrcReg);
812
813 MI = MergeBuilder;
814 } else {
815 MachineInstrBuilder UnMergeBuilder =
816 MIRBuilder.buildInstrNoInsert(TargetOpcode::G_UNMERGE_VALUES);
817 for (Register DefReg : NewVRegs)
818 UnMergeBuilder.addDef(DefReg);
819
820 UnMergeBuilder.addUse(MO.getReg());
821 MI = UnMergeBuilder;
822 }
823 }
824
825 if (RepairPt.getNumInsertPoints() != 1)
826 report_fatal_error("need testcase to support multiple insertion points");
827
828 // TODO:
829 // Check if MI is legal. if not, we need to legalize all the
830 // instructions we are going to insert.
831 std::unique_ptr<MachineInstr *[]> NewInstrs(
832 new MachineInstr *[RepairPt.getNumInsertPoints()]);
833 bool IsFirst = true;
834 unsigned Idx = 0;
835 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
836 MachineInstr *CurMI;
837 if (IsFirst)
838 CurMI = MI;
839 else
840 CurMI = MIRBuilder.getMF().CloneMachineInstr(MI);
841 InsertPt->insert(*CurMI);
842 NewInstrs[Idx++] = CurMI;
843 IsFirst = false;
844 }
845 // TODO:
846 // Legalize NewInstrs if need be.
847 return true;
848}
849
850uint64_t RegBankSelectImpl::getRepairCost(
851 const MachineOperand &MO,
852 const RegisterBankInfo::ValueMapping &ValMapping) const {
853 assert(MO.isReg() && "We should only repair register operand");
854 assert(ValMapping.NumBreakDowns && "Nothing to map??");
855
856 bool IsSameNumOfValues = ValMapping.NumBreakDowns == 1;
857 const RegisterBank *CurRegBank = RBI->getRegBank(MO.getReg(), *MRI, *TRI);
858 // If MO does not have a register bank, we should have just been
859 // able to set one unless we have to break the value down.
860 assert(CurRegBank || MO.isDef());
861
862 // Def: Val <- NewDefs
863 // Same number of values: copy
864 // Different number: Val = build_sequence Defs1, Defs2, ...
865 // Use: NewSources <- Val.
866 // Same number of values: copy.
867 // Different number: Src1, Src2, ... =
868 // extract_value Val, Src1Begin, Src1Len, Src2Begin, Src2Len, ...
869 // We should remember that this value is available somewhere else to
870 // coalesce the value.
871
872 if (ValMapping.NumBreakDowns != 1)
873 return RBI->getBreakDownCost(ValMapping, CurRegBank);
874
875 if (IsSameNumOfValues) {
876 const RegisterBank *DesiredRegBank = ValMapping.BreakDown[0].RegBank;
877 // If we repair a definition, swap the source and destination for
878 // the repairing.
879 if (MO.isDef())
880 std::swap(CurRegBank, DesiredRegBank);
881 // TODO: It may be possible to actually avoid the copy.
882 // If we repair something where the source is defined by a copy
883 // and the source of that copy is on the right bank, we can reuse
884 // it for free.
885 // E.g.,
886 // RegToRepair<BankA> = copy AlternativeSrc<BankB>
887 // = op RegToRepair<BankA>
888 // We can simply propagate AlternativeSrc instead of copying RegToRepair
889 // into a new virtual register.
890 // We would also need to propagate this information in the
891 // repairing placement.
892 unsigned Cost = RBI->copyCost(*DesiredRegBank, *CurRegBank,
893 RBI->getSizeInBits(MO.getReg(), *MRI, *TRI));
895 return Cost;
896 // Return the legalization cost of that repairing.
897 }
899}
900
901const RegisterBankInfo::InstructionMapping &RegBankSelectImpl::findBestMapping(
904 function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
905 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI) {
906 assert(!PossibleMappings.empty() &&
907 "Do not know how to map this instruction");
908
909 const RegisterBankInfo::InstructionMapping *BestMapping = nullptr;
910 MappingCost Cost = MappingCost::ImpossibleCost();
912 for (const RegisterBankInfo::InstructionMapping *CurMapping :
913 PossibleMappings) {
914 MappingCost CurCost = computeMapping(MI, *CurMapping, LocalRepairPts,
915 GetCachedMBFI, GetCachedMBPI, &Cost);
916 if (CurCost < Cost) {
917 LLVM_DEBUG(dbgs() << "New best: " << CurCost << '\n');
918 Cost = CurCost;
919 BestMapping = CurMapping;
920 RepairPts.clear();
921 for (RepairingPlacement &RepairPt : LocalRepairPts)
922 RepairPts.emplace_back(std::move(RepairPt));
923 }
924 }
925 if (!BestMapping && MI.getMF()->getTarget().Options.GlobalISelAbort !=
927 // If none of the mapping worked that means they are all impossible.
928 // Thus, pick the first one and set an impossible repairing point.
929 // It will trigger the failed isel mode.
930 BestMapping = *PossibleMappings.begin();
931 RepairPts.emplace_back(RepairingPlacement(MI, 0, *TRI, P, MFAM,
932 RepairingPlacement::Impossible));
933 } else
934 assert(BestMapping && "No suitable mapping for instruction");
935 return *BestMapping;
936}
937
938void RegBankSelectImpl::tryAvoidingSplit(
939 RegBankSelectImpl::RepairingPlacement &RepairPt, const MachineOperand &MO,
940 const RegisterBankInfo::ValueMapping &ValMapping) const {
941 const MachineInstr &MI = *MO.getParent();
942 assert(RepairPt.hasSplit() && "We should not have to adjust for split");
943 // Splitting should only occur for PHIs or between terminators,
944 // because we only do local repairing.
945 assert((MI.isPHI() || MI.isTerminator()) && "Why do we split?");
946
947 assert(&MI.getOperand(RepairPt.getOpIdx()) == &MO &&
948 "Repairing placement does not match operand");
949
950 // If we need splitting for phis, that means it is because we
951 // could not find an insertion point before the terminators of
952 // the predecessor block for this argument. In other words,
953 // the input value is defined by one of the terminators.
954 assert((!MI.isPHI() || !MO.isDef()) && "Need split for phi def?");
955
956 // We split to repair the use of a phi or a terminator.
957 if (!MO.isDef()) {
958 if (MI.isTerminator()) {
959 assert(&MI != &(*MI.getParent()->getFirstTerminator()) &&
960 "Need to split for the first terminator?!");
961 } else {
962 // For the PHI case, the split may not be actually required.
963 // In the copy case, a phi is already a copy on the incoming edge,
964 // therefore there is no need to split.
965 if (ValMapping.NumBreakDowns == 1)
966 // This is a already a copy, there is nothing to do.
967 RepairPt.switchTo(RepairingPlacement::RepairingKind::Reassign);
968 }
969 return;
970 }
971
972 // At this point, we need to repair a defintion of a terminator.
973
974 // Technically we need to fix the def of MI on all outgoing
975 // edges of MI to keep the repairing local. In other words, we
976 // will create several definitions of the same register. This
977 // does not work for SSA unless that definition is a physical
978 // register.
979 // However, there are other cases where we can get away with
980 // that while still keeping the repairing local.
981 assert(MI.isTerminator() && MO.isDef() &&
982 "This code is for the def of a terminator");
983
984 // Since we use RPO traversal, if we need to repair a definition
985 // this means this definition could be:
986 // 1. Used by PHIs (i.e., this VReg has been visited as part of the
987 // uses of a phi.), or
988 // 2. Part of a target specific instruction (i.e., the target applied
989 // some register class constraints when creating the instruction.)
990 // If the constraints come for #2, the target said that another mapping
991 // is supported so we may just drop them. Indeed, if we do not change
992 // the number of registers holding that value, the uses will get fixed
993 // when we get to them.
994 // Uses in PHIs may have already been proceeded though.
995 // If the constraints come for #1, then, those are weak constraints and
996 // no actual uses may rely on them. However, the problem remains mainly
997 // the same as for #2. If the value stays in one register, we could
998 // just switch the register bank of the definition, but we would need to
999 // account for a repairing cost for each phi we silently change.
1000 //
1001 // In any case, if the value needs to be broken down into several
1002 // registers, the repairing is not local anymore as we need to patch
1003 // every uses to rebuild the value in just one register.
1004 //
1005 // To summarize:
1006 // - If the value is in a physical register, we can do the split and
1007 // fix locally.
1008 // Otherwise if the value is in a virtual register:
1009 // - If the value remains in one register, we do not have to split
1010 // just switching the register bank would do, but we need to account
1011 // in the repairing cost all the phi we changed.
1012 // - If the value spans several registers, then we cannot do a local
1013 // repairing.
1014
1015 // Check if this is a physical or virtual register.
1016 Register Reg = MO.getReg();
1017 if (Reg.isPhysical()) {
1018 // We are going to split every outgoing edges.
1019 // Check that this is possible.
1020 // FIXME: The machine representation is currently broken
1021 // since it also several terminators in one basic block.
1022 // Because of that we would technically need a way to get
1023 // the targets of just one terminator to know which edges
1024 // we have to split.
1025 // Assert that we do not hit the ill-formed representation.
1026
1027 // If there are other terminators before that one, some of
1028 // the outgoing edges may not be dominated by this definition.
1029 assert(&MI == &(*MI.getParent()->getFirstTerminator()) &&
1030 "Do not know which outgoing edges are relevant");
1031 const MachineInstr *Next = MI.getNextNode();
1032 assert((!Next || Next->isUnconditionalBranch()) &&
1033 "Do not know where each terminator ends up");
1034 if (Next)
1035 // If the next terminator uses Reg, this means we have
1036 // to split right after MI and thus we need a way to ask
1037 // which outgoing edges are affected.
1038 assert(!Next->readsRegister(Reg, /*TRI=*/nullptr) &&
1039 "Need to split between terminators");
1040 // We will split all the edges and repair there.
1041 } else {
1042 // This is a virtual register defined by a terminator.
1043 if (ValMapping.NumBreakDowns == 1) {
1044 // There is nothing to repair, but we may actually lie on
1045 // the repairing cost because of the PHIs already proceeded
1046 // as already stated.
1047 // Though the code will be correct.
1048 assert(false && "Repairing cost may not be accurate");
1049 } else {
1050 // We need to do non-local repairing. Basically, patch all
1051 // the uses (i.e., phis) that we already proceeded.
1052 // For now, just say this mapping is not possible.
1053 RepairPt.switchTo(RepairingPlacement::RepairingKind::Impossible);
1054 }
1055 }
1056}
1057
1058RegBankSelectImpl::MappingCost RegBankSelectImpl::computeMapping(
1061 function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
1062 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI,
1063 const RegBankSelectImpl::MappingCost *BestCost) {
1064 assert((MBFI || !BestCost) && "Costs comparison require MBFI");
1065
1066 if (!InstrMapping.isValid())
1067 return MappingCost::ImpossibleCost();
1068
1069 // If mapped with InstrMapping, MI will have the recorded cost.
1070 MappingCost Cost(MBFI ? MBFI->getBlockFreq(MI.getParent())
1071 : BlockFrequency(1));
1072 bool Saturated = Cost.addLocalCost(InstrMapping.getCost());
1073 assert(!Saturated && "Possible mapping saturated the cost");
1074 LLVM_DEBUG(dbgs() << "Evaluating mapping cost for: " << MI);
1075 LLVM_DEBUG(dbgs() << "With: " << InstrMapping << '\n');
1076 RepairPts.clear();
1077 if (BestCost && Cost > *BestCost) {
1078 LLVM_DEBUG(dbgs() << "Mapping is too expensive from the start\n");
1079 return Cost;
1080 }
1081 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1082
1083 // Moreover, to realize this mapping, the register bank of each operand must
1084 // match this mapping. In other words, we may need to locally reassign the
1085 // register banks. Account for that repairing cost as well.
1086 // In this context, local means in the surrounding of MI.
1087 for (unsigned OpIdx = 0, EndOpIdx = InstrMapping.getNumOperands();
1088 OpIdx != EndOpIdx; ++OpIdx) {
1089 const MachineOperand &MO = MI.getOperand(OpIdx);
1090 if (!MO.isReg())
1091 continue;
1092 Register Reg = MO.getReg();
1093 if (!Reg)
1094 continue;
1095 LLT Ty = MRI.getType(Reg);
1096 if (!Ty.isValid())
1097 continue;
1098
1099 LLVM_DEBUG(dbgs() << "Opd" << OpIdx << '\n');
1100 const RegisterBankInfo::ValueMapping &ValMapping =
1101 InstrMapping.getOperandMapping(OpIdx);
1102 // If Reg is already properly mapped, this is free.
1103 bool Assign;
1104 if (assignmentMatch(Reg, ValMapping, Assign)) {
1105 LLVM_DEBUG(dbgs() << "=> is free (match).\n");
1106 continue;
1107 }
1108 if (Assign) {
1109 LLVM_DEBUG(dbgs() << "=> is free (simple assignment).\n");
1110 RepairPts.emplace_back(RepairingPlacement(MI, OpIdx, *TRI, P, MFAM,
1111 RepairingPlacement::Reassign));
1112 continue;
1113 }
1114
1115 // Find the insertion point for the repairing code.
1116 RepairPts.emplace_back(RepairingPlacement(MI, OpIdx, *TRI, P, MFAM,
1117 RepairingPlacement::Insert));
1118 RepairingPlacement &RepairPt = RepairPts.back();
1119
1120 // If we need to split a basic block to materialize this insertion point,
1121 // we may give a higher cost to this mapping.
1122 // Nevertheless, we may get away with the split, so try that first.
1123 if (RepairPt.hasSplit())
1124 tryAvoidingSplit(RepairPt, MO, ValMapping);
1125
1126 // Check that the materialization of the repairing is possible.
1127 if (!RepairPt.canMaterialize()) {
1128 LLVM_DEBUG(dbgs() << "Mapping involves impossible repairing\n");
1129 return MappingCost::ImpossibleCost();
1130 }
1131
1132 // Account for the split cost and repair cost.
1133 // Unless the cost is already saturated or we do not care about the cost.
1134 if (!BestCost || Saturated)
1135 continue;
1136
1137 // To get accurate information we need MBFI and MBPI.
1138 // Thus, if we end up here this information should be here.
1139 assert(MBFI && MBPI && "Cost computation requires MBFI and MBPI");
1140
1141 // FIXME: We will have to rework the repairing cost model.
1142 // The repairing cost depends on the register bank that MO has.
1143 // However, when we break down the value into different values,
1144 // MO may not have a register bank while still needing repairing.
1145 // For the fast mode, we don't compute the cost so that is fine,
1146 // but still for the repairing code, we will have to make a choice.
1147 // For the greedy mode, we should choose greedily what is the best
1148 // choice based on the next use of MO.
1149
1150 // Sums up the repairing cost of MO at each insertion point.
1151 uint64_t RepairCost = getRepairCost(MO, ValMapping);
1152
1153 // This is an impossible to repair cost.
1154 if (RepairCost == ImpossibleRepairCost)
1155 return MappingCost::ImpossibleCost();
1156
1157 // Bias used for splitting: 5%.
1158 const uint64_t PercentageForBias = 5;
1159 uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100;
1160 // We should not need more than a couple of instructions to repair
1161 // an assignment. In other words, the computation should not
1162 // overflow because the repairing cost is free of basic block
1163 // frequency.
1164 assert(((RepairCost < RepairCost * PercentageForBias) &&
1165 (RepairCost * PercentageForBias <
1166 RepairCost * PercentageForBias + 99)) &&
1167 "Repairing involves more than a billion of instructions?!");
1168 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
1169 assert(InsertPt->canMaterialize() && "We should not have made it here");
1170 // We will applied some basic block frequency and those uses uint64_t.
1171 if (!InsertPt->isSplit())
1172 Saturated = Cost.addLocalCost(RepairCost);
1173 else {
1174 uint64_t CostForInsertPt = RepairCost;
1175 // Again we shouldn't overflow here givent that
1176 // CostForInsertPt is frequency free at this point.
1177 assert(CostForInsertPt + Bias > CostForInsertPt &&
1178 "Repairing + split bias overflows");
1179 CostForInsertPt += Bias;
1180 uint64_t PtCost =
1181 InsertPt->frequency(GetCachedMBFI, GetCachedMBPI) * CostForInsertPt;
1182 // Check if we just overflowed.
1183 if ((Saturated = PtCost < CostForInsertPt))
1184 Cost.saturate();
1185 else
1186 Saturated = Cost.addNonLocalCost(PtCost);
1187 }
1188
1189 // Stop looking into what it takes to repair, this is already
1190 // too expensive.
1191 if (BestCost && Cost > *BestCost) {
1192 LLVM_DEBUG(dbgs() << "Mapping is too expensive, stop processing\n");
1193 return Cost;
1194 }
1195
1196 // No need to accumulate more cost information.
1197 // We need to still gather the repairing information though.
1198 if (Saturated)
1199 break;
1200 }
1201 }
1202 LLVM_DEBUG(dbgs() << "Total cost is: " << Cost << "\n");
1203 return Cost;
1204}
1205
1206bool RegBankSelectImpl::applyMapping(
1209 // OpdMapper will hold all the information needed for the rewriting.
1210 std::optional<RegisterBankInfo::OperandsMapper> OpdMapper;
1211
1212 // First, place the repairing code.
1213 for (RepairingPlacement &RepairPt : RepairPts) {
1214 if (!RepairPt.canMaterialize() ||
1215 RepairPt.getKind() == RepairingPlacement::Impossible)
1216 return false;
1217 assert(RepairPt.getKind() != RepairingPlacement::None &&
1218 "This should not make its way in the list");
1219 unsigned OpIdx = RepairPt.getOpIdx();
1220 MachineOperand &MO = MI.getOperand(OpIdx);
1221 const RegisterBankInfo::ValueMapping &ValMapping =
1222 InstrMapping.getOperandMapping(OpIdx);
1223 Register Reg = MO.getReg();
1224
1225 switch (RepairPt.getKind()) {
1226 case RepairingPlacement::Reassign:
1227 assert(ValMapping.NumBreakDowns == 1 &&
1228 "Reassignment should only be for simple mapping");
1229 MRI->setRegBank(Reg, *ValMapping.BreakDown[0].RegBank);
1230 break;
1231 case RepairingPlacement::Insert:
1232 // Don't insert additional instruction for debug instruction.
1233 if (MI.isDebugInstr())
1234 break;
1235 if (!OpdMapper)
1236 OpdMapper.emplace(MI, InstrMapping, *MRI);
1237 OpdMapper->createVRegs(OpIdx);
1238 if (!repairReg(MO, ValMapping, RepairPt, OpdMapper->getVRegs(OpIdx)))
1239 return false;
1240 break;
1241 default:
1242 llvm_unreachable("Other kind should not happen");
1243 }
1244 }
1245
1246 // Default mappings only need rewriting when repairs create new operands.
1247 if (!OpdMapper && InstrMapping.getID() == RegisterBankInfo::DefaultMappingID)
1248 return true;
1249
1250 if (!OpdMapper)
1251 OpdMapper.emplace(MI, InstrMapping, *MRI);
1252 // Second, rewrite the instruction.
1253 LLVM_DEBUG(dbgs() << "Actual mapping of the operands: " << *OpdMapper
1254 << '\n');
1255 RBI->applyMapping(MIRBuilder, *OpdMapper);
1256
1257 return true;
1258}
1259
1260bool RegBankSelectImpl::assignInstr(
1262 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI) {
1263 LLVM_DEBUG(dbgs() << "Assign: " << MI);
1264
1265 unsigned Opc = MI.getOpcode();
1267 assert((Opc == TargetOpcode::G_ASSERT_ZEXT ||
1268 Opc == TargetOpcode::G_ASSERT_SEXT ||
1269 Opc == TargetOpcode::G_ASSERT_ALIGN) &&
1270 "Unexpected hint opcode!");
1271 // The only correct mapping for these is to always use the source register
1272 // bank.
1273 const RegisterBank *RB =
1274 RBI->getRegBank(MI.getOperand(1).getReg(), *MRI, *TRI);
1275 // We can assume every instruction above this one has a selected register
1276 // bank.
1277 assert(RB && "Expected source register to have a register bank?");
1278 LLVM_DEBUG(dbgs() << "... Hint always uses source's register bank.\n");
1279 MRI->setRegBank(MI.getOperand(0).getReg(), *RB);
1280 return true;
1281 }
1282
1283 // Remember the repairing placement for all the operands.
1285
1286 const RegisterBankInfo::InstructionMapping *BestMapping;
1287 if (OptMode == RegBankSelectMode::Fast) {
1288 BestMapping = &RBI->getInstrMapping(MI);
1289 MappingCost DefaultCost = computeMapping(MI, *BestMapping, RepairPts,
1290 GetCachedMBFI, GetCachedMBPI);
1291 (void)DefaultCost;
1292 if (DefaultCost == MappingCost::ImpossibleCost())
1293 return false;
1294 } else {
1295 RegisterBankInfo::InstructionMappings PossibleMappings =
1297 if (PossibleMappings.empty())
1298 return false;
1299 BestMapping = &findBestMapping(MI, PossibleMappings, RepairPts,
1300 GetCachedMBFI, GetCachedMBPI);
1301 }
1302 // Make sure the mapping is valid for MI.
1303 assert(BestMapping->verify(MI) && "Invalid instruction mapping");
1304
1305 LLVM_DEBUG(dbgs() << "Best Mapping: " << *BestMapping << '\n');
1306
1307 // After this call, MI may not be valid anymore.
1308 // Do not use it.
1309 return applyMapping(MI, *BestMapping, RepairPts);
1310}
1311
1312bool RegBankSelectImpl::assignRegisterBanks(
1313 MachineFunction &MF,
1314 function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
1315 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI) {
1316 // Walk the function and assign register banks to all operands.
1317 // Use a RPOT to make sure all registers are assigned before we choose
1318 // the best mapping of the current instruction.
1320 for (MachineBasicBlock *MBB : RPOT) {
1321 // Set a sensible insertion point so that subsequent calls to
1322 // MIRBuilder.
1323 MIRBuilder.setMBB(*MBB);
1326
1327 while (!WorkList.empty()) {
1328 MachineInstr &MI = *WorkList.pop_back_val();
1329
1330 // Ignore target-specific post-isel instructions: they should use proper
1331 // regclasses.
1332 if (isTargetSpecificOpcode(MI.getOpcode()) && !MI.isPreISelOpcode())
1333 continue;
1334
1335 // Ignore inline asm instructions: they should use physical
1336 // registers/regclasses
1337 if (MI.isInlineAsm())
1338 continue;
1339
1340 // Ignore IMPLICIT_DEF which must have a regclass.
1341 if (MI.isImplicitDef())
1342 continue;
1343
1344 if (!assignInstr(MI, GetCachedMBFI, GetCachedMBPI)) {
1345 reportGISelFailure(MF, *MORE, "gisel-regbankselect",
1346 "unable to map instruction", MI);
1347 return false;
1348 }
1349 }
1350 }
1351
1352 return true;
1353}
1354
1355bool RegBankSelectImpl::checkFunctionIsLegal(MachineFunction &MF) const {
1356#ifndef NDEBUG
1358 if (const MachineInstr *MI = machineFunctionIsIllegal(MF)) {
1359 reportGISelFailure(MF, *MORE, "gisel-regbankselect",
1360 "instruction is not legal", *MI);
1361 return false;
1362 }
1363 }
1364#endif
1365 return true;
1366}
1367
1368bool RegBankSelectImpl::runOnMachineFunction(
1369 MachineFunction &MF, Pass *PassRef, MachineFunctionAnalysisManager *MFAMRef,
1372 function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
1373 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI) {
1374 // If the ISel pipeline failed, do not bother running that pass.
1375 if (MF.getProperties().hasFailedISel())
1376 return false;
1377
1378 P = PassRef;
1379 MFAM = MFAMRef;
1380
1381 LLVM_DEBUG(dbgs() << "Assign register banks for: " << MF.getName() << '\n');
1382 const Function &F = MF.getFunction();
1383 RegBankSelectMode SaveOptMode = OptMode;
1384 if (F.hasOptNone())
1385 OptMode = RegBankSelectMode::Fast;
1386 init(MF, GetMBFI, GetMBPI);
1387
1388#ifndef NDEBUG
1389 if (!checkFunctionIsLegal(MF))
1390 return false;
1391#endif
1392
1393 assignRegisterBanks(MF, GetCachedMBFI, GetCachedMBPI);
1394
1395 OptMode = SaveOptMode;
1396 return false;
1397}
1398
1399//------------------------------------------------------------------------------
1400// Helper Classes Implementation
1401//------------------------------------------------------------------------------
1402RegBankSelectImpl::RepairingPlacement::RepairingPlacement(
1403 MachineInstr &MI, unsigned OpIdx, const TargetRegisterInfo &TRI, Pass *P,
1405 RepairingPlacement::RepairingKind Kind)
1406 // Default is, we are going to insert code to repair OpIdx.
1407 : Kind(Kind), OpIdx(OpIdx),
1408 CanMaterialize(Kind != RepairingKind::Impossible), P(P) {
1409 const MachineOperand &MO = MI.getOperand(OpIdx);
1410 assert(MO.isReg() && "Trying to repair a non-reg operand");
1411
1412 if (Kind != RepairingKind::Insert)
1413 return;
1414
1415 // Repairings for definitions happen after MI, uses happen before.
1416 bool Before = !MO.isDef();
1417
1418 // Check if we are done with MI.
1419 if (!MI.isPHI() && !MI.isTerminator()) {
1420 addInsertPoint(MI, Before);
1421 // We are done with the initialization.
1422 return;
1423 }
1424
1425 // Now, look for the special cases.
1426 if (MI.isPHI()) {
1427 // - PHI must be the first instructions:
1428 // * Before, we have to split the related incoming edge.
1429 // * After, move the insertion point past the last phi.
1430 if (!Before) {
1431 MachineBasicBlock::iterator It = MI.getParent()->getFirstNonPHI();
1432 if (It != MI.getParent()->end())
1433 addInsertPoint(*It, /*Before*/ true);
1434 else
1435 addInsertPoint(*(--It), /*Before*/ false);
1436 return;
1437 }
1438 // We repair a use of a phi, we may need to split the related edge.
1439 MachineBasicBlock &Pred = *MI.getOperand(OpIdx + 1).getMBB();
1440 // Check if we can move the insertion point prior to the
1441 // terminators of the predecessor.
1442 Register Reg = MO.getReg();
1444 for (auto Begin = Pred.begin(); It != Begin && It->isTerminator(); --It)
1445 if (It->modifiesRegister(Reg, &TRI)) {
1446 // We cannot hoist the repairing code in the predecessor.
1447 // Split the edge.
1448 addInsertPoint(Pred, *MI.getParent());
1449 return;
1450 }
1451 // At this point, we can insert in Pred.
1452
1453 // - If It is invalid, Pred is empty and we can insert in Pred
1454 // wherever we want.
1455 // - If It is valid, It is the first non-terminator, insert after It.
1456 if (It == Pred.end())
1457 addInsertPoint(Pred, /*Beginning*/ false);
1458 else
1459 addInsertPoint(*It, /*Before*/ false);
1460 } else {
1461 // - Terminators must be the last instructions:
1462 // * Before, move the insert point before the first terminator.
1463 // * After, we have to split the outcoming edges.
1464 if (Before) {
1465 // Check whether Reg is defined by any terminator.
1467 auto REnd = MI.getParent()->rend();
1468
1469 for (; It != REnd && It->isTerminator(); ++It) {
1470 assert(!It->modifiesRegister(MO.getReg(), &TRI) &&
1471 "copy insertion in middle of terminators not handled");
1472 }
1473
1474 if (It == REnd) {
1475 addInsertPoint(*MI.getParent()->begin(), true);
1476 return;
1477 }
1478
1479 // We are sure to be right before the first terminator.
1480 addInsertPoint(*It, /*Before*/ false);
1481 return;
1482 }
1483 // Make sure Reg is not redefined by other terminators, otherwise
1484 // we do not know how to split.
1485 for (MachineBasicBlock::iterator It = MI, End = MI.getParent()->end();
1486 ++It != End;)
1487 // The machine verifier should reject this kind of code.
1488 assert(It->modifiesRegister(MO.getReg(), &TRI) &&
1489 "Do not know where to split");
1490 // Split each outcoming edges.
1491 MachineBasicBlock &Src = *MI.getParent();
1492 for (auto &Succ : Src.successors())
1493 addInsertPoint(Src, Succ);
1494 }
1495}
1496
1497void RegBankSelectImpl::RepairingPlacement::addInsertPoint(MachineInstr &MI,
1498 bool Before) {
1499 addInsertPoint(*new InstrInsertPoint(MI, Before));
1500}
1501
1502void RegBankSelectImpl::RepairingPlacement::addInsertPoint(
1503 MachineBasicBlock &MBB, bool Beginning) {
1504 addInsertPoint(*new MBBInsertPoint(MBB, Beginning));
1505}
1506
1507void RegBankSelectImpl::RepairingPlacement::addInsertPoint(
1509 addInsertPoint(*new EdgeInsertPoint(Src, Dst, P, MFAM));
1510}
1511
1512void RegBankSelectImpl::RepairingPlacement::addInsertPoint(
1513 RegBankSelectImpl::InsertPoint &Point) {
1514 CanMaterialize &= Point.canMaterialize();
1515 HasSplit |= Point.isSplit();
1516 InsertPoints.emplace_back(&Point);
1517}
1518
1519RegBankSelectImpl::InstrInsertPoint::InstrInsertPoint(MachineInstr &Instr,
1520 bool Before)
1521 : Instr(Instr), Before(Before) {
1522 // Since we do not support splitting, we do not need to update
1523 // liveness and such, so do not do anything with P.
1524 assert((!Before || !Instr.isPHI()) &&
1525 "Splitting before phis requires more points");
1526 assert((!Before || !Instr.getNextNode() || !Instr.getNextNode()->isPHI()) &&
1527 "Splitting between phis does not make sense");
1528}
1529
1530void RegBankSelectImpl::InstrInsertPoint::materialize() {
1531 if (isSplit()) {
1532 // Slice and return the beginning of the new block.
1533 // If we need to split between the terminators, we theoritically
1534 // need to know where the first and second set of terminators end
1535 // to update the successors properly.
1536 // Now, in pratice, we should have a maximum of 2 branch
1537 // instructions; one conditional and one unconditional. Therefore
1538 // we know how to update the successor by looking at the target of
1539 // the unconditional branch.
1540 // If we end up splitting at some point, then, we should update
1541 // the liveness information and such. I.e., we would need to
1542 // access P here.
1543 // The machine verifier should actually make sure such cases
1544 // cannot happen.
1545 llvm_unreachable("Not yet implemented");
1546 }
1547 // Otherwise the insertion point is just the current or next
1548 // instruction depending on Before. I.e., there is nothing to do
1549 // here.
1550}
1551
1552bool RegBankSelectImpl::InstrInsertPoint::isSplit() const {
1553 // If the insertion point is after a terminator, we need to split.
1554 if (!Before)
1555 return Instr.isTerminator();
1556 // If we insert before an instruction that is after a terminator,
1557 // we are still after a terminator.
1558 return Instr.getPrevNode() && Instr.getPrevNode()->isTerminator();
1559}
1560
1561uint64_t RegBankSelectImpl::InstrInsertPoint::frequency(
1562 function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
1563 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI) const {
1564 // Even if we need to split, because we insert between terminators,
1565 // this split has actually the same frequency as the instruction.
1566 const MachineBlockFrequencyInfo *MBFI = GetCachedMBFI();
1567 if (!MBFI)
1568 return 1;
1569 return MBFI->getBlockFreq(Instr.getParent()).getFrequency();
1570}
1571
1572uint64_t RegBankSelectImpl::MBBInsertPoint::frequency(
1573 function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
1574 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI) const {
1575 const MachineBlockFrequencyInfo *MBFI = GetCachedMBFI();
1576 if (!MBFI)
1577 return 1;
1578 return MBFI->getBlockFreq(&MBB).getFrequency();
1579}
1580
1581void RegBankSelectImpl::EdgeInsertPoint::materialize() {
1582 // If we end up repairing twice at the same place before materializing the
1583 // insertion point, we may think we have to split an edge twice.
1584 // We should have a factory for the insert point such that identical points
1585 // are the same instance.
1586 assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
1587 "This point has already been split");
1588 MachineBasicBlock *NewBB = Src.SplitCriticalEdge(DstOrSplit, P, MFAM);
1589 assert(NewBB && "Invalid call to materialize");
1590 // We reuse the destination block to hold the information of the new block.
1591 DstOrSplit = NewBB;
1592}
1593
1594uint64_t RegBankSelectImpl::EdgeInsertPoint::frequency(
1595 function_ref<MachineBlockFrequencyInfo *()> GetCachedMBFI,
1596 function_ref<MachineBranchProbabilityInfo *()> GetCachedMBPI) const {
1597 const MachineBlockFrequencyInfo *MBFI = GetCachedMBFI();
1598 if (!MBFI)
1599 return 1;
1600 if (WasMaterialized)
1601 return MBFI->getBlockFreq(DstOrSplit).getFrequency();
1602
1603 const MachineBranchProbabilityInfo *MBPI = GetCachedMBPI();
1604 if (!MBPI)
1605 return 1;
1606 // The basic block will be on the edge.
1607 return (MBFI->getBlockFreq(&Src) * MBPI->getEdgeProbability(&Src, DstOrSplit))
1608 .getFrequency();
1609}
1610
1611bool RegBankSelectImpl::EdgeInsertPoint::canMaterialize() const {
1612 // If this is not a critical edge, we should not have used this insert
1613 // point. Indeed, either the successor or the predecessor should
1614 // have do.
1615 assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
1616 "Edge is not critical");
1617 return Src.canSplitCriticalEdge(DstOrSplit);
1618}
1619
1620RegBankSelectImpl::MappingCost::MappingCost(BlockFrequency LocalFreq)
1621 : LocalFreq(LocalFreq.getFrequency()) {}
1622
1623bool RegBankSelectImpl::MappingCost::addLocalCost(uint64_t Cost) {
1624 // Check if this overflows.
1625 if (LocalCost + Cost < LocalCost) {
1626 saturate();
1627 return true;
1628 }
1629 LocalCost += Cost;
1630 return isSaturated();
1631}
1632
1633bool RegBankSelectImpl::MappingCost::addNonLocalCost(uint64_t Cost) {
1634 // Check if this overflows.
1635 if (NonLocalCost + Cost < NonLocalCost) {
1636 saturate();
1637 return true;
1638 }
1639 NonLocalCost += Cost;
1640 return isSaturated();
1641}
1642
1643bool RegBankSelectImpl::MappingCost::isSaturated() const {
1644 return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
1645 LocalFreq == UINT64_MAX;
1646}
1647
1648void RegBankSelectImpl::MappingCost::saturate() {
1649 *this = ImpossibleCost();
1650 --LocalCost;
1651}
1652
1653RegBankSelectImpl::MappingCost
1654RegBankSelectImpl::MappingCost::ImpossibleCost() {
1655 return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
1656}
1657
1658bool RegBankSelectImpl::MappingCost::operator<(const MappingCost &Cost) const {
1659 // Sort out the easy cases.
1660 if (*this == Cost)
1661 return false;
1662 // If one is impossible to realize the other is cheaper unless it is
1663 // impossible as well.
1664 if ((*this == ImpossibleCost()) || (Cost == ImpossibleCost()))
1665 return (*this == ImpossibleCost()) < (Cost == ImpossibleCost());
1666 // If one is saturated the other is cheaper, unless it is saturated
1667 // as well.
1668 if (isSaturated() || Cost.isSaturated())
1669 return isSaturated() < Cost.isSaturated();
1670 // At this point we know both costs hold sensible values.
1671
1672 // If both values have a different base frequency, there is no much
1673 // we can do but to scale everything.
1674 // However, if they have the same base frequency we can avoid making
1675 // complicated computation.
1676 uint64_t ThisLocalAdjust;
1677 uint64_t OtherLocalAdjust;
1678 if (LLVM_LIKELY(LocalFreq == Cost.LocalFreq)) {
1679
1680 // At this point, we know the local costs are comparable.
1681 // Do the case that do not involve potential overflow first.
1682 if (NonLocalCost == Cost.NonLocalCost)
1683 // Since the non-local costs do not discriminate on the result,
1684 // just compare the local costs.
1685 return LocalCost < Cost.LocalCost;
1686
1687 // The base costs are comparable so we may only keep the relative
1688 // value to increase our chances of avoiding overflows.
1689 ThisLocalAdjust = 0;
1690 OtherLocalAdjust = 0;
1691 if (LocalCost < Cost.LocalCost)
1692 OtherLocalAdjust = Cost.LocalCost - LocalCost;
1693 else
1694 ThisLocalAdjust = LocalCost - Cost.LocalCost;
1695 } else {
1696 ThisLocalAdjust = LocalCost;
1697 OtherLocalAdjust = Cost.LocalCost;
1698 }
1699
1700 // The non-local costs are comparable, just keep the relative value.
1701 uint64_t ThisNonLocalAdjust = 0;
1702 uint64_t OtherNonLocalAdjust = 0;
1703 if (NonLocalCost < Cost.NonLocalCost)
1704 OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
1705 else
1706 ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
1707 // Scale everything to make them comparable.
1708 uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
1709 // Check for overflow on that operation.
1710 bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
1711 ThisScaledCost < LocalFreq);
1712 uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
1713 // Check for overflow on the last operation.
1714 bool OtherOverflows =
1715 OtherLocalAdjust &&
1716 (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
1717 // Add the non-local costs.
1718 ThisOverflows |= ThisNonLocalAdjust &&
1719 ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
1720 ThisScaledCost += ThisNonLocalAdjust;
1721 OtherOverflows |= OtherNonLocalAdjust &&
1722 OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
1723 OtherScaledCost += OtherNonLocalAdjust;
1724 // If both overflows, we cannot compare without additional
1725 // precision, e.g., APInt. Just give up on that case.
1726 if (ThisOverflows && OtherOverflows)
1727 return false;
1728 // If one overflows but not the other, we can still compare.
1729 if (ThisOverflows || OtherOverflows)
1730 return ThisOverflows < OtherOverflows;
1731 // Otherwise, just compare the values.
1732 return ThisScaledCost < OtherScaledCost;
1733}
1734
1735bool RegBankSelectImpl::MappingCost::operator==(const MappingCost &Cost) const {
1736 return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
1737 LocalFreq == Cost.LocalFreq;
1738}
1739
1740#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1741LLVM_DUMP_METHOD void RegBankSelectImpl::MappingCost::dump() const {
1742 print(dbgs());
1743 dbgs() << '\n';
1744}
1745#endif
1746
1747void RegBankSelectImpl::MappingCost::print(raw_ostream &OS) const {
1748 if (*this == ImpossibleCost()) {
1749 OS << "impossible";
1750 return;
1751 }
1752 if (isSaturated()) {
1753 OS << "saturated";
1754 return;
1755 }
1756 OS << LocalFreq << " * " << LocalCost << " + " << NonLocalCost;
1757}
1758
1760 RegBankSelectImpl Impl(OptMode);
1761 return Impl.runOnMachineFunction(
1762 MF, this, nullptr,
1763 [&]() {
1765 },
1766 [&]() {
1768 .getMBPI();
1769 },
1770 [&]() {
1772 ->getMBFI();
1773 },
1774 [&]() {
1775 return &getAnalysisIfAvailable<
1777 ->getMBPI();
1778 });
1779}
1780
1782 : OptMode(RunningMode) {}
1783
1786 MFPropsModifier _(*this, MF);
1787 RegBankSelectImpl Impl(OptMode);
1788 bool Changed = Impl.runOnMachineFunction(
1789 MF, nullptr, &MFAM,
1790 [&]() { return &MFAM.getResult<MachineBlockFrequencyAnalysis>(MF); },
1791 [&]() { return &MFAM.getResult<MachineBranchProbabilityAnalysis>(MF); },
1792 [&]() { return MFAM.getCachedResult<MachineBlockFrequencyAnalysis>(MF); },
1793 [&]() {
1795 });
1799}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock & MBB
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define LLVM_ABI
Definition Compiler.h:215
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:343
#define DEBUG_TYPE
#define _
IRTranslator LLVM IR MI
Interface for Targets to specify which operations they can successfully select and how the others sho...
#define F(x, y, z)
Definition MD5.cpp:54
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:621
This file declares the MachineIRBuilder class.
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static constexpr unsigned ImpossibleRepairCost
Cost value representing an impossible or invalid repairing.
static cl::opt< RegBankSelectMode > RegBankSelectModeOption(cl::desc("Mode of the RegBankSelect pass"), cl::Hidden, cl::Optional, cl::values(clEnumValN(RegBankSelectMode::Fast, "regbankselect-fast", "Run the Fast mode (default mapping)"), clEnumValN(RegBankSelectMode::Greedy, "regbankselect-greedy", "Use the Greedy mode (best local mapping)")))
This file describes the interface of the MachineFunctionPass responsible for assigning the generic vi...
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Target-Independent Code Generator Pass Configuration Options pass.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
LLVM_ABI void print(raw_ostream &OS) const
constexpr unsigned getScalarSizeInBits() const
constexpr bool isValid() const
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
constexpr bool isVector() const
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
An RAII based helper class to modify MachineFunctionProperties when running pass.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isPredecessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a predecessor of this block.
LLVM_ABI iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
MachineInstrBundleIterator< MachineInstr > iterator
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
void insert(iterator MBBI, MachineBasicBlock *MBB)
MachineFunction & getMF()
Getter for the function we currently build.
void setMBB(MachineBasicBlock &MBB)
Set the insertion point to the end of MBB.
MachineInstrBuilder buildInstrNoInsert(unsigned Opcode)
Build but don't insert <empty> = Opcode <empty>.
void setMF(MachineFunction &MF)
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLT getType(Register Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register.
LLVM_ABI void setRegBank(Register Reg, const RegisterBank &RegBank)
Set the register bank to RegBank for Reg.
const MachineFunction & getMF() const
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
This pass implements the reg bank selector pass used in the GlobalISel pipeline.
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
RegBankSelectLegacy(RegBankSelectMode RunningMode=RegBankSelectMode::Fast)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
RegBankSelectPass(RegBankSelectMode RunningMode=RegBankSelectMode::Fast)
Helper class that represents how the value of an instruction may be mapped and what is the related co...
unsigned getNumOperands() const
Get the number of operands.
LLVM_ABI bool verify(const MachineInstr &MI) const
Verifiy that this mapping makes sense for MI.
bool isValid() const
Check whether this object is valid.
void applyMapping(MachineIRBuilder &Builder, const OperandsMapper &OpdMapper) const
Apply OpdMapper.getInstrMapping() to OpdMapper.getMI().
virtual const InstructionMapping & getInstrMapping(const MachineInstr &MI) const
Get the mapping of the different operands of MI on the register bank.
const RegisterBank & getRegBank(unsigned ID)
Get the register bank identified by ID.
TypeSize getSizeInBits(Register Reg, const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI) const
Get the size in bits of Reg.
InstructionMappings getInstrPossibleMappings(const MachineInstr &MI) const
Get the possible mapping for MI.
static const unsigned DefaultMappingID
Identifier used when the related instruction mapping instance is generated by target independent code...
SmallVector< const InstructionMapping *, 4 > InstructionMappings
Convenient type to represent the alternatives for mapping an instruction.
virtual unsigned copyCost(const RegisterBank &A, const RegisterBank &B, TypeSize Size) const
Get the cost of a copy from B to A, or put differently, get the cost of A = COPY B.
virtual unsigned getBreakDownCost(const ValueMapping &ValMapping, const RegisterBank *CurBank=nullptr) const
Get the cost of using ValMapping to decompose a register.
This class implements the register bank concept.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
typename SuperClass::const_iterator const_iterator
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Target-Independent Code Generator Pass Configuration Options.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const RegisterBankInfo * getRegBankInfo() const
If the information for the register banks is available, return it.
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
An efficient, type-erasing, non-owning reference to a callable.
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
#define UINT64_MAX
Definition DataTypes.h:77
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
iterator end() const
Definition BasicBlock.h:89
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
InstructionCost Cost
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2140
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
bool isPreISelGenericOptimizationHint(unsigned Opcode)
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool operator>(int64_t V1, const APSInt &V2)
Definition APSInt.h:361
LLVM_ABI cl::opt< bool > DisableGISelLegalityCheck
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void reportGISelFailure(MachineFunction &MF, MachineOptimizationRemarkEmitter &MORE, MachineOptimizationRemarkMissed &R)
Report an ISel error as a missed optimization remark to the LLVMContext's diagnostic stream.
Definition Utils.cpp:261
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI Printable printRegClassOrBank(Register Reg, const MachineRegisterInfo &RegInfo, const TargetRegisterInfo *TRI)
Create Printable object to print register classes or register banks on a raw_ostream.
const MachineInstr * machineFunctionIsIllegal(const MachineFunction &MF)
Checks that MIR is fully legal, returns an illegal instruction if it's not, nullptr otherwise.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
LLVM_ABI void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition Utils.cpp:1137
RegBankSelectMode
List of the modes supported by the RegBankSelect pass.
@ Greedy
Greedily minimize the cost of assigning register banks.
@ Fast
Assign the register banks as fast as possible (default).
bool isTargetSpecificOpcode(unsigned Opcode)
Check whether the given Opcode is a target-specific opcode.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define MORE()
Definition regcomp.c:246
const RegisterBank * RegBank
Register bank where the partial value lives.
unsigned Length
Length of this mapping in bits.
Helper struct that represents how a value is mapped through different register banks.
unsigned NumBreakDowns
Number of partial mapping to break down this value.
const PartialMapping * BreakDown
How the value is broken down between the different register banks.