1 //===- MachineVerifier.cpp - Machine Code Verifier ------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // Pass to verify generated machine code. The following is checked:
11 // Operand counts: All explicit operands must be present.
13 // Register classes: All physical and virtual register operands must be
14 // compatible with the register class required by the instruction descriptor.
16 // Register live intervals: Registers must be defined only once, and must be
17 // defined before use.
19 // The machine code verifier is enabled with the command-line option
20 // -verify-machineinstrs.
21 //===----------------------------------------------------------------------===//
23 #include "llvm/ADT/BitVector.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/DenseSet.h"
26 #include "llvm/ADT/DepthFirstIterator.h"
27 #include "llvm/ADT/PostOrderIterator.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SetOperations.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/ADT/Twine.h"
34 #include "llvm/Analysis/EHPersonalities.h"
35 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
36 #include "llvm/CodeGen/LiveInterval.h"
37 #include "llvm/CodeGen/LiveIntervalCalc.h"
38 #include "llvm/CodeGen/LiveIntervals.h"
39 #include "llvm/CodeGen/LiveStacks.h"
40 #include "llvm/CodeGen/LiveVariables.h"
41 #include "llvm/CodeGen/MachineBasicBlock.h"
42 #include "llvm/CodeGen/MachineFrameInfo.h"
43 #include "llvm/CodeGen/MachineFunction.h"
44 #include "llvm/CodeGen/MachineFunctionPass.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBundle.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/PseudoSourceValue.h"
51 #include "llvm/CodeGen/SlotIndexes.h"
52 #include "llvm/CodeGen/StackMaps.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetOpcodes.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/TargetSubtargetInfo.h"
57 #include "llvm/IR/BasicBlock.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/InlineAsm.h"
60 #include "llvm/IR/Instructions.h"
61 #include "llvm/InitializePasses.h"
62 #include "llvm/MC/LaneBitmask.h"
63 #include "llvm/MC/MCAsmInfo.h"
64 #include "llvm/MC/MCInstrDesc.h"
65 #include "llvm/MC/MCRegisterInfo.h"
66 #include "llvm/MC/MCTargetOptions.h"
67 #include "llvm/Pass.h"
68 #include "llvm/Support/Casting.h"
69 #include "llvm/Support/ErrorHandling.h"
70 #include "llvm/Support/LowLevelTypeImpl.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/raw_ostream.h"
73 #include "llvm/Target/TargetMachine.h"
86 struct MachineVerifier
{
87 MachineVerifier(Pass
*pass
, const char *b
) : PASS(pass
), Banner(b
) {}
89 unsigned verify(const MachineFunction
&MF
);
93 const MachineFunction
*MF
;
94 const TargetMachine
*TM
;
95 const TargetInstrInfo
*TII
;
96 const TargetRegisterInfo
*TRI
;
97 const MachineRegisterInfo
*MRI
;
101 // Avoid querying the MachineFunctionProperties for each operand.
102 bool isFunctionRegBankSelected
;
103 bool isFunctionSelected
;
105 using RegVector
= SmallVector
<Register
, 16>;
106 using RegMaskVector
= SmallVector
<const uint32_t *, 4>;
107 using RegSet
= DenseSet
<Register
>;
108 using RegMap
= DenseMap
<Register
, const MachineInstr
*>;
109 using BlockSet
= SmallPtrSet
<const MachineBasicBlock
*, 8>;
111 const MachineInstr
*FirstNonPHI
;
112 const MachineInstr
*FirstTerminator
;
113 BlockSet FunctionBlocks
;
115 BitVector regsReserved
;
117 RegVector regsDefined
, regsDead
, regsKilled
;
118 RegMaskVector regMasks
;
122 // Add Reg and any sub-registers to RV
123 void addRegWithSubRegs(RegVector
&RV
, Register Reg
) {
125 if (Reg
.isPhysical())
126 append_range(RV
, TRI
->subregs(Reg
.asMCReg()));
130 // Is this MBB reachable from the MF entry point?
131 bool reachable
= false;
133 // Vregs that must be live in because they are used without being
134 // defined. Map value is the user. vregsLiveIn doesn't include regs
135 // that only are used by PHI nodes.
138 // Regs killed in MBB. They may be defined again, and will then be in both
139 // regsKilled and regsLiveOut.
142 // Regs defined in MBB and live out. Note that vregs passing through may
143 // be live out without being mentioned here.
146 // Vregs that pass through MBB untouched. This set is disjoint from
147 // regsKilled and regsLiveOut.
150 // Vregs that must pass through MBB because they are needed by a successor
151 // block. This set is disjoint from regsLiveOut.
152 RegSet vregsRequired
;
154 // Set versions of block's predecessor and successor lists.
155 BlockSet Preds
, Succs
;
159 // Add register to vregsRequired if it belongs there. Return true if
161 bool addRequired(Register Reg
) {
162 if (!Reg
.isVirtual())
164 if (regsLiveOut
.count(Reg
))
166 return vregsRequired
.insert(Reg
).second
;
169 // Same for a full set.
170 bool addRequired(const RegSet
&RS
) {
171 bool Changed
= false;
172 for (Register Reg
: RS
)
173 Changed
|= addRequired(Reg
);
177 // Same for a full map.
178 bool addRequired(const RegMap
&RM
) {
179 bool Changed
= false;
180 for (const auto &I
: RM
)
181 Changed
|= addRequired(I
.first
);
185 // Live-out registers are either in regsLiveOut or vregsPassed.
186 bool isLiveOut(Register Reg
) const {
187 return regsLiveOut
.count(Reg
) || vregsPassed
.count(Reg
);
191 // Extra register info per MBB.
192 DenseMap
<const MachineBasicBlock
*, BBInfo
> MBBInfoMap
;
194 bool isReserved(Register Reg
) {
195 return Reg
.id() < regsReserved
.size() && regsReserved
.test(Reg
.id());
198 bool isAllocatable(Register Reg
) const {
199 return Reg
.id() < TRI
->getNumRegs() && TRI
->isInAllocatableClass(Reg
) &&
200 !regsReserved
.test(Reg
.id());
203 // Analysis information if available
204 LiveVariables
*LiveVars
;
205 LiveIntervals
*LiveInts
;
206 LiveStacks
*LiveStks
;
207 SlotIndexes
*Indexes
;
209 void visitMachineFunctionBefore();
210 void visitMachineBasicBlockBefore(const MachineBasicBlock
*MBB
);
211 void visitMachineBundleBefore(const MachineInstr
*MI
);
213 /// Verify that all of \p MI's virtual register operands are scalars.
214 /// \returns True if all virtual register operands are scalar. False
216 bool verifyAllRegOpsScalar(const MachineInstr
&MI
,
217 const MachineRegisterInfo
&MRI
);
218 bool verifyVectorElementMatch(LLT Ty0
, LLT Ty1
, const MachineInstr
*MI
);
219 void verifyPreISelGenericInstruction(const MachineInstr
*MI
);
220 void visitMachineInstrBefore(const MachineInstr
*MI
);
221 void visitMachineOperand(const MachineOperand
*MO
, unsigned MONum
);
222 void visitMachineBundleAfter(const MachineInstr
*MI
);
223 void visitMachineBasicBlockAfter(const MachineBasicBlock
*MBB
);
224 void visitMachineFunctionAfter();
226 void report(const char *msg
, const MachineFunction
*MF
);
227 void report(const char *msg
, const MachineBasicBlock
*MBB
);
228 void report(const char *msg
, const MachineInstr
*MI
);
229 void report(const char *msg
, const MachineOperand
*MO
, unsigned MONum
,
230 LLT MOVRegType
= LLT
{});
231 void report(const Twine
&Msg
, const MachineInstr
*MI
);
233 void report_context(const LiveInterval
&LI
) const;
234 void report_context(const LiveRange
&LR
, Register VRegUnit
,
235 LaneBitmask LaneMask
) const;
236 void report_context(const LiveRange::Segment
&S
) const;
237 void report_context(const VNInfo
&VNI
) const;
238 void report_context(SlotIndex Pos
) const;
239 void report_context(MCPhysReg PhysReg
) const;
240 void report_context_liverange(const LiveRange
&LR
) const;
241 void report_context_lanemask(LaneBitmask LaneMask
) const;
242 void report_context_vreg(Register VReg
) const;
243 void report_context_vreg_regunit(Register VRegOrUnit
) const;
245 void verifyInlineAsm(const MachineInstr
*MI
);
247 void checkLiveness(const MachineOperand
*MO
, unsigned MONum
);
248 void checkLivenessAtUse(const MachineOperand
*MO
, unsigned MONum
,
249 SlotIndex UseIdx
, const LiveRange
&LR
,
251 LaneBitmask LaneMask
= LaneBitmask::getNone());
252 void checkLivenessAtDef(const MachineOperand
*MO
, unsigned MONum
,
253 SlotIndex DefIdx
, const LiveRange
&LR
,
254 Register VRegOrUnit
, bool SubRangeCheck
= false,
255 LaneBitmask LaneMask
= LaneBitmask::getNone());
257 void markReachable(const MachineBasicBlock
*MBB
);
258 void calcRegsPassed();
259 void checkPHIOps(const MachineBasicBlock
&MBB
);
261 void calcRegsRequired();
262 void verifyLiveVariables();
263 void verifyLiveIntervals();
264 void verifyLiveInterval(const LiveInterval
&);
265 void verifyLiveRangeValue(const LiveRange
&, const VNInfo
*, Register
,
267 void verifyLiveRangeSegment(const LiveRange
&,
268 const LiveRange::const_iterator I
, Register
,
270 void verifyLiveRange(const LiveRange
&, Register
,
271 LaneBitmask LaneMask
= LaneBitmask::getNone());
273 void verifyStackFrame();
275 void verifySlotIndexes() const;
276 void verifyProperties(const MachineFunction
&MF
);
279 struct MachineVerifierPass
: public MachineFunctionPass
{
280 static char ID
; // Pass ID, replacement for typeid
282 const std::string Banner
;
284 MachineVerifierPass(std::string banner
= std::string())
285 : MachineFunctionPass(ID
), Banner(std::move(banner
)) {
286 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
289 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
290 AU
.setPreservesAll();
291 MachineFunctionPass::getAnalysisUsage(AU
);
294 bool runOnMachineFunction(MachineFunction
&MF
) override
{
295 unsigned FoundErrors
= MachineVerifier(this, Banner
.c_str()).verify(MF
);
297 report_fatal_error("Found "+Twine(FoundErrors
)+" machine code errors.");
302 } // end anonymous namespace
304 char MachineVerifierPass::ID
= 0;
306 INITIALIZE_PASS(MachineVerifierPass
, "machineverifier",
307 "Verify generated machine code", false, false)
309 FunctionPass
*llvm::createMachineVerifierPass(const std::string
&Banner
) {
310 return new MachineVerifierPass(Banner
);
313 void llvm::verifyMachineFunction(MachineFunctionAnalysisManager
*,
314 const std::string
&Banner
,
315 const MachineFunction
&MF
) {
316 // TODO: Use MFAM after porting below analyses.
317 // LiveVariables *LiveVars;
318 // LiveIntervals *LiveInts;
319 // LiveStacks *LiveStks;
320 // SlotIndexes *Indexes;
321 unsigned FoundErrors
= MachineVerifier(nullptr, Banner
.c_str()).verify(MF
);
323 report_fatal_error("Found " + Twine(FoundErrors
) + " machine code errors.");
326 bool MachineFunction::verify(Pass
*p
, const char *Banner
, bool AbortOnErrors
)
328 MachineFunction
&MF
= const_cast<MachineFunction
&>(*this);
329 unsigned FoundErrors
= MachineVerifier(p
, Banner
).verify(MF
);
330 if (AbortOnErrors
&& FoundErrors
)
331 report_fatal_error("Found "+Twine(FoundErrors
)+" machine code errors.");
332 return FoundErrors
== 0;
335 void MachineVerifier::verifySlotIndexes() const {
336 if (Indexes
== nullptr)
339 // Ensure the IdxMBB list is sorted by slot indexes.
341 for (SlotIndexes::MBBIndexIterator I
= Indexes
->MBBIndexBegin(),
342 E
= Indexes
->MBBIndexEnd(); I
!= E
; ++I
) {
343 assert(!Last
.isValid() || I
->first
> Last
);
348 void MachineVerifier::verifyProperties(const MachineFunction
&MF
) {
349 // If a pass has introduced virtual registers without clearing the
350 // NoVRegs property (or set it without allocating the vregs)
351 // then report an error.
352 if (MF
.getProperties().hasProperty(
353 MachineFunctionProperties::Property::NoVRegs
) &&
354 MRI
->getNumVirtRegs())
355 report("Function has NoVRegs property but there are VReg operands", &MF
);
358 unsigned MachineVerifier::verify(const MachineFunction
&MF
) {
362 TM
= &MF
.getTarget();
363 TII
= MF
.getSubtarget().getInstrInfo();
364 TRI
= MF
.getSubtarget().getRegisterInfo();
365 MRI
= &MF
.getRegInfo();
367 const bool isFunctionFailedISel
= MF
.getProperties().hasProperty(
368 MachineFunctionProperties::Property::FailedISel
);
370 // If we're mid-GlobalISel and we already triggered the fallback path then
371 // it's expected that the MIR is somewhat broken but that's ok since we'll
372 // reset it and clear the FailedISel attribute in ResetMachineFunctions.
373 if (isFunctionFailedISel
)
376 isFunctionRegBankSelected
= MF
.getProperties().hasProperty(
377 MachineFunctionProperties::Property::RegBankSelected
);
378 isFunctionSelected
= MF
.getProperties().hasProperty(
379 MachineFunctionProperties::Property::Selected
);
386 LiveInts
= PASS
->getAnalysisIfAvailable
<LiveIntervals
>();
387 // We don't want to verify LiveVariables if LiveIntervals is available.
389 LiveVars
= PASS
->getAnalysisIfAvailable
<LiveVariables
>();
390 LiveStks
= PASS
->getAnalysisIfAvailable
<LiveStacks
>();
391 Indexes
= PASS
->getAnalysisIfAvailable
<SlotIndexes
>();
396 verifyProperties(MF
);
398 visitMachineFunctionBefore();
399 for (const MachineBasicBlock
&MBB
: MF
) {
400 visitMachineBasicBlockBefore(&MBB
);
401 // Keep track of the current bundle header.
402 const MachineInstr
*CurBundle
= nullptr;
403 // Do we expect the next instruction to be part of the same bundle?
404 bool InBundle
= false;
406 for (const MachineInstr
&MI
: MBB
.instrs()) {
407 if (MI
.getParent() != &MBB
) {
408 report("Bad instruction parent pointer", &MBB
);
409 errs() << "Instruction: " << MI
;
413 // Check for consistent bundle flags.
414 if (InBundle
&& !MI
.isBundledWithPred())
415 report("Missing BundledPred flag, "
416 "BundledSucc was set on predecessor",
418 if (!InBundle
&& MI
.isBundledWithPred())
419 report("BundledPred flag is set, "
420 "but BundledSucc not set on predecessor",
423 // Is this a bundle header?
424 if (!MI
.isInsideBundle()) {
426 visitMachineBundleAfter(CurBundle
);
428 visitMachineBundleBefore(CurBundle
);
429 } else if (!CurBundle
)
430 report("No bundle header", &MI
);
431 visitMachineInstrBefore(&MI
);
432 for (unsigned I
= 0, E
= MI
.getNumOperands(); I
!= E
; ++I
) {
433 const MachineOperand
&Op
= MI
.getOperand(I
);
434 if (Op
.getParent() != &MI
) {
435 // Make sure to use correct addOperand / RemoveOperand / ChangeTo
436 // functions when replacing operands of a MachineInstr.
437 report("Instruction has operand with wrong parent set", &MI
);
440 visitMachineOperand(&Op
, I
);
443 // Was this the last bundled instruction?
444 InBundle
= MI
.isBundledWithSucc();
447 visitMachineBundleAfter(CurBundle
);
449 report("BundledSucc flag set on last instruction in block", &MBB
.back());
450 visitMachineBasicBlockAfter(&MBB
);
452 visitMachineFunctionAfter();
465 void MachineVerifier::report(const char *msg
, const MachineFunction
*MF
) {
468 if (!foundErrors
++) {
470 errs() << "# " << Banner
<< '\n';
471 if (LiveInts
!= nullptr)
472 LiveInts
->print(errs());
474 MF
->print(errs(), Indexes
);
476 errs() << "*** Bad machine code: " << msg
<< " ***\n"
477 << "- function: " << MF
->getName() << "\n";
480 void MachineVerifier::report(const char *msg
, const MachineBasicBlock
*MBB
) {
482 report(msg
, MBB
->getParent());
483 errs() << "- basic block: " << printMBBReference(*MBB
) << ' '
484 << MBB
->getName() << " (" << (const void *)MBB
<< ')';
486 errs() << " [" << Indexes
->getMBBStartIdx(MBB
)
487 << ';' << Indexes
->getMBBEndIdx(MBB
) << ')';
491 void MachineVerifier::report(const char *msg
, const MachineInstr
*MI
) {
493 report(msg
, MI
->getParent());
494 errs() << "- instruction: ";
495 if (Indexes
&& Indexes
->hasIndex(*MI
))
496 errs() << Indexes
->getInstructionIndex(*MI
) << '\t';
497 MI
->print(errs(), /*IsStandalone=*/true);
500 void MachineVerifier::report(const char *msg
, const MachineOperand
*MO
,
501 unsigned MONum
, LLT MOVRegType
) {
503 report(msg
, MO
->getParent());
504 errs() << "- operand " << MONum
<< ": ";
505 MO
->print(errs(), MOVRegType
, TRI
);
509 void MachineVerifier::report(const Twine
&Msg
, const MachineInstr
*MI
) {
510 report(Msg
.str().c_str(), MI
);
513 void MachineVerifier::report_context(SlotIndex Pos
) const {
514 errs() << "- at: " << Pos
<< '\n';
517 void MachineVerifier::report_context(const LiveInterval
&LI
) const {
518 errs() << "- interval: " << LI
<< '\n';
521 void MachineVerifier::report_context(const LiveRange
&LR
, Register VRegUnit
,
522 LaneBitmask LaneMask
) const {
523 report_context_liverange(LR
);
524 report_context_vreg_regunit(VRegUnit
);
526 report_context_lanemask(LaneMask
);
529 void MachineVerifier::report_context(const LiveRange::Segment
&S
) const {
530 errs() << "- segment: " << S
<< '\n';
533 void MachineVerifier::report_context(const VNInfo
&VNI
) const {
534 errs() << "- ValNo: " << VNI
.id
<< " (def " << VNI
.def
<< ")\n";
537 void MachineVerifier::report_context_liverange(const LiveRange
&LR
) const {
538 errs() << "- liverange: " << LR
<< '\n';
541 void MachineVerifier::report_context(MCPhysReg PReg
) const {
542 errs() << "- p. register: " << printReg(PReg
, TRI
) << '\n';
545 void MachineVerifier::report_context_vreg(Register VReg
) const {
546 errs() << "- v. register: " << printReg(VReg
, TRI
) << '\n';
549 void MachineVerifier::report_context_vreg_regunit(Register VRegOrUnit
) const {
550 if (Register::isVirtualRegister(VRegOrUnit
)) {
551 report_context_vreg(VRegOrUnit
);
553 errs() << "- regunit: " << printRegUnit(VRegOrUnit
, TRI
) << '\n';
557 void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask
) const {
558 errs() << "- lanemask: " << PrintLaneMask(LaneMask
) << '\n';
561 void MachineVerifier::markReachable(const MachineBasicBlock
*MBB
) {
562 BBInfo
&MInfo
= MBBInfoMap
[MBB
];
563 if (!MInfo
.reachable
) {
564 MInfo
.reachable
= true;
565 for (const MachineBasicBlock
*Succ
: MBB
->successors())
570 void MachineVerifier::visitMachineFunctionBefore() {
571 lastIndex
= SlotIndex();
572 regsReserved
= MRI
->reservedRegsFrozen() ? MRI
->getReservedRegs()
573 : TRI
->getReservedRegs(*MF
);
576 markReachable(&MF
->front());
578 // Build a set of the basic blocks in the function.
579 FunctionBlocks
.clear();
580 for (const auto &MBB
: *MF
) {
581 FunctionBlocks
.insert(&MBB
);
582 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
584 MInfo
.Preds
.insert(MBB
.pred_begin(), MBB
.pred_end());
585 if (MInfo
.Preds
.size() != MBB
.pred_size())
586 report("MBB has duplicate entries in its predecessor list.", &MBB
);
588 MInfo
.Succs
.insert(MBB
.succ_begin(), MBB
.succ_end());
589 if (MInfo
.Succs
.size() != MBB
.succ_size())
590 report("MBB has duplicate entries in its successor list.", &MBB
);
593 // Check that the register use lists are sane.
594 MRI
->verifyUseLists();
601 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock
*MBB
) {
602 FirstTerminator
= nullptr;
603 FirstNonPHI
= nullptr;
605 if (!MF
->getProperties().hasProperty(
606 MachineFunctionProperties::Property::NoPHIs
) && MRI
->tracksLiveness()) {
607 // If this block has allocatable physical registers live-in, check that
608 // it is an entry block or landing pad.
609 for (const auto &LI
: MBB
->liveins()) {
610 if (isAllocatable(LI
.PhysReg
) && !MBB
->isEHPad() &&
611 MBB
->getIterator() != MBB
->getParent()->begin()) {
612 report("MBB has allocatable live-in, but isn't entry or landing-pad.", MBB
);
613 report_context(LI
.PhysReg
);
618 // Count the number of landing pad successors.
619 SmallPtrSet
<const MachineBasicBlock
*, 4> LandingPadSuccs
;
620 for (const auto *succ
: MBB
->successors()) {
622 LandingPadSuccs
.insert(succ
);
623 if (!FunctionBlocks
.count(succ
))
624 report("MBB has successor that isn't part of the function.", MBB
);
625 if (!MBBInfoMap
[succ
].Preds
.count(MBB
)) {
626 report("Inconsistent CFG", MBB
);
627 errs() << "MBB is not in the predecessor list of the successor "
628 << printMBBReference(*succ
) << ".\n";
632 // Check the predecessor list.
633 for (const MachineBasicBlock
*Pred
: MBB
->predecessors()) {
634 if (!FunctionBlocks
.count(Pred
))
635 report("MBB has predecessor that isn't part of the function.", MBB
);
636 if (!MBBInfoMap
[Pred
].Succs
.count(MBB
)) {
637 report("Inconsistent CFG", MBB
);
638 errs() << "MBB is not in the successor list of the predecessor "
639 << printMBBReference(*Pred
) << ".\n";
643 const MCAsmInfo
*AsmInfo
= TM
->getMCAsmInfo();
644 const BasicBlock
*BB
= MBB
->getBasicBlock();
645 const Function
&F
= MF
->getFunction();
646 if (LandingPadSuccs
.size() > 1 &&
648 AsmInfo
->getExceptionHandlingType() == ExceptionHandling::SjLj
&&
649 BB
&& isa
<SwitchInst
>(BB
->getTerminator())) &&
650 !isScopedEHPersonality(classifyEHPersonality(F
.getPersonalityFn())))
651 report("MBB has more than one landing pad successor", MBB
);
653 // Call analyzeBranch. If it succeeds, there several more conditions to check.
654 MachineBasicBlock
*TBB
= nullptr, *FBB
= nullptr;
655 SmallVector
<MachineOperand
, 4> Cond
;
656 if (!TII
->analyzeBranch(*const_cast<MachineBasicBlock
*>(MBB
), TBB
, FBB
,
658 // Ok, analyzeBranch thinks it knows what's going on with this block. Let's
659 // check whether its answers match up with reality.
661 // Block falls through to its successor.
662 if (!MBB
->empty() && MBB
->back().isBarrier() &&
663 !TII
->isPredicated(MBB
->back())) {
664 report("MBB exits via unconditional fall-through but ends with a "
665 "barrier instruction!", MBB
);
668 report("MBB exits via unconditional fall-through but has a condition!",
671 } else if (TBB
&& !FBB
&& Cond
.empty()) {
672 // Block unconditionally branches somewhere.
674 report("MBB exits via unconditional branch but doesn't contain "
675 "any instructions!", MBB
);
676 } else if (!MBB
->back().isBarrier()) {
677 report("MBB exits via unconditional branch but doesn't end with a "
678 "barrier instruction!", MBB
);
679 } else if (!MBB
->back().isTerminator()) {
680 report("MBB exits via unconditional branch but the branch isn't a "
681 "terminator instruction!", MBB
);
683 } else if (TBB
&& !FBB
&& !Cond
.empty()) {
684 // Block conditionally branches somewhere, otherwise falls through.
686 report("MBB exits via conditional branch/fall-through but doesn't "
687 "contain any instructions!", MBB
);
688 } else if (MBB
->back().isBarrier()) {
689 report("MBB exits via conditional branch/fall-through but ends with a "
690 "barrier instruction!", MBB
);
691 } else if (!MBB
->back().isTerminator()) {
692 report("MBB exits via conditional branch/fall-through but the branch "
693 "isn't a terminator instruction!", MBB
);
695 } else if (TBB
&& FBB
) {
696 // Block conditionally branches somewhere, otherwise branches
699 report("MBB exits via conditional branch/branch but doesn't "
700 "contain any instructions!", MBB
);
701 } else if (!MBB
->back().isBarrier()) {
702 report("MBB exits via conditional branch/branch but doesn't end with a "
703 "barrier instruction!", MBB
);
704 } else if (!MBB
->back().isTerminator()) {
705 report("MBB exits via conditional branch/branch but the branch "
706 "isn't a terminator instruction!", MBB
);
709 report("MBB exits via conditional branch/branch but there's no "
713 report("analyzeBranch returned invalid data!", MBB
);
716 // Now check that the successors match up with the answers reported by
718 if (TBB
&& !MBB
->isSuccessor(TBB
))
719 report("MBB exits via jump or conditional branch, but its target isn't a "
722 if (FBB
&& !MBB
->isSuccessor(FBB
))
723 report("MBB exits via conditional branch, but its target isn't a CFG "
727 // There might be a fallthrough to the next block if there's either no
728 // unconditional true branch, or if there's a condition, and one of the
729 // branches is missing.
730 bool Fallthrough
= !TBB
|| (!Cond
.empty() && !FBB
);
732 // A conditional fallthrough must be an actual CFG successor, not
733 // unreachable. (Conversely, an unconditional fallthrough might not really
734 // be a successor, because the block might end in unreachable.)
735 if (!Cond
.empty() && !FBB
) {
736 MachineFunction::const_iterator MBBI
= std::next(MBB
->getIterator());
737 if (MBBI
== MF
->end()) {
738 report("MBB conditionally falls through out of function!", MBB
);
739 } else if (!MBB
->isSuccessor(&*MBBI
))
740 report("MBB exits via conditional branch/fall-through but the CFG "
741 "successors don't match the actual successors!",
745 // Verify that there aren't any extra un-accounted-for successors.
746 for (const MachineBasicBlock
*SuccMBB
: MBB
->successors()) {
747 // If this successor is one of the branch targets, it's okay.
748 if (SuccMBB
== TBB
|| SuccMBB
== FBB
)
750 // If we might have a fallthrough, and the successor is the fallthrough
751 // block, that's also ok.
752 if (Fallthrough
&& SuccMBB
== MBB
->getNextNode())
754 // Also accept successors which are for exception-handling or might be
755 // inlineasm_br targets.
756 if (SuccMBB
->isEHPad() || SuccMBB
->isInlineAsmBrIndirectTarget())
758 report("MBB has unexpected successors which are not branch targets, "
759 "fallthrough, EHPads, or inlineasm_br targets.",
765 if (MRI
->tracksLiveness()) {
766 for (const auto &LI
: MBB
->liveins()) {
767 if (!Register::isPhysicalRegister(LI
.PhysReg
)) {
768 report("MBB live-in list contains non-physical register", MBB
);
771 for (const MCPhysReg
&SubReg
: TRI
->subregs_inclusive(LI
.PhysReg
))
772 regsLive
.insert(SubReg
);
776 const MachineFrameInfo
&MFI
= MF
->getFrameInfo();
777 BitVector PR
= MFI
.getPristineRegs(*MF
);
778 for (unsigned I
: PR
.set_bits()) {
779 for (const MCPhysReg
&SubReg
: TRI
->subregs_inclusive(I
))
780 regsLive
.insert(SubReg
);
787 lastIndex
= Indexes
->getMBBStartIdx(MBB
);
790 // This function gets called for all bundle headers, including normal
791 // stand-alone unbundled instructions.
792 void MachineVerifier::visitMachineBundleBefore(const MachineInstr
*MI
) {
793 if (Indexes
&& Indexes
->hasIndex(*MI
)) {
794 SlotIndex idx
= Indexes
->getInstructionIndex(*MI
);
795 if (!(idx
> lastIndex
)) {
796 report("Instruction index out of order", MI
);
797 errs() << "Last instruction was at " << lastIndex
<< '\n';
802 // Ensure non-terminators don't follow terminators.
803 if (MI
->isTerminator()) {
804 if (!FirstTerminator
)
805 FirstTerminator
= MI
;
806 } else if (FirstTerminator
) {
807 report("Non-terminator instruction after the first terminator", MI
);
808 errs() << "First terminator was:\t" << *FirstTerminator
;
812 // The operands on an INLINEASM instruction must follow a template.
813 // Verify that the flag operands make sense.
814 void MachineVerifier::verifyInlineAsm(const MachineInstr
*MI
) {
815 // The first two operands on INLINEASM are the asm string and global flags.
816 if (MI
->getNumOperands() < 2) {
817 report("Too few operands on inline asm", MI
);
820 if (!MI
->getOperand(0).isSymbol())
821 report("Asm string must be an external symbol", MI
);
822 if (!MI
->getOperand(1).isImm())
823 report("Asm flags must be an immediate", MI
);
824 // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
825 // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16,
826 // and Extra_IsConvergent = 32.
827 if (!isUInt
<6>(MI
->getOperand(1).getImm()))
828 report("Unknown asm flags", &MI
->getOperand(1), 1);
830 static_assert(InlineAsm::MIOp_FirstOperand
== 2, "Asm format changed");
832 unsigned OpNo
= InlineAsm::MIOp_FirstOperand
;
834 for (unsigned e
= MI
->getNumOperands(); OpNo
< e
; OpNo
+= NumOps
) {
835 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
836 // There may be implicit ops after the fixed operands.
839 NumOps
= 1 + InlineAsm::getNumOperandRegisters(MO
.getImm());
842 if (OpNo
> MI
->getNumOperands())
843 report("Missing operands in last group", MI
);
845 // An optional MDNode follows the groups.
846 if (OpNo
< MI
->getNumOperands() && MI
->getOperand(OpNo
).isMetadata())
849 // All trailing operands must be implicit registers.
850 for (unsigned e
= MI
->getNumOperands(); OpNo
< e
; ++OpNo
) {
851 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
852 if (!MO
.isReg() || !MO
.isImplicit())
853 report("Expected implicit register after groups", &MO
, OpNo
);
857 bool MachineVerifier::verifyAllRegOpsScalar(const MachineInstr
&MI
,
858 const MachineRegisterInfo
&MRI
) {
859 if (none_of(MI
.explicit_operands(), [&MRI
](const MachineOperand
&Op
) {
862 const auto Reg
= Op
.getReg();
863 if (Reg
.isPhysical())
865 return !MRI
.getType(Reg
).isScalar();
868 report("All register operands must have scalar types", &MI
);
872 /// Check that types are consistent when two operands need to have the same
873 /// number of vector elements.
874 /// \return true if the types are valid.
875 bool MachineVerifier::verifyVectorElementMatch(LLT Ty0
, LLT Ty1
,
876 const MachineInstr
*MI
) {
877 if (Ty0
.isVector() != Ty1
.isVector()) {
878 report("operand types must be all-vector or all-scalar", MI
);
879 // Generally we try to report as many issues as possible at once, but in
880 // this case it's not clear what should we be comparing the size of the
881 // scalar with: the size of the whole vector or its lane. Instead of
882 // making an arbitrary choice and emitting not so helpful message, let's
883 // avoid the extra noise and stop here.
887 if (Ty0
.isVector() && Ty0
.getNumElements() != Ty1
.getNumElements()) {
888 report("operand types must preserve number of vector elements", MI
);
895 void MachineVerifier::verifyPreISelGenericInstruction(const MachineInstr
*MI
) {
896 if (isFunctionSelected
)
897 report("Unexpected generic instruction in a Selected function", MI
);
899 const MCInstrDesc
&MCID
= MI
->getDesc();
900 unsigned NumOps
= MI
->getNumOperands();
902 // Branches must reference a basic block if they are not indirect
903 if (MI
->isBranch() && !MI
->isIndirectBranch()) {
905 for (const MachineOperand
&Op
: MI
->operands()) {
913 report("Branch instruction is missing a basic block operand or "
914 "isIndirectBranch property",
920 SmallVector
<LLT
, 4> Types
;
921 for (unsigned I
= 0, E
= std::min(MCID
.getNumOperands(), NumOps
);
923 if (!MCID
.OpInfo
[I
].isGenericType())
925 // Generic instructions specify type equality constraints between some of
926 // their operands. Make sure these are consistent.
927 size_t TypeIdx
= MCID
.OpInfo
[I
].getGenericTypeIndex();
928 Types
.resize(std::max(TypeIdx
+ 1, Types
.size()));
930 const MachineOperand
*MO
= &MI
->getOperand(I
);
932 report("generic instruction must use register operands", MI
);
936 LLT OpTy
= MRI
->getType(MO
->getReg());
937 // Don't report a type mismatch if there is no actual mismatch, only a
938 // type missing, to reduce noise:
939 if (OpTy
.isValid()) {
940 // Only the first valid type for a type index will be printed: don't
941 // overwrite it later so it's always clear which type was expected:
942 if (!Types
[TypeIdx
].isValid())
943 Types
[TypeIdx
] = OpTy
;
944 else if (Types
[TypeIdx
] != OpTy
)
945 report("Type mismatch in generic instruction", MO
, I
, OpTy
);
947 // Generic instructions must have types attached to their operands.
948 report("Generic instruction is missing a virtual register type", MO
, I
);
952 // Generic opcodes must not have physical register operands.
953 for (unsigned I
= 0; I
< MI
->getNumOperands(); ++I
) {
954 const MachineOperand
*MO
= &MI
->getOperand(I
);
955 if (MO
->isReg() && Register::isPhysicalRegister(MO
->getReg()))
956 report("Generic instruction cannot have physical register", MO
, I
);
959 // Avoid out of bounds in checks below. This was already reported earlier.
960 if (MI
->getNumOperands() < MCID
.getNumOperands())
964 if (!TII
->verifyInstruction(*MI
, ErrorInfo
))
965 report(ErrorInfo
.data(), MI
);
967 // Verify properties of various specific instruction types
968 unsigned Opc
= MI
->getOpcode();
970 case TargetOpcode::G_ISNAN
: {
971 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
972 LLT SrcTy
= MRI
->getType(MI
->getOperand(1).getReg());
973 LLT S1
= DstTy
.isVector() ? DstTy
.getElementType() : DstTy
;
974 if (S1
!= LLT::scalar(1)) {
975 report("Destination must be a 1-bit scalar or vector of 1-bit elements",
980 // Disallow pointers.
981 LLT SrcOrElt
= SrcTy
.isVector() ? SrcTy
.getElementType() : SrcTy
;
982 if (!SrcOrElt
.isScalar()) {
983 report("Source must be a scalar or vector of scalars", MI
);
986 verifyVectorElementMatch(DstTy
, SrcTy
, MI
);
989 case TargetOpcode::G_ASSERT_SEXT
:
990 case TargetOpcode::G_ASSERT_ZEXT
: {
991 std::string OpcName
=
992 Opc
== TargetOpcode::G_ASSERT_ZEXT
? "G_ASSERT_ZEXT" : "G_ASSERT_SEXT";
993 if (!MI
->getOperand(2).isImm()) {
994 report(Twine(OpcName
, " expects an immediate operand #2"), MI
);
998 Register Dst
= MI
->getOperand(0).getReg();
999 Register Src
= MI
->getOperand(1).getReg();
1000 LLT SrcTy
= MRI
->getType(Src
);
1001 int64_t Imm
= MI
->getOperand(2).getImm();
1003 report(Twine(OpcName
, " size must be >= 1"), MI
);
1007 if (Imm
>= SrcTy
.getScalarSizeInBits()) {
1008 report(Twine(OpcName
, " size must be less than source bit width"), MI
);
1012 if (MRI
->getRegBankOrNull(Src
) != MRI
->getRegBankOrNull(Dst
)) {
1014 Twine(OpcName
, " source and destination register banks must match"),
1019 if (MRI
->getRegClassOrNull(Src
) != MRI
->getRegClassOrNull(Dst
))
1021 Twine(OpcName
, " source and destination register classes must match"),
1027 case TargetOpcode::G_CONSTANT
:
1028 case TargetOpcode::G_FCONSTANT
: {
1029 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1030 if (DstTy
.isVector())
1031 report("Instruction cannot use a vector result type", MI
);
1033 if (MI
->getOpcode() == TargetOpcode::G_CONSTANT
) {
1034 if (!MI
->getOperand(1).isCImm()) {
1035 report("G_CONSTANT operand must be cimm", MI
);
1039 const ConstantInt
*CI
= MI
->getOperand(1).getCImm();
1040 if (CI
->getBitWidth() != DstTy
.getSizeInBits())
1041 report("inconsistent constant size", MI
);
1043 if (!MI
->getOperand(1).isFPImm()) {
1044 report("G_FCONSTANT operand must be fpimm", MI
);
1047 const ConstantFP
*CF
= MI
->getOperand(1).getFPImm();
1049 if (APFloat::getSizeInBits(CF
->getValueAPF().getSemantics()) !=
1050 DstTy
.getSizeInBits()) {
1051 report("inconsistent constant size", MI
);
1057 case TargetOpcode::G_LOAD
:
1058 case TargetOpcode::G_STORE
:
1059 case TargetOpcode::G_ZEXTLOAD
:
1060 case TargetOpcode::G_SEXTLOAD
: {
1061 LLT ValTy
= MRI
->getType(MI
->getOperand(0).getReg());
1062 LLT PtrTy
= MRI
->getType(MI
->getOperand(1).getReg());
1063 if (!PtrTy
.isPointer())
1064 report("Generic memory instruction must access a pointer", MI
);
1066 // Generic loads and stores must have a single MachineMemOperand
1067 // describing that access.
1068 if (!MI
->hasOneMemOperand()) {
1069 report("Generic instruction accessing memory must have one mem operand",
1072 const MachineMemOperand
&MMO
= **MI
->memoperands_begin();
1073 if (MI
->getOpcode() == TargetOpcode::G_ZEXTLOAD
||
1074 MI
->getOpcode() == TargetOpcode::G_SEXTLOAD
) {
1075 if (MMO
.getSizeInBits() >= ValTy
.getSizeInBits())
1076 report("Generic extload must have a narrower memory type", MI
);
1077 } else if (MI
->getOpcode() == TargetOpcode::G_LOAD
) {
1078 if (MMO
.getSize() > ValTy
.getSizeInBytes())
1079 report("load memory size cannot exceed result size", MI
);
1080 } else if (MI
->getOpcode() == TargetOpcode::G_STORE
) {
1081 if (ValTy
.getSizeInBytes() < MMO
.getSize())
1082 report("store memory size cannot exceed value size", MI
);
1088 case TargetOpcode::G_PHI
: {
1089 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1090 if (!DstTy
.isValid() || !all_of(drop_begin(MI
->operands()),
1091 [this, &DstTy
](const MachineOperand
&MO
) {
1094 LLT Ty
= MRI
->getType(MO
.getReg());
1095 if (!Ty
.isValid() || (Ty
!= DstTy
))
1099 report("Generic Instruction G_PHI has operands with incompatible/missing "
1104 case TargetOpcode::G_BITCAST
: {
1105 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1106 LLT SrcTy
= MRI
->getType(MI
->getOperand(1).getReg());
1107 if (!DstTy
.isValid() || !SrcTy
.isValid())
1110 if (SrcTy
.isPointer() != DstTy
.isPointer())
1111 report("bitcast cannot convert between pointers and other types", MI
);
1113 if (SrcTy
.getSizeInBits() != DstTy
.getSizeInBits())
1114 report("bitcast sizes must match", MI
);
1117 report("bitcast must change the type", MI
);
1121 case TargetOpcode::G_INTTOPTR
:
1122 case TargetOpcode::G_PTRTOINT
:
1123 case TargetOpcode::G_ADDRSPACE_CAST
: {
1124 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1125 LLT SrcTy
= MRI
->getType(MI
->getOperand(1).getReg());
1126 if (!DstTy
.isValid() || !SrcTy
.isValid())
1129 verifyVectorElementMatch(DstTy
, SrcTy
, MI
);
1131 DstTy
= DstTy
.getScalarType();
1132 SrcTy
= SrcTy
.getScalarType();
1134 if (MI
->getOpcode() == TargetOpcode::G_INTTOPTR
) {
1135 if (!DstTy
.isPointer())
1136 report("inttoptr result type must be a pointer", MI
);
1137 if (SrcTy
.isPointer())
1138 report("inttoptr source type must not be a pointer", MI
);
1139 } else if (MI
->getOpcode() == TargetOpcode::G_PTRTOINT
) {
1140 if (!SrcTy
.isPointer())
1141 report("ptrtoint source type must be a pointer", MI
);
1142 if (DstTy
.isPointer())
1143 report("ptrtoint result type must not be a pointer", MI
);
1145 assert(MI
->getOpcode() == TargetOpcode::G_ADDRSPACE_CAST
);
1146 if (!SrcTy
.isPointer() || !DstTy
.isPointer())
1147 report("addrspacecast types must be pointers", MI
);
1149 if (SrcTy
.getAddressSpace() == DstTy
.getAddressSpace())
1150 report("addrspacecast must convert different address spaces", MI
);
1156 case TargetOpcode::G_PTR_ADD
: {
1157 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1158 LLT PtrTy
= MRI
->getType(MI
->getOperand(1).getReg());
1159 LLT OffsetTy
= MRI
->getType(MI
->getOperand(2).getReg());
1160 if (!DstTy
.isValid() || !PtrTy
.isValid() || !OffsetTy
.isValid())
1163 if (!PtrTy
.getScalarType().isPointer())
1164 report("gep first operand must be a pointer", MI
);
1166 if (OffsetTy
.getScalarType().isPointer())
1167 report("gep offset operand must not be a pointer", MI
);
1169 // TODO: Is the offset allowed to be a scalar with a vector?
1172 case TargetOpcode::G_PTRMASK
: {
1173 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1174 LLT SrcTy
= MRI
->getType(MI
->getOperand(1).getReg());
1175 LLT MaskTy
= MRI
->getType(MI
->getOperand(2).getReg());
1176 if (!DstTy
.isValid() || !SrcTy
.isValid() || !MaskTy
.isValid())
1179 if (!DstTy
.getScalarType().isPointer())
1180 report("ptrmask result type must be a pointer", MI
);
1182 if (!MaskTy
.getScalarType().isScalar())
1183 report("ptrmask mask type must be an integer", MI
);
1185 verifyVectorElementMatch(DstTy
, MaskTy
, MI
);
1188 case TargetOpcode::G_SEXT
:
1189 case TargetOpcode::G_ZEXT
:
1190 case TargetOpcode::G_ANYEXT
:
1191 case TargetOpcode::G_TRUNC
:
1192 case TargetOpcode::G_FPEXT
:
1193 case TargetOpcode::G_FPTRUNC
: {
1194 // Number of operands and presense of types is already checked (and
1195 // reported in case of any issues), so no need to report them again. As
1196 // we're trying to report as many issues as possible at once, however, the
1197 // instructions aren't guaranteed to have the right number of operands or
1198 // types attached to them at this point
1199 assert(MCID
.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}");
1200 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1201 LLT SrcTy
= MRI
->getType(MI
->getOperand(1).getReg());
1202 if (!DstTy
.isValid() || !SrcTy
.isValid())
1205 LLT DstElTy
= DstTy
.getScalarType();
1206 LLT SrcElTy
= SrcTy
.getScalarType();
1207 if (DstElTy
.isPointer() || SrcElTy
.isPointer())
1208 report("Generic extend/truncate can not operate on pointers", MI
);
1210 verifyVectorElementMatch(DstTy
, SrcTy
, MI
);
1212 unsigned DstSize
= DstElTy
.getSizeInBits();
1213 unsigned SrcSize
= SrcElTy
.getSizeInBits();
1214 switch (MI
->getOpcode()) {
1216 if (DstSize
<= SrcSize
)
1217 report("Generic extend has destination type no larger than source", MI
);
1219 case TargetOpcode::G_TRUNC
:
1220 case TargetOpcode::G_FPTRUNC
:
1221 if (DstSize
>= SrcSize
)
1222 report("Generic truncate has destination type no smaller than source",
1228 case TargetOpcode::G_SELECT
: {
1229 LLT SelTy
= MRI
->getType(MI
->getOperand(0).getReg());
1230 LLT CondTy
= MRI
->getType(MI
->getOperand(1).getReg());
1231 if (!SelTy
.isValid() || !CondTy
.isValid())
1234 // Scalar condition select on a vector is valid.
1235 if (CondTy
.isVector())
1236 verifyVectorElementMatch(SelTy
, CondTy
, MI
);
1239 case TargetOpcode::G_MERGE_VALUES
: {
1240 // G_MERGE_VALUES should only be used to merge scalars into a larger scalar,
1241 // e.g. s2N = MERGE sN, sN
1242 // Merging multiple scalars into a vector is not allowed, should use
1243 // G_BUILD_VECTOR for that.
1244 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1245 LLT SrcTy
= MRI
->getType(MI
->getOperand(1).getReg());
1246 if (DstTy
.isVector() || SrcTy
.isVector())
1247 report("G_MERGE_VALUES cannot operate on vectors", MI
);
1249 const unsigned NumOps
= MI
->getNumOperands();
1250 if (DstTy
.getSizeInBits() != SrcTy
.getSizeInBits() * (NumOps
- 1))
1251 report("G_MERGE_VALUES result size is inconsistent", MI
);
1253 for (unsigned I
= 2; I
!= NumOps
; ++I
) {
1254 if (MRI
->getType(MI
->getOperand(I
).getReg()) != SrcTy
)
1255 report("G_MERGE_VALUES source types do not match", MI
);
1260 case TargetOpcode::G_UNMERGE_VALUES
: {
1261 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1262 LLT SrcTy
= MRI
->getType(MI
->getOperand(MI
->getNumOperands()-1).getReg());
1263 // For now G_UNMERGE can split vectors.
1264 for (unsigned i
= 0; i
< MI
->getNumOperands()-1; ++i
) {
1265 if (MRI
->getType(MI
->getOperand(i
).getReg()) != DstTy
)
1266 report("G_UNMERGE_VALUES destination types do not match", MI
);
1268 if (SrcTy
.getSizeInBits() !=
1269 (DstTy
.getSizeInBits() * (MI
->getNumOperands() - 1))) {
1270 report("G_UNMERGE_VALUES source operand does not cover dest operands",
1275 case TargetOpcode::G_BUILD_VECTOR
: {
1276 // Source types must be scalars, dest type a vector. Total size of scalars
1277 // must match the dest vector size.
1278 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1279 LLT SrcEltTy
= MRI
->getType(MI
->getOperand(1).getReg());
1280 if (!DstTy
.isVector() || SrcEltTy
.isVector()) {
1281 report("G_BUILD_VECTOR must produce a vector from scalar operands", MI
);
1285 if (DstTy
.getElementType() != SrcEltTy
)
1286 report("G_BUILD_VECTOR result element type must match source type", MI
);
1288 if (DstTy
.getNumElements() != MI
->getNumOperands() - 1)
1289 report("G_BUILD_VECTOR must have an operand for each elemement", MI
);
1291 for (unsigned i
= 2; i
< MI
->getNumOperands(); ++i
) {
1292 if (MRI
->getType(MI
->getOperand(1).getReg()) !=
1293 MRI
->getType(MI
->getOperand(i
).getReg()))
1294 report("G_BUILD_VECTOR source operand types are not homogeneous", MI
);
1299 case TargetOpcode::G_BUILD_VECTOR_TRUNC
: {
1300 // Source types must be scalars, dest type a vector. Scalar types must be
1301 // larger than the dest vector elt type, as this is a truncating operation.
1302 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1303 LLT SrcEltTy
= MRI
->getType(MI
->getOperand(1).getReg());
1304 if (!DstTy
.isVector() || SrcEltTy
.isVector())
1305 report("G_BUILD_VECTOR_TRUNC must produce a vector from scalar operands",
1307 for (unsigned i
= 2; i
< MI
->getNumOperands(); ++i
) {
1308 if (MRI
->getType(MI
->getOperand(1).getReg()) !=
1309 MRI
->getType(MI
->getOperand(i
).getReg()))
1310 report("G_BUILD_VECTOR_TRUNC source operand types are not homogeneous",
1313 if (SrcEltTy
.getSizeInBits() <= DstTy
.getElementType().getSizeInBits())
1314 report("G_BUILD_VECTOR_TRUNC source operand types are not larger than "
1319 case TargetOpcode::G_CONCAT_VECTORS
: {
1320 // Source types should be vectors, and total size should match the dest
1322 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1323 LLT SrcTy
= MRI
->getType(MI
->getOperand(1).getReg());
1324 if (!DstTy
.isVector() || !SrcTy
.isVector())
1325 report("G_CONCAT_VECTOR requires vector source and destination operands",
1328 if (MI
->getNumOperands() < 3)
1329 report("G_CONCAT_VECTOR requires at least 2 source operands", MI
);
1331 for (unsigned i
= 2; i
< MI
->getNumOperands(); ++i
) {
1332 if (MRI
->getType(MI
->getOperand(1).getReg()) !=
1333 MRI
->getType(MI
->getOperand(i
).getReg()))
1334 report("G_CONCAT_VECTOR source operand types are not homogeneous", MI
);
1336 if (DstTy
.getNumElements() !=
1337 SrcTy
.getNumElements() * (MI
->getNumOperands() - 1))
1338 report("G_CONCAT_VECTOR num dest and source elements should match", MI
);
1341 case TargetOpcode::G_ICMP
:
1342 case TargetOpcode::G_FCMP
: {
1343 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1344 LLT SrcTy
= MRI
->getType(MI
->getOperand(2).getReg());
1346 if ((DstTy
.isVector() != SrcTy
.isVector()) ||
1347 (DstTy
.isVector() && DstTy
.getNumElements() != SrcTy
.getNumElements()))
1348 report("Generic vector icmp/fcmp must preserve number of lanes", MI
);
1352 case TargetOpcode::G_EXTRACT
: {
1353 const MachineOperand
&SrcOp
= MI
->getOperand(1);
1354 if (!SrcOp
.isReg()) {
1355 report("extract source must be a register", MI
);
1359 const MachineOperand
&OffsetOp
= MI
->getOperand(2);
1360 if (!OffsetOp
.isImm()) {
1361 report("extract offset must be a constant", MI
);
1365 unsigned DstSize
= MRI
->getType(MI
->getOperand(0).getReg()).getSizeInBits();
1366 unsigned SrcSize
= MRI
->getType(SrcOp
.getReg()).getSizeInBits();
1367 if (SrcSize
== DstSize
)
1368 report("extract source must be larger than result", MI
);
1370 if (DstSize
+ OffsetOp
.getImm() > SrcSize
)
1371 report("extract reads past end of register", MI
);
1374 case TargetOpcode::G_INSERT
: {
1375 const MachineOperand
&SrcOp
= MI
->getOperand(2);
1376 if (!SrcOp
.isReg()) {
1377 report("insert source must be a register", MI
);
1381 const MachineOperand
&OffsetOp
= MI
->getOperand(3);
1382 if (!OffsetOp
.isImm()) {
1383 report("insert offset must be a constant", MI
);
1387 unsigned DstSize
= MRI
->getType(MI
->getOperand(0).getReg()).getSizeInBits();
1388 unsigned SrcSize
= MRI
->getType(SrcOp
.getReg()).getSizeInBits();
1390 if (DstSize
<= SrcSize
)
1391 report("inserted size must be smaller than total register", MI
);
1393 if (SrcSize
+ OffsetOp
.getImm() > DstSize
)
1394 report("insert writes past end of register", MI
);
1398 case TargetOpcode::G_JUMP_TABLE
: {
1399 if (!MI
->getOperand(1).isJTI())
1400 report("G_JUMP_TABLE source operand must be a jump table index", MI
);
1401 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1402 if (!DstTy
.isPointer())
1403 report("G_JUMP_TABLE dest operand must have a pointer type", MI
);
1406 case TargetOpcode::G_BRJT
: {
1407 if (!MRI
->getType(MI
->getOperand(0).getReg()).isPointer())
1408 report("G_BRJT src operand 0 must be a pointer type", MI
);
1410 if (!MI
->getOperand(1).isJTI())
1411 report("G_BRJT src operand 1 must be a jump table index", MI
);
1413 const auto &IdxOp
= MI
->getOperand(2);
1414 if (!IdxOp
.isReg() || MRI
->getType(IdxOp
.getReg()).isPointer())
1415 report("G_BRJT src operand 2 must be a scalar reg type", MI
);
1418 case TargetOpcode::G_INTRINSIC
:
1419 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS
: {
1420 // TODO: Should verify number of def and use operands, but the current
1421 // interface requires passing in IR types for mangling.
1422 const MachineOperand
&IntrIDOp
= MI
->getOperand(MI
->getNumExplicitDefs());
1423 if (!IntrIDOp
.isIntrinsicID()) {
1424 report("G_INTRINSIC first src operand must be an intrinsic ID", MI
);
1428 bool NoSideEffects
= MI
->getOpcode() == TargetOpcode::G_INTRINSIC
;
1429 unsigned IntrID
= IntrIDOp
.getIntrinsicID();
1430 if (IntrID
!= 0 && IntrID
< Intrinsic::num_intrinsics
) {
1432 = Intrinsic::getAttributes(MF
->getFunction().getContext(),
1433 static_cast<Intrinsic::ID
>(IntrID
));
1434 bool DeclHasSideEffects
= !Attrs
.hasFnAttr(Attribute::ReadNone
);
1435 if (NoSideEffects
&& DeclHasSideEffects
) {
1436 report("G_INTRINSIC used with intrinsic that accesses memory", MI
);
1439 if (!NoSideEffects
&& !DeclHasSideEffects
) {
1440 report("G_INTRINSIC_W_SIDE_EFFECTS used with readnone intrinsic", MI
);
1447 case TargetOpcode::G_SEXT_INREG
: {
1448 if (!MI
->getOperand(2).isImm()) {
1449 report("G_SEXT_INREG expects an immediate operand #2", MI
);
1453 LLT SrcTy
= MRI
->getType(MI
->getOperand(1).getReg());
1454 int64_t Imm
= MI
->getOperand(2).getImm();
1456 report("G_SEXT_INREG size must be >= 1", MI
);
1457 if (Imm
>= SrcTy
.getScalarSizeInBits())
1458 report("G_SEXT_INREG size must be less than source bit width", MI
);
1461 case TargetOpcode::G_SHUFFLE_VECTOR
: {
1462 const MachineOperand
&MaskOp
= MI
->getOperand(3);
1463 if (!MaskOp
.isShuffleMask()) {
1464 report("Incorrect mask operand type for G_SHUFFLE_VECTOR", MI
);
1468 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1469 LLT Src0Ty
= MRI
->getType(MI
->getOperand(1).getReg());
1470 LLT Src1Ty
= MRI
->getType(MI
->getOperand(2).getReg());
1472 if (Src0Ty
!= Src1Ty
)
1473 report("Source operands must be the same type", MI
);
1475 if (Src0Ty
.getScalarType() != DstTy
.getScalarType())
1476 report("G_SHUFFLE_VECTOR cannot change element type", MI
);
1478 // Don't check that all operands are vector because scalars are used in
1479 // place of 1 element vectors.
1480 int SrcNumElts
= Src0Ty
.isVector() ? Src0Ty
.getNumElements() : 1;
1481 int DstNumElts
= DstTy
.isVector() ? DstTy
.getNumElements() : 1;
1483 ArrayRef
<int> MaskIdxes
= MaskOp
.getShuffleMask();
1485 if (static_cast<int>(MaskIdxes
.size()) != DstNumElts
)
1486 report("Wrong result type for shufflemask", MI
);
1488 for (int Idx
: MaskIdxes
) {
1492 if (Idx
>= 2 * SrcNumElts
)
1493 report("Out of bounds shuffle index", MI
);
1498 case TargetOpcode::G_DYN_STACKALLOC
: {
1499 const MachineOperand
&DstOp
= MI
->getOperand(0);
1500 const MachineOperand
&AllocOp
= MI
->getOperand(1);
1501 const MachineOperand
&AlignOp
= MI
->getOperand(2);
1503 if (!DstOp
.isReg() || !MRI
->getType(DstOp
.getReg()).isPointer()) {
1504 report("dst operand 0 must be a pointer type", MI
);
1508 if (!AllocOp
.isReg() || !MRI
->getType(AllocOp
.getReg()).isScalar()) {
1509 report("src operand 1 must be a scalar reg type", MI
);
1513 if (!AlignOp
.isImm()) {
1514 report("src operand 2 must be an immediate type", MI
);
1519 case TargetOpcode::G_MEMCPY_INLINE
:
1520 case TargetOpcode::G_MEMCPY
:
1521 case TargetOpcode::G_MEMMOVE
: {
1522 ArrayRef
<MachineMemOperand
*> MMOs
= MI
->memoperands();
1523 if (MMOs
.size() != 2) {
1524 report("memcpy/memmove must have 2 memory operands", MI
);
1528 if ((!MMOs
[0]->isStore() || MMOs
[0]->isLoad()) ||
1529 (MMOs
[1]->isStore() || !MMOs
[1]->isLoad())) {
1530 report("wrong memory operand types", MI
);
1534 if (MMOs
[0]->getSize() != MMOs
[1]->getSize())
1535 report("inconsistent memory operand sizes", MI
);
1537 LLT DstPtrTy
= MRI
->getType(MI
->getOperand(0).getReg());
1538 LLT SrcPtrTy
= MRI
->getType(MI
->getOperand(1).getReg());
1540 if (!DstPtrTy
.isPointer() || !SrcPtrTy
.isPointer()) {
1541 report("memory instruction operand must be a pointer", MI
);
1545 if (DstPtrTy
.getAddressSpace() != MMOs
[0]->getAddrSpace())
1546 report("inconsistent store address space", MI
);
1547 if (SrcPtrTy
.getAddressSpace() != MMOs
[1]->getAddrSpace())
1548 report("inconsistent load address space", MI
);
1550 if (Opc
!= TargetOpcode::G_MEMCPY_INLINE
)
1551 if (!MI
->getOperand(3).isImm() || (MI
->getOperand(3).getImm() & ~1LL))
1552 report("'tail' flag (operand 3) must be an immediate 0 or 1", MI
);
1556 case TargetOpcode::G_BZERO
:
1557 case TargetOpcode::G_MEMSET
: {
1558 ArrayRef
<MachineMemOperand
*> MMOs
= MI
->memoperands();
1559 std::string Name
= Opc
== TargetOpcode::G_MEMSET
? "memset" : "bzero";
1560 if (MMOs
.size() != 1) {
1561 report(Twine(Name
, " must have 1 memory operand"), MI
);
1565 if ((!MMOs
[0]->isStore() || MMOs
[0]->isLoad())) {
1566 report(Twine(Name
, " memory operand must be a store"), MI
);
1570 LLT DstPtrTy
= MRI
->getType(MI
->getOperand(0).getReg());
1571 if (!DstPtrTy
.isPointer()) {
1572 report(Twine(Name
, " operand must be a pointer"), MI
);
1576 if (DstPtrTy
.getAddressSpace() != MMOs
[0]->getAddrSpace())
1577 report("inconsistent " + Twine(Name
, " address space"), MI
);
1579 if (!MI
->getOperand(MI
->getNumOperands() - 1).isImm() ||
1580 (MI
->getOperand(MI
->getNumOperands() - 1).getImm() & ~1LL))
1581 report("'tail' flag (last operand) must be an immediate 0 or 1", MI
);
1585 case TargetOpcode::G_VECREDUCE_SEQ_FADD
:
1586 case TargetOpcode::G_VECREDUCE_SEQ_FMUL
: {
1587 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1588 LLT Src1Ty
= MRI
->getType(MI
->getOperand(1).getReg());
1589 LLT Src2Ty
= MRI
->getType(MI
->getOperand(2).getReg());
1590 if (!DstTy
.isScalar())
1591 report("Vector reduction requires a scalar destination type", MI
);
1592 if (!Src1Ty
.isScalar())
1593 report("Sequential FADD/FMUL vector reduction requires a scalar 1st operand", MI
);
1594 if (!Src2Ty
.isVector())
1595 report("Sequential FADD/FMUL vector reduction must have a vector 2nd operand", MI
);
1598 case TargetOpcode::G_VECREDUCE_FADD
:
1599 case TargetOpcode::G_VECREDUCE_FMUL
:
1600 case TargetOpcode::G_VECREDUCE_FMAX
:
1601 case TargetOpcode::G_VECREDUCE_FMIN
:
1602 case TargetOpcode::G_VECREDUCE_ADD
:
1603 case TargetOpcode::G_VECREDUCE_MUL
:
1604 case TargetOpcode::G_VECREDUCE_AND
:
1605 case TargetOpcode::G_VECREDUCE_OR
:
1606 case TargetOpcode::G_VECREDUCE_XOR
:
1607 case TargetOpcode::G_VECREDUCE_SMAX
:
1608 case TargetOpcode::G_VECREDUCE_SMIN
:
1609 case TargetOpcode::G_VECREDUCE_UMAX
:
1610 case TargetOpcode::G_VECREDUCE_UMIN
: {
1611 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1612 if (!DstTy
.isScalar())
1613 report("Vector reduction requires a scalar destination type", MI
);
1617 case TargetOpcode::G_SBFX
:
1618 case TargetOpcode::G_UBFX
: {
1619 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1620 if (DstTy
.isVector()) {
1621 report("Bitfield extraction is not supported on vectors", MI
);
1626 case TargetOpcode::G_ROTR
:
1627 case TargetOpcode::G_ROTL
: {
1628 LLT Src1Ty
= MRI
->getType(MI
->getOperand(1).getReg());
1629 LLT Src2Ty
= MRI
->getType(MI
->getOperand(2).getReg());
1630 if (Src1Ty
.isVector() != Src2Ty
.isVector()) {
1631 report("Rotate requires operands to be either all scalars or all vectors",
1637 case TargetOpcode::G_LLROUND
:
1638 case TargetOpcode::G_LROUND
: {
1639 verifyAllRegOpsScalar(*MI
, *MRI
);
1647 void MachineVerifier::visitMachineInstrBefore(const MachineInstr
*MI
) {
1648 const MCInstrDesc
&MCID
= MI
->getDesc();
1649 if (MI
->getNumOperands() < MCID
.getNumOperands()) {
1650 report("Too few operands", MI
);
1651 errs() << MCID
.getNumOperands() << " operands expected, but "
1652 << MI
->getNumOperands() << " given.\n";
1656 if (MF
->getProperties().hasProperty(
1657 MachineFunctionProperties::Property::NoPHIs
))
1658 report("Found PHI instruction with NoPHIs property set", MI
);
1661 report("Found PHI instruction after non-PHI", MI
);
1662 } else if (FirstNonPHI
== nullptr)
1665 // Check the tied operands.
1666 if (MI
->isInlineAsm())
1667 verifyInlineAsm(MI
);
1669 // Check that unspillable terminators define a reg and have at most one use.
1670 if (TII
->isUnspillableTerminator(MI
)) {
1671 if (!MI
->getOperand(0).isReg() || !MI
->getOperand(0).isDef())
1672 report("Unspillable Terminator does not define a reg", MI
);
1673 Register Def
= MI
->getOperand(0).getReg();
1674 if (Def
.isVirtual() &&
1675 std::distance(MRI
->use_nodbg_begin(Def
), MRI
->use_nodbg_end()) > 1)
1676 report("Unspillable Terminator expected to have at most one use!", MI
);
1679 // A fully-formed DBG_VALUE must have a location. Ignore partially formed
1680 // DBG_VALUEs: these are convenient to use in tests, but should never get
1682 if (MI
->isDebugValue() && MI
->getNumOperands() == 4)
1683 if (!MI
->getDebugLoc())
1684 report("Missing DebugLoc for debug instruction", MI
);
1686 // Meta instructions should never be the subject of debug value tracking,
1687 // they don't create a value in the output program at all.
1688 if (MI
->isMetaInstruction() && MI
->peekDebugInstrNum())
1689 report("Metadata instruction should not have a value tracking number", MI
);
1691 // Check the MachineMemOperands for basic consistency.
1692 for (MachineMemOperand
*Op
: MI
->memoperands()) {
1693 if (Op
->isLoad() && !MI
->mayLoad())
1694 report("Missing mayLoad flag", MI
);
1695 if (Op
->isStore() && !MI
->mayStore())
1696 report("Missing mayStore flag", MI
);
1699 // Debug values must not have a slot index.
1700 // Other instructions must have one, unless they are inside a bundle.
1702 bool mapped
= !LiveInts
->isNotInMIMap(*MI
);
1703 if (MI
->isDebugOrPseudoInstr()) {
1705 report("Debug instruction has a slot index", MI
);
1706 } else if (MI
->isInsideBundle()) {
1708 report("Instruction inside bundle has a slot index", MI
);
1711 report("Missing slot index", MI
);
1715 unsigned Opc
= MCID
.getOpcode();
1716 if (isPreISelGenericOpcode(Opc
) || isPreISelGenericOptimizationHint(Opc
)) {
1717 verifyPreISelGenericInstruction(MI
);
1721 StringRef ErrorInfo
;
1722 if (!TII
->verifyInstruction(*MI
, ErrorInfo
))
1723 report(ErrorInfo
.data(), MI
);
1725 // Verify properties of various specific instruction types
1726 switch (MI
->getOpcode()) {
1727 case TargetOpcode::COPY
: {
1728 const MachineOperand
&DstOp
= MI
->getOperand(0);
1729 const MachineOperand
&SrcOp
= MI
->getOperand(1);
1730 const Register SrcReg
= SrcOp
.getReg();
1731 const Register DstReg
= DstOp
.getReg();
1733 LLT DstTy
= MRI
->getType(DstReg
);
1734 LLT SrcTy
= MRI
->getType(SrcReg
);
1735 if (SrcTy
.isValid() && DstTy
.isValid()) {
1736 // If both types are valid, check that the types are the same.
1737 if (SrcTy
!= DstTy
) {
1738 report("Copy Instruction is illegal with mismatching types", MI
);
1739 errs() << "Def = " << DstTy
<< ", Src = " << SrcTy
<< "\n";
1745 if (!SrcTy
.isValid() && !DstTy
.isValid())
1748 // If we have only one valid type, this is likely a copy between a virtual
1749 // and physical register.
1750 unsigned SrcSize
= 0;
1751 unsigned DstSize
= 0;
1752 if (SrcReg
.isPhysical() && DstTy
.isValid()) {
1753 const TargetRegisterClass
*SrcRC
=
1754 TRI
->getMinimalPhysRegClassLLT(SrcReg
, DstTy
);
1756 SrcSize
= TRI
->getRegSizeInBits(*SrcRC
);
1760 SrcSize
= TRI
->getRegSizeInBits(SrcReg
, *MRI
);
1762 if (DstReg
.isPhysical() && SrcTy
.isValid()) {
1763 const TargetRegisterClass
*DstRC
=
1764 TRI
->getMinimalPhysRegClassLLT(DstReg
, SrcTy
);
1766 DstSize
= TRI
->getRegSizeInBits(*DstRC
);
1770 DstSize
= TRI
->getRegSizeInBits(DstReg
, *MRI
);
1772 if (SrcSize
!= 0 && DstSize
!= 0 && SrcSize
!= DstSize
) {
1773 if (!DstOp
.getSubReg() && !SrcOp
.getSubReg()) {
1774 report("Copy Instruction is illegal with mismatching sizes", MI
);
1775 errs() << "Def Size = " << DstSize
<< ", Src Size = " << SrcSize
1781 case TargetOpcode::STATEPOINT
: {
1782 StatepointOpers
SO(MI
);
1783 if (!MI
->getOperand(SO
.getIDPos()).isImm() ||
1784 !MI
->getOperand(SO
.getNBytesPos()).isImm() ||
1785 !MI
->getOperand(SO
.getNCallArgsPos()).isImm()) {
1786 report("meta operands to STATEPOINT not constant!", MI
);
1790 auto VerifyStackMapConstant
= [&](unsigned Offset
) {
1791 if (Offset
>= MI
->getNumOperands()) {
1792 report("stack map constant to STATEPOINT is out of range!", MI
);
1795 if (!MI
->getOperand(Offset
- 1).isImm() ||
1796 MI
->getOperand(Offset
- 1).getImm() != StackMaps::ConstantOp
||
1797 !MI
->getOperand(Offset
).isImm())
1798 report("stack map constant to STATEPOINT not well formed!", MI
);
1800 VerifyStackMapConstant(SO
.getCCIdx());
1801 VerifyStackMapConstant(SO
.getFlagsIdx());
1802 VerifyStackMapConstant(SO
.getNumDeoptArgsIdx());
1803 VerifyStackMapConstant(SO
.getNumGCPtrIdx());
1804 VerifyStackMapConstant(SO
.getNumAllocaIdx());
1805 VerifyStackMapConstant(SO
.getNumGcMapEntriesIdx());
1807 // Verify that all explicit statepoint defs are tied to gc operands as
1808 // they are expected to be a relocation of gc operands.
1809 unsigned FirstGCPtrIdx
= SO
.getFirstGCPtrIdx();
1810 unsigned LastGCPtrIdx
= SO
.getNumAllocaIdx() - 2;
1811 for (unsigned Idx
= 0; Idx
< MI
->getNumDefs(); Idx
++) {
1813 if (!MI
->isRegTiedToUseOperand(Idx
, &UseOpIdx
)) {
1814 report("STATEPOINT defs expected to be tied", MI
);
1817 if (UseOpIdx
< FirstGCPtrIdx
|| UseOpIdx
> LastGCPtrIdx
) {
1818 report("STATEPOINT def tied to non-gc operand", MI
);
1823 // TODO: verify we have properly encoded deopt arguments
1825 case TargetOpcode::INSERT_SUBREG
: {
1826 unsigned InsertedSize
;
1827 if (unsigned SubIdx
= MI
->getOperand(2).getSubReg())
1828 InsertedSize
= TRI
->getSubRegIdxSize(SubIdx
);
1830 InsertedSize
= TRI
->getRegSizeInBits(MI
->getOperand(2).getReg(), *MRI
);
1831 unsigned SubRegSize
= TRI
->getSubRegIdxSize(MI
->getOperand(3).getImm());
1832 if (SubRegSize
< InsertedSize
) {
1833 report("INSERT_SUBREG expected inserted value to have equal or lesser "
1834 "size than the subreg it was inserted into", MI
);
1842 MachineVerifier::visitMachineOperand(const MachineOperand
*MO
, unsigned MONum
) {
1843 const MachineInstr
*MI
= MO
->getParent();
1844 const MCInstrDesc
&MCID
= MI
->getDesc();
1845 unsigned NumDefs
= MCID
.getNumDefs();
1846 if (MCID
.getOpcode() == TargetOpcode::PATCHPOINT
)
1847 NumDefs
= (MONum
== 0 && MO
->isReg()) ? NumDefs
: 0;
1849 // The first MCID.NumDefs operands must be explicit register defines
1850 if (MONum
< NumDefs
) {
1851 const MCOperandInfo
&MCOI
= MCID
.OpInfo
[MONum
];
1853 report("Explicit definition must be a register", MO
, MONum
);
1854 else if (!MO
->isDef() && !MCOI
.isOptionalDef())
1855 report("Explicit definition marked as use", MO
, MONum
);
1856 else if (MO
->isImplicit())
1857 report("Explicit definition marked as implicit", MO
, MONum
);
1858 } else if (MONum
< MCID
.getNumOperands()) {
1859 const MCOperandInfo
&MCOI
= MCID
.OpInfo
[MONum
];
1860 // Don't check if it's the last operand in a variadic instruction. See,
1861 // e.g., LDM_RET in the arm back end. Check non-variadic operands only.
1862 bool IsOptional
= MI
->isVariadic() && MONum
== MCID
.getNumOperands() - 1;
1865 if (MO
->isDef() && !MCOI
.isOptionalDef() && !MCID
.variadicOpsAreDefs())
1866 report("Explicit operand marked as def", MO
, MONum
);
1867 if (MO
->isImplicit())
1868 report("Explicit operand marked as implicit", MO
, MONum
);
1871 // Check that an instruction has register operands only as expected.
1872 if (MCOI
.OperandType
== MCOI::OPERAND_REGISTER
&&
1873 !MO
->isReg() && !MO
->isFI())
1874 report("Expected a register operand.", MO
, MONum
);
1876 if (MCOI
.OperandType
== MCOI::OPERAND_IMMEDIATE
||
1877 (MCOI
.OperandType
== MCOI::OPERAND_PCREL
&&
1878 !TII
->isPCRelRegisterOperandLegal(*MO
)))
1879 report("Expected a non-register operand.", MO
, MONum
);
1883 int TiedTo
= MCID
.getOperandConstraint(MONum
, MCOI::TIED_TO
);
1886 report("Tied use must be a register", MO
, MONum
);
1887 else if (!MO
->isTied())
1888 report("Operand should be tied", MO
, MONum
);
1889 else if (unsigned(TiedTo
) != MI
->findTiedOperandIdx(MONum
))
1890 report("Tied def doesn't match MCInstrDesc", MO
, MONum
);
1891 else if (Register::isPhysicalRegister(MO
->getReg())) {
1892 const MachineOperand
&MOTied
= MI
->getOperand(TiedTo
);
1893 if (!MOTied
.isReg())
1894 report("Tied counterpart must be a register", &MOTied
, TiedTo
);
1895 else if (Register::isPhysicalRegister(MOTied
.getReg()) &&
1896 MO
->getReg() != MOTied
.getReg())
1897 report("Tied physical registers must match.", &MOTied
, TiedTo
);
1899 } else if (MO
->isReg() && MO
->isTied())
1900 report("Explicit operand should not be tied", MO
, MONum
);
1902 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
1903 if (MO
->isReg() && !MO
->isImplicit() && !MI
->isVariadic() && MO
->getReg())
1904 report("Extra explicit operand on non-variadic instruction", MO
, MONum
);
1907 switch (MO
->getType()) {
1908 case MachineOperand::MO_Register
: {
1909 const Register Reg
= MO
->getReg();
1912 if (MRI
->tracksLiveness() && !MI
->isDebugValue())
1913 checkLiveness(MO
, MONum
);
1915 // Verify the consistency of tied operands.
1917 unsigned OtherIdx
= MI
->findTiedOperandIdx(MONum
);
1918 const MachineOperand
&OtherMO
= MI
->getOperand(OtherIdx
);
1919 if (!OtherMO
.isReg())
1920 report("Must be tied to a register", MO
, MONum
);
1921 if (!OtherMO
.isTied())
1922 report("Missing tie flags on tied operand", MO
, MONum
);
1923 if (MI
->findTiedOperandIdx(OtherIdx
) != MONum
)
1924 report("Inconsistent tie links", MO
, MONum
);
1925 if (MONum
< MCID
.getNumDefs()) {
1926 if (OtherIdx
< MCID
.getNumOperands()) {
1927 if (-1 == MCID
.getOperandConstraint(OtherIdx
, MCOI::TIED_TO
))
1928 report("Explicit def tied to explicit use without tie constraint",
1931 if (!OtherMO
.isImplicit())
1932 report("Explicit def should be tied to implicit use", MO
, MONum
);
1937 // Verify two-address constraints after the twoaddressinstruction pass.
1938 // Both twoaddressinstruction pass and phi-node-elimination pass call
1939 // MRI->leaveSSA() to set MF as NoSSA, we should do the verification after
1940 // twoaddressinstruction pass not after phi-node-elimination pass. So we
1941 // shouldn't use the NoSSA as the condition, we should based on
1942 // TiedOpsRewritten property to verify two-address constraints, this
1943 // property will be set in twoaddressinstruction pass.
1945 if (MF
->getProperties().hasProperty(
1946 MachineFunctionProperties::Property::TiedOpsRewritten
) &&
1947 MO
->isUse() && MI
->isRegTiedToDefOperand(MONum
, &DefIdx
) &&
1948 Reg
!= MI
->getOperand(DefIdx
).getReg())
1949 report("Two-address instruction operands must be identical", MO
, MONum
);
1951 // Check register classes.
1952 unsigned SubIdx
= MO
->getSubReg();
1954 if (Register::isPhysicalRegister(Reg
)) {
1956 report("Illegal subregister index for physical register", MO
, MONum
);
1959 if (MONum
< MCID
.getNumOperands()) {
1960 if (const TargetRegisterClass
*DRC
=
1961 TII
->getRegClass(MCID
, MONum
, TRI
, *MF
)) {
1962 if (!DRC
->contains(Reg
)) {
1963 report("Illegal physical register for instruction", MO
, MONum
);
1964 errs() << printReg(Reg
, TRI
) << " is not a "
1965 << TRI
->getRegClassName(DRC
) << " register.\n";
1969 if (MO
->isRenamable()) {
1970 if (MRI
->isReserved(Reg
)) {
1971 report("isRenamable set on reserved register", MO
, MONum
);
1975 if (MI
->isDebugValue() && MO
->isUse() && !MO
->isDebug()) {
1976 report("Use-reg is not IsDebug in a DBG_VALUE", MO
, MONum
);
1980 // Virtual register.
1981 const TargetRegisterClass
*RC
= MRI
->getRegClassOrNull(Reg
);
1983 // This is a generic virtual register.
1985 // Do not allow undef uses for generic virtual registers. This ensures
1986 // getVRegDef can never fail and return null on a generic register.
1988 // FIXME: This restriction should probably be broadened to all SSA
1989 // MIR. However, DetectDeadLanes/ProcessImplicitDefs technically still
1990 // run on the SSA function just before phi elimination.
1992 report("Generic virtual register use cannot be undef", MO
, MONum
);
1994 // If we're post-Select, we can't have gvregs anymore.
1995 if (isFunctionSelected
) {
1996 report("Generic virtual register invalid in a Selected function",
2001 // The gvreg must have a type and it must not have a SubIdx.
2002 LLT Ty
= MRI
->getType(Reg
);
2003 if (!Ty
.isValid()) {
2004 report("Generic virtual register must have a valid type", MO
,
2009 const RegisterBank
*RegBank
= MRI
->getRegBankOrNull(Reg
);
2011 // If we're post-RegBankSelect, the gvreg must have a bank.
2012 if (!RegBank
&& isFunctionRegBankSelected
) {
2013 report("Generic virtual register must have a bank in a "
2014 "RegBankSelected function",
2019 // Make sure the register fits into its register bank if any.
2020 if (RegBank
&& Ty
.isValid() &&
2021 RegBank
->getSize() < Ty
.getSizeInBits()) {
2022 report("Register bank is too small for virtual register", MO
,
2024 errs() << "Register bank " << RegBank
->getName() << " too small("
2025 << RegBank
->getSize() << ") to fit " << Ty
.getSizeInBits()
2030 report("Generic virtual register does not allow subregister index", MO
,
2035 // If this is a target specific instruction and this operand
2036 // has register class constraint, the virtual register must
2038 if (!isPreISelGenericOpcode(MCID
.getOpcode()) &&
2039 MONum
< MCID
.getNumOperands() &&
2040 TII
->getRegClass(MCID
, MONum
, TRI
, *MF
)) {
2041 report("Virtual register does not match instruction constraint", MO
,
2043 errs() << "Expect register class "
2044 << TRI
->getRegClassName(
2045 TII
->getRegClass(MCID
, MONum
, TRI
, *MF
))
2046 << " but got nothing\n";
2053 const TargetRegisterClass
*SRC
=
2054 TRI
->getSubClassWithSubReg(RC
, SubIdx
);
2056 report("Invalid subregister index for virtual register", MO
, MONum
);
2057 errs() << "Register class " << TRI
->getRegClassName(RC
)
2058 << " does not support subreg index " << SubIdx
<< "\n";
2062 report("Invalid register class for subregister index", MO
, MONum
);
2063 errs() << "Register class " << TRI
->getRegClassName(RC
)
2064 << " does not fully support subreg index " << SubIdx
<< "\n";
2068 if (MONum
< MCID
.getNumOperands()) {
2069 if (const TargetRegisterClass
*DRC
=
2070 TII
->getRegClass(MCID
, MONum
, TRI
, *MF
)) {
2072 const TargetRegisterClass
*SuperRC
=
2073 TRI
->getLargestLegalSuperClass(RC
, *MF
);
2075 report("No largest legal super class exists.", MO
, MONum
);
2078 DRC
= TRI
->getMatchingSuperRegClass(SuperRC
, DRC
, SubIdx
);
2080 report("No matching super-reg register class.", MO
, MONum
);
2084 if (!RC
->hasSuperClassEq(DRC
)) {
2085 report("Illegal virtual register for instruction", MO
, MONum
);
2086 errs() << "Expected a " << TRI
->getRegClassName(DRC
)
2087 << " register, but got a " << TRI
->getRegClassName(RC
)
2096 case MachineOperand::MO_RegisterMask
:
2097 regMasks
.push_back(MO
->getRegMask());
2100 case MachineOperand::MO_MachineBasicBlock
:
2101 if (MI
->isPHI() && !MO
->getMBB()->isSuccessor(MI
->getParent()))
2102 report("PHI operand is not in the CFG", MO
, MONum
);
2105 case MachineOperand::MO_FrameIndex
:
2106 if (LiveStks
&& LiveStks
->hasInterval(MO
->getIndex()) &&
2107 LiveInts
&& !LiveInts
->isNotInMIMap(*MI
)) {
2108 int FI
= MO
->getIndex();
2109 LiveInterval
&LI
= LiveStks
->getInterval(FI
);
2110 SlotIndex Idx
= LiveInts
->getInstructionIndex(*MI
);
2112 bool stores
= MI
->mayStore();
2113 bool loads
= MI
->mayLoad();
2114 // For a memory-to-memory move, we need to check if the frame
2115 // index is used for storing or loading, by inspecting the
2117 if (stores
&& loads
) {
2118 for (auto *MMO
: MI
->memoperands()) {
2119 const PseudoSourceValue
*PSV
= MMO
->getPseudoValue();
2120 if (PSV
== nullptr) continue;
2121 const FixedStackPseudoSourceValue
*Value
=
2122 dyn_cast
<FixedStackPseudoSourceValue
>(PSV
);
2123 if (Value
== nullptr) continue;
2124 if (Value
->getFrameIndex() != FI
) continue;
2132 if (loads
== stores
)
2133 report("Missing fixed stack memoperand.", MI
);
2135 if (loads
&& !LI
.liveAt(Idx
.getRegSlot(true))) {
2136 report("Instruction loads from dead spill slot", MO
, MONum
);
2137 errs() << "Live stack: " << LI
<< '\n';
2139 if (stores
&& !LI
.liveAt(Idx
.getRegSlot())) {
2140 report("Instruction stores to dead spill slot", MO
, MONum
);
2141 errs() << "Live stack: " << LI
<< '\n';
2151 void MachineVerifier::checkLivenessAtUse(const MachineOperand
*MO
,
2152 unsigned MONum
, SlotIndex UseIdx
,
2153 const LiveRange
&LR
,
2154 Register VRegOrUnit
,
2155 LaneBitmask LaneMask
) {
2156 LiveQueryResult LRQ
= LR
.Query(UseIdx
);
2157 // Check if we have a segment at the use, note however that we only need one
2158 // live subregister range, the others may be dead.
2159 if (!LRQ
.valueIn() && LaneMask
.none()) {
2160 report("No live segment at use", MO
, MONum
);
2161 report_context_liverange(LR
);
2162 report_context_vreg_regunit(VRegOrUnit
);
2163 report_context(UseIdx
);
2165 if (MO
->isKill() && !LRQ
.isKill()) {
2166 report("Live range continues after kill flag", MO
, MONum
);
2167 report_context_liverange(LR
);
2168 report_context_vreg_regunit(VRegOrUnit
);
2170 report_context_lanemask(LaneMask
);
2171 report_context(UseIdx
);
2175 void MachineVerifier::checkLivenessAtDef(const MachineOperand
*MO
,
2176 unsigned MONum
, SlotIndex DefIdx
,
2177 const LiveRange
&LR
,
2178 Register VRegOrUnit
,
2180 LaneBitmask LaneMask
) {
2181 if (const VNInfo
*VNI
= LR
.getVNInfoAt(DefIdx
)) {
2182 assert(VNI
&& "NULL valno is not allowed");
2183 if (VNI
->def
!= DefIdx
) {
2184 report("Inconsistent valno->def", MO
, MONum
);
2185 report_context_liverange(LR
);
2186 report_context_vreg_regunit(VRegOrUnit
);
2188 report_context_lanemask(LaneMask
);
2189 report_context(*VNI
);
2190 report_context(DefIdx
);
2193 report("No live segment at def", MO
, MONum
);
2194 report_context_liverange(LR
);
2195 report_context_vreg_regunit(VRegOrUnit
);
2197 report_context_lanemask(LaneMask
);
2198 report_context(DefIdx
);
2200 // Check that, if the dead def flag is present, LiveInts agree.
2202 LiveQueryResult LRQ
= LR
.Query(DefIdx
);
2203 if (!LRQ
.isDeadDef()) {
2204 assert(Register::isVirtualRegister(VRegOrUnit
) &&
2205 "Expecting a virtual register.");
2206 // A dead subreg def only tells us that the specific subreg is dead. There
2207 // could be other non-dead defs of other subregs, or we could have other
2208 // parts of the register being live through the instruction. So unless we
2209 // are checking liveness for a subrange it is ok for the live range to
2210 // continue, given that we have a dead def of a subregister.
2211 if (SubRangeCheck
|| MO
->getSubReg() == 0) {
2212 report("Live range continues after dead def flag", MO
, MONum
);
2213 report_context_liverange(LR
);
2214 report_context_vreg_regunit(VRegOrUnit
);
2216 report_context_lanemask(LaneMask
);
2222 void MachineVerifier::checkLiveness(const MachineOperand
*MO
, unsigned MONum
) {
2223 const MachineInstr
*MI
= MO
->getParent();
2224 const Register Reg
= MO
->getReg();
2226 // Both use and def operands can read a register.
2227 if (MO
->readsReg()) {
2229 addRegWithSubRegs(regsKilled
, Reg
);
2231 // Check that LiveVars knows this kill.
2232 if (LiveVars
&& Register::isVirtualRegister(Reg
) && MO
->isKill()) {
2233 LiveVariables::VarInfo
&VI
= LiveVars
->getVarInfo(Reg
);
2234 if (!is_contained(VI
.Kills
, MI
))
2235 report("Kill missing from LiveVariables", MO
, MONum
);
2238 // Check LiveInts liveness and kill.
2239 if (LiveInts
&& !LiveInts
->isNotInMIMap(*MI
)) {
2240 SlotIndex UseIdx
= LiveInts
->getInstructionIndex(*MI
);
2241 // Check the cached regunit intervals.
2242 if (Reg
.isPhysical() && !isReserved(Reg
)) {
2243 for (MCRegUnitIterator
Units(Reg
.asMCReg(), TRI
); Units
.isValid();
2245 if (MRI
->isReservedRegUnit(*Units
))
2247 if (const LiveRange
*LR
= LiveInts
->getCachedRegUnit(*Units
))
2248 checkLivenessAtUse(MO
, MONum
, UseIdx
, *LR
, *Units
);
2252 if (Register::isVirtualRegister(Reg
)) {
2253 if (LiveInts
->hasInterval(Reg
)) {
2254 // This is a virtual register interval.
2255 const LiveInterval
&LI
= LiveInts
->getInterval(Reg
);
2256 checkLivenessAtUse(MO
, MONum
, UseIdx
, LI
, Reg
);
2258 if (LI
.hasSubRanges() && !MO
->isDef()) {
2259 unsigned SubRegIdx
= MO
->getSubReg();
2260 LaneBitmask MOMask
= SubRegIdx
!= 0
2261 ? TRI
->getSubRegIndexLaneMask(SubRegIdx
)
2262 : MRI
->getMaxLaneMaskForVReg(Reg
);
2263 LaneBitmask LiveInMask
;
2264 for (const LiveInterval::SubRange
&SR
: LI
.subranges()) {
2265 if ((MOMask
& SR
.LaneMask
).none())
2267 checkLivenessAtUse(MO
, MONum
, UseIdx
, SR
, Reg
, SR
.LaneMask
);
2268 LiveQueryResult LRQ
= SR
.Query(UseIdx
);
2270 LiveInMask
|= SR
.LaneMask
;
2272 // At least parts of the register has to be live at the use.
2273 if ((LiveInMask
& MOMask
).none()) {
2274 report("No live subrange at use", MO
, MONum
);
2276 report_context(UseIdx
);
2280 report("Virtual register has no live interval", MO
, MONum
);
2285 // Use of a dead register.
2286 if (!regsLive
.count(Reg
)) {
2287 if (Register::isPhysicalRegister(Reg
)) {
2288 // Reserved registers may be used even when 'dead'.
2289 bool Bad
= !isReserved(Reg
);
2290 // We are fine if just any subregister has a defined value.
2293 for (const MCPhysReg
&SubReg
: TRI
->subregs(Reg
)) {
2294 if (regsLive
.count(SubReg
)) {
2300 // If there is an additional implicit-use of a super register we stop
2301 // here. By definition we are fine if the super register is not
2302 // (completely) dead, if the complete super register is dead we will
2303 // get a report for its operand.
2305 for (const MachineOperand
&MOP
: MI
->uses()) {
2306 if (!MOP
.isReg() || !MOP
.isImplicit())
2309 if (!Register::isPhysicalRegister(MOP
.getReg()))
2312 if (llvm::is_contained(TRI
->subregs(MOP
.getReg()), Reg
))
2317 report("Using an undefined physical register", MO
, MONum
);
2318 } else if (MRI
->def_empty(Reg
)) {
2319 report("Reading virtual register without a def", MO
, MONum
);
2321 BBInfo
&MInfo
= MBBInfoMap
[MI
->getParent()];
2322 // We don't know which virtual registers are live in, so only complain
2323 // if vreg was killed in this MBB. Otherwise keep track of vregs that
2324 // must be live in. PHI instructions are handled separately.
2325 if (MInfo
.regsKilled
.count(Reg
))
2326 report("Using a killed virtual register", MO
, MONum
);
2327 else if (!MI
->isPHI())
2328 MInfo
.vregsLiveIn
.insert(std::make_pair(Reg
, MI
));
2334 // Register defined.
2335 // TODO: verify that earlyclobber ops are not used.
2337 addRegWithSubRegs(regsDead
, Reg
);
2339 addRegWithSubRegs(regsDefined
, Reg
);
2342 if (MRI
->isSSA() && Register::isVirtualRegister(Reg
) &&
2343 std::next(MRI
->def_begin(Reg
)) != MRI
->def_end())
2344 report("Multiple virtual register defs in SSA form", MO
, MONum
);
2346 // Check LiveInts for a live segment, but only for virtual registers.
2347 if (LiveInts
&& !LiveInts
->isNotInMIMap(*MI
)) {
2348 SlotIndex DefIdx
= LiveInts
->getInstructionIndex(*MI
);
2349 DefIdx
= DefIdx
.getRegSlot(MO
->isEarlyClobber());
2351 if (Register::isVirtualRegister(Reg
)) {
2352 if (LiveInts
->hasInterval(Reg
)) {
2353 const LiveInterval
&LI
= LiveInts
->getInterval(Reg
);
2354 checkLivenessAtDef(MO
, MONum
, DefIdx
, LI
, Reg
);
2356 if (LI
.hasSubRanges()) {
2357 unsigned SubRegIdx
= MO
->getSubReg();
2358 LaneBitmask MOMask
= SubRegIdx
!= 0
2359 ? TRI
->getSubRegIndexLaneMask(SubRegIdx
)
2360 : MRI
->getMaxLaneMaskForVReg(Reg
);
2361 for (const LiveInterval::SubRange
&SR
: LI
.subranges()) {
2362 if ((SR
.LaneMask
& MOMask
).none())
2364 checkLivenessAtDef(MO
, MONum
, DefIdx
, SR
, Reg
, true, SR
.LaneMask
);
2368 report("Virtual register has no Live interval", MO
, MONum
);
2375 // This function gets called after visiting all instructions in a bundle. The
2376 // argument points to the bundle header.
2377 // Normal stand-alone instructions are also considered 'bundles', and this
2378 // function is called for all of them.
2379 void MachineVerifier::visitMachineBundleAfter(const MachineInstr
*MI
) {
2380 BBInfo
&MInfo
= MBBInfoMap
[MI
->getParent()];
2381 set_union(MInfo
.regsKilled
, regsKilled
);
2382 set_subtract(regsLive
, regsKilled
); regsKilled
.clear();
2383 // Kill any masked registers.
2384 while (!regMasks
.empty()) {
2385 const uint32_t *Mask
= regMasks
.pop_back_val();
2386 for (Register Reg
: regsLive
)
2387 if (Reg
.isPhysical() &&
2388 MachineOperand::clobbersPhysReg(Mask
, Reg
.asMCReg()))
2389 regsDead
.push_back(Reg
);
2391 set_subtract(regsLive
, regsDead
); regsDead
.clear();
2392 set_union(regsLive
, regsDefined
); regsDefined
.clear();
2396 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock
*MBB
) {
2397 MBBInfoMap
[MBB
].regsLiveOut
= regsLive
;
2401 SlotIndex stop
= Indexes
->getMBBEndIdx(MBB
);
2402 if (!(stop
> lastIndex
)) {
2403 report("Block ends before last instruction index", MBB
);
2404 errs() << "Block ends at " << stop
2405 << " last instruction was at " << lastIndex
<< '\n';
2412 // This implements a set of registers that serves as a filter: can filter other
2413 // sets by passing through elements not in the filter and blocking those that
2414 // are. Any filter implicitly includes the full set of physical registers upon
2415 // creation, thus filtering them all out. The filter itself as a set only grows,
2416 // and needs to be as efficient as possible.
2418 // Add elements to the filter itself. \pre Input set \p FromRegSet must have
2419 // no duplicates. Both virtual and physical registers are fine.
2420 template <typename RegSetT
> void add(const RegSetT
&FromRegSet
) {
2421 SmallVector
<Register
, 0> VRegsBuffer
;
2422 filterAndAdd(FromRegSet
, VRegsBuffer
);
2424 // Filter \p FromRegSet through the filter and append passed elements into \p
2425 // ToVRegs. All elements appended are then added to the filter itself.
2426 // \returns true if anything changed.
2427 template <typename RegSetT
>
2428 bool filterAndAdd(const RegSetT
&FromRegSet
,
2429 SmallVectorImpl
<Register
> &ToVRegs
) {
2430 unsigned SparseUniverse
= Sparse
.size();
2431 unsigned NewSparseUniverse
= SparseUniverse
;
2432 unsigned NewDenseSize
= Dense
.size();
2433 size_t Begin
= ToVRegs
.size();
2434 for (Register Reg
: FromRegSet
) {
2435 if (!Reg
.isVirtual())
2437 unsigned Index
= Register::virtReg2Index(Reg
);
2438 if (Index
< SparseUniverseMax
) {
2439 if (Index
< SparseUniverse
&& Sparse
.test(Index
))
2441 NewSparseUniverse
= std::max(NewSparseUniverse
, Index
+ 1);
2443 if (Dense
.count(Reg
))
2447 ToVRegs
.push_back(Reg
);
2449 size_t End
= ToVRegs
.size();
2452 // Reserving space in sets once performs better than doing so continuously
2453 // and pays easily for double look-ups (even in Dense with SparseUniverseMax
2454 // tuned all the way down) and double iteration (the second one is over a
2455 // SmallVector, which is a lot cheaper compared to DenseSet or BitVector).
2456 Sparse
.resize(NewSparseUniverse
);
2457 Dense
.reserve(NewDenseSize
);
2458 for (unsigned I
= Begin
; I
< End
; ++I
) {
2459 Register Reg
= ToVRegs
[I
];
2460 unsigned Index
= Register::virtReg2Index(Reg
);
2461 if (Index
< SparseUniverseMax
)
2470 static constexpr unsigned SparseUniverseMax
= 10 * 1024 * 8;
2471 // VRegs indexed within SparseUniverseMax are tracked by Sparse, those beyound
2472 // are tracked by Dense. The only purpose of the threashold and the Dense set
2473 // is to have a reasonably growing memory usage in pathological cases (large
2474 // number of very sparse VRegFilter instances live at the same time). In
2475 // practice even in the worst-by-execution time cases having all elements
2476 // tracked by Sparse (very large SparseUniverseMax scenario) tends to be more
2477 // space efficient than if tracked by Dense. The threashold is set to keep the
2478 // worst-case memory usage within 2x of figures determined empirically for
2479 // "all Dense" scenario in such worst-by-execution-time cases.
2481 DenseSet
<unsigned> Dense
;
2484 // Implements both a transfer function and a (binary, in-place) join operator
2485 // for a dataflow over register sets with set union join and filtering transfer
2486 // (out_b = in_b \ filter_b). filter_b is expected to be set-up ahead of time.
2487 // Maintains out_b as its state, allowing for O(n) iteration over it at any
2488 // time, where n is the size of the set (as opposed to O(U) where U is the
2489 // universe). filter_b implicitly contains all physical registers at all times.
2490 class FilteringVRegSet
{
2492 SmallVector
<Register
, 0> VRegs
;
2495 // Set-up the filter_b. \pre Input register set \p RS must have no duplicates.
2496 // Both virtual and physical registers are fine.
2497 template <typename RegSetT
> void addToFilter(const RegSetT
&RS
) {
2500 // Passes \p RS through the filter_b (transfer function) and adds what's left
2501 // to itself (out_b).
2502 template <typename RegSetT
> bool add(const RegSetT
&RS
) {
2503 // Double-duty the Filter: to maintain VRegs a set (and the join operation
2504 // a set union) just add everything being added here to the Filter as well.
2505 return Filter
.filterAndAdd(RS
, VRegs
);
2507 using const_iterator
= decltype(VRegs
)::const_iterator
;
2508 const_iterator
begin() const { return VRegs
.begin(); }
2509 const_iterator
end() const { return VRegs
.end(); }
2510 size_t size() const { return VRegs
.size(); }
2514 // Calculate the largest possible vregsPassed sets. These are the registers that
2515 // can pass through an MBB live, but may not be live every time. It is assumed
2516 // that all vregsPassed sets are empty before the call.
2517 void MachineVerifier::calcRegsPassed() {
2519 // ReversePostOrderTraversal doesn't handle empty functions.
2522 for (const MachineBasicBlock
*MB
:
2523 ReversePostOrderTraversal
<const MachineFunction
*>(MF
)) {
2524 FilteringVRegSet VRegs
;
2525 BBInfo
&Info
= MBBInfoMap
[MB
];
2526 assert(Info
.reachable
);
2528 VRegs
.addToFilter(Info
.regsKilled
);
2529 VRegs
.addToFilter(Info
.regsLiveOut
);
2530 for (const MachineBasicBlock
*Pred
: MB
->predecessors()) {
2531 const BBInfo
&PredInfo
= MBBInfoMap
[Pred
];
2532 if (!PredInfo
.reachable
)
2535 VRegs
.add(PredInfo
.regsLiveOut
);
2536 VRegs
.add(PredInfo
.vregsPassed
);
2538 Info
.vregsPassed
.reserve(VRegs
.size());
2539 Info
.vregsPassed
.insert(VRegs
.begin(), VRegs
.end());
2543 // Calculate the set of virtual registers that must be passed through each basic
2544 // block in order to satisfy the requirements of successor blocks. This is very
2545 // similar to calcRegsPassed, only backwards.
2546 void MachineVerifier::calcRegsRequired() {
2547 // First push live-in regs to predecessors' vregsRequired.
2548 SmallPtrSet
<const MachineBasicBlock
*, 8> todo
;
2549 for (const auto &MBB
: *MF
) {
2550 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
2551 for (const MachineBasicBlock
*Pred
: MBB
.predecessors()) {
2552 BBInfo
&PInfo
= MBBInfoMap
[Pred
];
2553 if (PInfo
.addRequired(MInfo
.vregsLiveIn
))
2557 // Handle the PHI node.
2558 for (const MachineInstr
&MI
: MBB
.phis()) {
2559 for (unsigned i
= 1, e
= MI
.getNumOperands(); i
!= e
; i
+= 2) {
2560 // Skip those Operands which are undef regs or not regs.
2561 if (!MI
.getOperand(i
).isReg() || !MI
.getOperand(i
).readsReg())
2564 // Get register and predecessor for one PHI edge.
2565 Register Reg
= MI
.getOperand(i
).getReg();
2566 const MachineBasicBlock
*Pred
= MI
.getOperand(i
+ 1).getMBB();
2568 BBInfo
&PInfo
= MBBInfoMap
[Pred
];
2569 if (PInfo
.addRequired(Reg
))
2575 // Iteratively push vregsRequired to predecessors. This will converge to the
2576 // same final state regardless of DenseSet iteration order.
2577 while (!todo
.empty()) {
2578 const MachineBasicBlock
*MBB
= *todo
.begin();
2580 BBInfo
&MInfo
= MBBInfoMap
[MBB
];
2581 for (const MachineBasicBlock
*Pred
: MBB
->predecessors()) {
2584 BBInfo
&SInfo
= MBBInfoMap
[Pred
];
2585 if (SInfo
.addRequired(MInfo
.vregsRequired
))
2591 // Check PHI instructions at the beginning of MBB. It is assumed that
2592 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
2593 void MachineVerifier::checkPHIOps(const MachineBasicBlock
&MBB
) {
2594 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
2596 SmallPtrSet
<const MachineBasicBlock
*, 8> seen
;
2597 for (const MachineInstr
&Phi
: MBB
) {
2602 const MachineOperand
&MODef
= Phi
.getOperand(0);
2603 if (!MODef
.isReg() || !MODef
.isDef()) {
2604 report("Expected first PHI operand to be a register def", &MODef
, 0);
2607 if (MODef
.isTied() || MODef
.isImplicit() || MODef
.isInternalRead() ||
2608 MODef
.isEarlyClobber() || MODef
.isDebug())
2609 report("Unexpected flag on PHI operand", &MODef
, 0);
2610 Register DefReg
= MODef
.getReg();
2611 if (!Register::isVirtualRegister(DefReg
))
2612 report("Expected first PHI operand to be a virtual register", &MODef
, 0);
2614 for (unsigned I
= 1, E
= Phi
.getNumOperands(); I
!= E
; I
+= 2) {
2615 const MachineOperand
&MO0
= Phi
.getOperand(I
);
2617 report("Expected PHI operand to be a register", &MO0
, I
);
2620 if (MO0
.isImplicit() || MO0
.isInternalRead() || MO0
.isEarlyClobber() ||
2621 MO0
.isDebug() || MO0
.isTied())
2622 report("Unexpected flag on PHI operand", &MO0
, I
);
2624 const MachineOperand
&MO1
= Phi
.getOperand(I
+ 1);
2626 report("Expected PHI operand to be a basic block", &MO1
, I
+ 1);
2630 const MachineBasicBlock
&Pre
= *MO1
.getMBB();
2631 if (!Pre
.isSuccessor(&MBB
)) {
2632 report("PHI input is not a predecessor block", &MO1
, I
+ 1);
2636 if (MInfo
.reachable
) {
2638 BBInfo
&PrInfo
= MBBInfoMap
[&Pre
];
2639 if (!MO0
.isUndef() && PrInfo
.reachable
&&
2640 !PrInfo
.isLiveOut(MO0
.getReg()))
2641 report("PHI operand is not live-out from predecessor", &MO0
, I
);
2645 // Did we see all predecessors?
2646 if (MInfo
.reachable
) {
2647 for (MachineBasicBlock
*Pred
: MBB
.predecessors()) {
2648 if (!seen
.count(Pred
)) {
2649 report("Missing PHI operand", &Phi
);
2650 errs() << printMBBReference(*Pred
)
2651 << " is a predecessor according to the CFG.\n";
2658 void MachineVerifier::visitMachineFunctionAfter() {
2661 for (const MachineBasicBlock
&MBB
: *MF
)
2664 // Now check liveness info if available
2667 // Check for killed virtual registers that should be live out.
2668 for (const auto &MBB
: *MF
) {
2669 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
2670 for (Register VReg
: MInfo
.vregsRequired
)
2671 if (MInfo
.regsKilled
.count(VReg
)) {
2672 report("Virtual register killed in block, but needed live out.", &MBB
);
2673 errs() << "Virtual register " << printReg(VReg
)
2674 << " is used after the block.\n";
2679 BBInfo
&MInfo
= MBBInfoMap
[&MF
->front()];
2680 for (Register VReg
: MInfo
.vregsRequired
) {
2681 report("Virtual register defs don't dominate all uses.", MF
);
2682 report_context_vreg(VReg
);
2687 verifyLiveVariables();
2689 verifyLiveIntervals();
2691 // Check live-in list of each MBB. If a register is live into MBB, check
2692 // that the register is in regsLiveOut of each predecessor block. Since
2693 // this must come from a definition in the predecesssor or its live-in
2694 // list, this will catch a live-through case where the predecessor does not
2695 // have the register in its live-in list. This currently only checks
2696 // registers that have no aliases, are not allocatable and are not
2697 // reserved, which could mean a condition code register for instance.
2698 if (MRI
->tracksLiveness())
2699 for (const auto &MBB
: *MF
)
2700 for (MachineBasicBlock::RegisterMaskPair P
: MBB
.liveins()) {
2701 MCPhysReg LiveInReg
= P
.PhysReg
;
2702 bool hasAliases
= MCRegAliasIterator(LiveInReg
, TRI
, false).isValid();
2703 if (hasAliases
|| isAllocatable(LiveInReg
) || isReserved(LiveInReg
))
2705 for (const MachineBasicBlock
*Pred
: MBB
.predecessors()) {
2706 BBInfo
&PInfo
= MBBInfoMap
[Pred
];
2707 if (!PInfo
.regsLiveOut
.count(LiveInReg
)) {
2708 report("Live in register not found to be live out from predecessor.",
2710 errs() << TRI
->getName(LiveInReg
)
2711 << " not found to be live out from "
2712 << printMBBReference(*Pred
) << "\n";
2717 for (auto CSInfo
: MF
->getCallSitesInfo())
2718 if (!CSInfo
.first
->isCall())
2719 report("Call site info referencing instruction that is not call", MF
);
2721 // If there's debug-info, check that we don't have any duplicate value
2722 // tracking numbers.
2723 if (MF
->getFunction().getSubprogram()) {
2724 DenseSet
<unsigned> SeenNumbers
;
2725 for (auto &MBB
: *MF
) {
2726 for (auto &MI
: MBB
) {
2727 if (auto Num
= MI
.peekDebugInstrNum()) {
2728 auto Result
= SeenNumbers
.insert((unsigned)Num
);
2730 report("Instruction has a duplicated value tracking number", &MI
);
2737 void MachineVerifier::verifyLiveVariables() {
2738 assert(LiveVars
&& "Don't call verifyLiveVariables without LiveVars");
2739 for (unsigned I
= 0, E
= MRI
->getNumVirtRegs(); I
!= E
; ++I
) {
2740 Register Reg
= Register::index2VirtReg(I
);
2741 LiveVariables::VarInfo
&VI
= LiveVars
->getVarInfo(Reg
);
2742 for (const auto &MBB
: *MF
) {
2743 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
2745 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
2746 if (MInfo
.vregsRequired
.count(Reg
)) {
2747 if (!VI
.AliveBlocks
.test(MBB
.getNumber())) {
2748 report("LiveVariables: Block missing from AliveBlocks", &MBB
);
2749 errs() << "Virtual register " << printReg(Reg
)
2750 << " must be live through the block.\n";
2753 if (VI
.AliveBlocks
.test(MBB
.getNumber())) {
2754 report("LiveVariables: Block should not be in AliveBlocks", &MBB
);
2755 errs() << "Virtual register " << printReg(Reg
)
2756 << " is not needed live through the block.\n";
2763 void MachineVerifier::verifyLiveIntervals() {
2764 assert(LiveInts
&& "Don't call verifyLiveIntervals without LiveInts");
2765 for (unsigned I
= 0, E
= MRI
->getNumVirtRegs(); I
!= E
; ++I
) {
2766 Register Reg
= Register::index2VirtReg(I
);
2768 // Spilling and splitting may leave unused registers around. Skip them.
2769 if (MRI
->reg_nodbg_empty(Reg
))
2772 if (!LiveInts
->hasInterval(Reg
)) {
2773 report("Missing live interval for virtual register", MF
);
2774 errs() << printReg(Reg
, TRI
) << " still has defs or uses\n";
2778 const LiveInterval
&LI
= LiveInts
->getInterval(Reg
);
2779 assert(Reg
== LI
.reg() && "Invalid reg to interval mapping");
2780 verifyLiveInterval(LI
);
2783 // Verify all the cached regunit intervals.
2784 for (unsigned i
= 0, e
= TRI
->getNumRegUnits(); i
!= e
; ++i
)
2785 if (const LiveRange
*LR
= LiveInts
->getCachedRegUnit(i
))
2786 verifyLiveRange(*LR
, i
);
2789 void MachineVerifier::verifyLiveRangeValue(const LiveRange
&LR
,
2790 const VNInfo
*VNI
, Register Reg
,
2791 LaneBitmask LaneMask
) {
2792 if (VNI
->isUnused())
2795 const VNInfo
*DefVNI
= LR
.getVNInfoAt(VNI
->def
);
2798 report("Value not live at VNInfo def and not marked unused", MF
);
2799 report_context(LR
, Reg
, LaneMask
);
2800 report_context(*VNI
);
2804 if (DefVNI
!= VNI
) {
2805 report("Live segment at def has different VNInfo", MF
);
2806 report_context(LR
, Reg
, LaneMask
);
2807 report_context(*VNI
);
2811 const MachineBasicBlock
*MBB
= LiveInts
->getMBBFromIndex(VNI
->def
);
2813 report("Invalid VNInfo definition index", MF
);
2814 report_context(LR
, Reg
, LaneMask
);
2815 report_context(*VNI
);
2819 if (VNI
->isPHIDef()) {
2820 if (VNI
->def
!= LiveInts
->getMBBStartIdx(MBB
)) {
2821 report("PHIDef VNInfo is not defined at MBB start", MBB
);
2822 report_context(LR
, Reg
, LaneMask
);
2823 report_context(*VNI
);
2829 const MachineInstr
*MI
= LiveInts
->getInstructionFromIndex(VNI
->def
);
2831 report("No instruction at VNInfo def index", MBB
);
2832 report_context(LR
, Reg
, LaneMask
);
2833 report_context(*VNI
);
2838 bool hasDef
= false;
2839 bool isEarlyClobber
= false;
2840 for (ConstMIBundleOperands
MOI(*MI
); MOI
.isValid(); ++MOI
) {
2841 if (!MOI
->isReg() || !MOI
->isDef())
2843 if (Register::isVirtualRegister(Reg
)) {
2844 if (MOI
->getReg() != Reg
)
2847 if (!Register::isPhysicalRegister(MOI
->getReg()) ||
2848 !TRI
->hasRegUnit(MOI
->getReg(), Reg
))
2851 if (LaneMask
.any() &&
2852 (TRI
->getSubRegIndexLaneMask(MOI
->getSubReg()) & LaneMask
).none())
2855 if (MOI
->isEarlyClobber())
2856 isEarlyClobber
= true;
2860 report("Defining instruction does not modify register", MI
);
2861 report_context(LR
, Reg
, LaneMask
);
2862 report_context(*VNI
);
2865 // Early clobber defs begin at USE slots, but other defs must begin at
2867 if (isEarlyClobber
) {
2868 if (!VNI
->def
.isEarlyClobber()) {
2869 report("Early clobber def must be at an early-clobber slot", MBB
);
2870 report_context(LR
, Reg
, LaneMask
);
2871 report_context(*VNI
);
2873 } else if (!VNI
->def
.isRegister()) {
2874 report("Non-PHI, non-early clobber def must be at a register slot", MBB
);
2875 report_context(LR
, Reg
, LaneMask
);
2876 report_context(*VNI
);
2881 void MachineVerifier::verifyLiveRangeSegment(const LiveRange
&LR
,
2882 const LiveRange::const_iterator I
,
2884 LaneBitmask LaneMask
) {
2885 const LiveRange::Segment
&S
= *I
;
2886 const VNInfo
*VNI
= S
.valno
;
2887 assert(VNI
&& "Live segment has no valno");
2889 if (VNI
->id
>= LR
.getNumValNums() || VNI
!= LR
.getValNumInfo(VNI
->id
)) {
2890 report("Foreign valno in live segment", MF
);
2891 report_context(LR
, Reg
, LaneMask
);
2893 report_context(*VNI
);
2896 if (VNI
->isUnused()) {
2897 report("Live segment valno is marked unused", MF
);
2898 report_context(LR
, Reg
, LaneMask
);
2902 const MachineBasicBlock
*MBB
= LiveInts
->getMBBFromIndex(S
.start
);
2904 report("Bad start of live segment, no basic block", MF
);
2905 report_context(LR
, Reg
, LaneMask
);
2909 SlotIndex MBBStartIdx
= LiveInts
->getMBBStartIdx(MBB
);
2910 if (S
.start
!= MBBStartIdx
&& S
.start
!= VNI
->def
) {
2911 report("Live segment must begin at MBB entry or valno def", MBB
);
2912 report_context(LR
, Reg
, LaneMask
);
2916 const MachineBasicBlock
*EndMBB
=
2917 LiveInts
->getMBBFromIndex(S
.end
.getPrevSlot());
2919 report("Bad end of live segment, no basic block", MF
);
2920 report_context(LR
, Reg
, LaneMask
);
2925 // No more checks for live-out segments.
2926 if (S
.end
== LiveInts
->getMBBEndIdx(EndMBB
))
2929 // RegUnit intervals are allowed dead phis.
2930 if (!Register::isVirtualRegister(Reg
) && VNI
->isPHIDef() &&
2931 S
.start
== VNI
->def
&& S
.end
== VNI
->def
.getDeadSlot())
2934 // The live segment is ending inside EndMBB
2935 const MachineInstr
*MI
=
2936 LiveInts
->getInstructionFromIndex(S
.end
.getPrevSlot());
2938 report("Live segment doesn't end at a valid instruction", EndMBB
);
2939 report_context(LR
, Reg
, LaneMask
);
2944 // The block slot must refer to a basic block boundary.
2945 if (S
.end
.isBlock()) {
2946 report("Live segment ends at B slot of an instruction", EndMBB
);
2947 report_context(LR
, Reg
, LaneMask
);
2951 if (S
.end
.isDead()) {
2952 // Segment ends on the dead slot.
2953 // That means there must be a dead def.
2954 if (!SlotIndex::isSameInstr(S
.start
, S
.end
)) {
2955 report("Live segment ending at dead slot spans instructions", EndMBB
);
2956 report_context(LR
, Reg
, LaneMask
);
2961 // A live segment can only end at an early-clobber slot if it is being
2962 // redefined by an early-clobber def.
2963 if (S
.end
.isEarlyClobber()) {
2964 if (I
+1 == LR
.end() || (I
+1)->start
!= S
.end
) {
2965 report("Live segment ending at early clobber slot must be "
2966 "redefined by an EC def in the same instruction", EndMBB
);
2967 report_context(LR
, Reg
, LaneMask
);
2972 // The following checks only apply to virtual registers. Physreg liveness
2973 // is too weird to check.
2974 if (Register::isVirtualRegister(Reg
)) {
2975 // A live segment can end with either a redefinition, a kill flag on a
2976 // use, or a dead flag on a def.
2977 bool hasRead
= false;
2978 bool hasSubRegDef
= false;
2979 bool hasDeadDef
= false;
2980 for (ConstMIBundleOperands
MOI(*MI
); MOI
.isValid(); ++MOI
) {
2981 if (!MOI
->isReg() || MOI
->getReg() != Reg
)
2983 unsigned Sub
= MOI
->getSubReg();
2984 LaneBitmask SLM
= Sub
!= 0 ? TRI
->getSubRegIndexLaneMask(Sub
)
2985 : LaneBitmask::getAll();
2988 hasSubRegDef
= true;
2989 // An operand %0:sub0 reads %0:sub1..n. Invert the lane
2990 // mask for subregister defs. Read-undef defs will be handled by
2997 if (LaneMask
.any() && (LaneMask
& SLM
).none())
2999 if (MOI
->readsReg())
3002 if (S
.end
.isDead()) {
3003 // Make sure that the corresponding machine operand for a "dead" live
3004 // range has the dead flag. We cannot perform this check for subregister
3005 // liveranges as partially dead values are allowed.
3006 if (LaneMask
.none() && !hasDeadDef
) {
3007 report("Instruction ending live segment on dead slot has no dead flag",
3009 report_context(LR
, Reg
, LaneMask
);
3014 // When tracking subregister liveness, the main range must start new
3015 // values on partial register writes, even if there is no read.
3016 if (!MRI
->shouldTrackSubRegLiveness(Reg
) || LaneMask
.any() ||
3018 report("Instruction ending live segment doesn't read the register",
3020 report_context(LR
, Reg
, LaneMask
);
3027 // Now check all the basic blocks in this live segment.
3028 MachineFunction::const_iterator MFI
= MBB
->getIterator();
3029 // Is this live segment the beginning of a non-PHIDef VN?
3030 if (S
.start
== VNI
->def
&& !VNI
->isPHIDef()) {
3031 // Not live-in to any blocks.
3038 SmallVector
<SlotIndex
, 4> Undefs
;
3039 if (LaneMask
.any()) {
3040 LiveInterval
&OwnerLI
= LiveInts
->getInterval(Reg
);
3041 OwnerLI
.computeSubRangeUndefs(Undefs
, LaneMask
, *MRI
, *Indexes
);
3045 assert(LiveInts
->isLiveInToMBB(LR
, &*MFI
));
3046 // We don't know how to track physregs into a landing pad.
3047 if (!Register::isVirtualRegister(Reg
) && MFI
->isEHPad()) {
3048 if (&*MFI
== EndMBB
)
3054 // Is VNI a PHI-def in the current block?
3055 bool IsPHI
= VNI
->isPHIDef() &&
3056 VNI
->def
== LiveInts
->getMBBStartIdx(&*MFI
);
3058 // Check that VNI is live-out of all predecessors.
3059 for (const MachineBasicBlock
*Pred
: MFI
->predecessors()) {
3060 SlotIndex PEnd
= LiveInts
->getMBBEndIdx(Pred
);
3061 // Predecessor of landing pad live-out on last call.
3062 if (MFI
->isEHPad()) {
3063 for (auto I
= Pred
->rbegin(), E
= Pred
->rend(); I
!= E
; ++I
) {
3065 PEnd
= Indexes
->getInstructionIndex(*I
).getBoundaryIndex();
3070 const VNInfo
*PVNI
= LR
.getVNInfoBefore(PEnd
);
3072 // All predecessors must have a live-out value. However for a phi
3073 // instruction with subregister intervals
3074 // only one of the subregisters (not necessarily the current one) needs to
3076 if (!PVNI
&& (LaneMask
.none() || !IsPHI
)) {
3077 if (LiveRangeCalc::isJointlyDominated(Pred
, Undefs
, *Indexes
))
3079 report("Register not marked live out of predecessor", Pred
);
3080 report_context(LR
, Reg
, LaneMask
);
3081 report_context(*VNI
);
3082 errs() << " live into " << printMBBReference(*MFI
) << '@'
3083 << LiveInts
->getMBBStartIdx(&*MFI
) << ", not live before "
3088 // Only PHI-defs can take different predecessor values.
3089 if (!IsPHI
&& PVNI
!= VNI
) {
3090 report("Different value live out of predecessor", Pred
);
3091 report_context(LR
, Reg
, LaneMask
);
3092 errs() << "Valno #" << PVNI
->id
<< " live out of "
3093 << printMBBReference(*Pred
) << '@' << PEnd
<< "\nValno #"
3094 << VNI
->id
<< " live into " << printMBBReference(*MFI
) << '@'
3095 << LiveInts
->getMBBStartIdx(&*MFI
) << '\n';
3098 if (&*MFI
== EndMBB
)
3104 void MachineVerifier::verifyLiveRange(const LiveRange
&LR
, Register Reg
,
3105 LaneBitmask LaneMask
) {
3106 for (const VNInfo
*VNI
: LR
.valnos
)
3107 verifyLiveRangeValue(LR
, VNI
, Reg
, LaneMask
);
3109 for (LiveRange::const_iterator I
= LR
.begin(), E
= LR
.end(); I
!= E
; ++I
)
3110 verifyLiveRangeSegment(LR
, I
, Reg
, LaneMask
);
3113 void MachineVerifier::verifyLiveInterval(const LiveInterval
&LI
) {
3114 Register Reg
= LI
.reg();
3115 assert(Register::isVirtualRegister(Reg
));
3116 verifyLiveRange(LI
, Reg
);
3119 LaneBitmask MaxMask
= MRI
->getMaxLaneMaskForVReg(Reg
);
3120 for (const LiveInterval::SubRange
&SR
: LI
.subranges()) {
3121 if ((Mask
& SR
.LaneMask
).any()) {
3122 report("Lane masks of sub ranges overlap in live interval", MF
);
3125 if ((SR
.LaneMask
& ~MaxMask
).any()) {
3126 report("Subrange lanemask is invalid", MF
);
3130 report("Subrange must not be empty", MF
);
3131 report_context(SR
, LI
.reg(), SR
.LaneMask
);
3133 Mask
|= SR
.LaneMask
;
3134 verifyLiveRange(SR
, LI
.reg(), SR
.LaneMask
);
3135 if (!LI
.covers(SR
)) {
3136 report("A Subrange is not covered by the main range", MF
);
3141 // Check the LI only has one connected component.
3142 ConnectedVNInfoEqClasses
ConEQ(*LiveInts
);
3143 unsigned NumComp
= ConEQ
.Classify(LI
);
3145 report("Multiple connected components in live interval", MF
);
3147 for (unsigned comp
= 0; comp
!= NumComp
; ++comp
) {
3148 errs() << comp
<< ": valnos";
3149 for (const VNInfo
*I
: LI
.valnos
)
3150 if (comp
== ConEQ
.getEqClass(I
))
3151 errs() << ' ' << I
->id
;
3159 // FrameSetup and FrameDestroy can have zero adjustment, so using a single
3160 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
3162 // We use a bool plus an integer to capture the stack state.
3163 struct StackStateOfBB
{
3164 StackStateOfBB() = default;
3165 StackStateOfBB(int EntryVal
, int ExitVal
, bool EntrySetup
, bool ExitSetup
) :
3166 EntryValue(EntryVal
), ExitValue(ExitVal
), EntryIsSetup(EntrySetup
),
3167 ExitIsSetup(ExitSetup
) {}
3169 // Can be negative, which means we are setting up a frame.
3172 bool EntryIsSetup
= false;
3173 bool ExitIsSetup
= false;
3176 } // end anonymous namespace
3178 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
3179 /// by a FrameDestroy <n>, stack adjustments are identical on all
3180 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
3181 void MachineVerifier::verifyStackFrame() {
3182 unsigned FrameSetupOpcode
= TII
->getCallFrameSetupOpcode();
3183 unsigned FrameDestroyOpcode
= TII
->getCallFrameDestroyOpcode();
3184 if (FrameSetupOpcode
== ~0u && FrameDestroyOpcode
== ~0u)
3187 SmallVector
<StackStateOfBB
, 8> SPState
;
3188 SPState
.resize(MF
->getNumBlockIDs());
3189 df_iterator_default_set
<const MachineBasicBlock
*> Reachable
;
3191 // Visit the MBBs in DFS order.
3192 for (df_ext_iterator
<const MachineFunction
*,
3193 df_iterator_default_set
<const MachineBasicBlock
*>>
3194 DFI
= df_ext_begin(MF
, Reachable
), DFE
= df_ext_end(MF
, Reachable
);
3195 DFI
!= DFE
; ++DFI
) {
3196 const MachineBasicBlock
*MBB
= *DFI
;
3198 StackStateOfBB BBState
;
3199 // Check the exit state of the DFS stack predecessor.
3200 if (DFI
.getPathLength() >= 2) {
3201 const MachineBasicBlock
*StackPred
= DFI
.getPath(DFI
.getPathLength() - 2);
3202 assert(Reachable
.count(StackPred
) &&
3203 "DFS stack predecessor is already visited.\n");
3204 BBState
.EntryValue
= SPState
[StackPred
->getNumber()].ExitValue
;
3205 BBState
.EntryIsSetup
= SPState
[StackPred
->getNumber()].ExitIsSetup
;
3206 BBState
.ExitValue
= BBState
.EntryValue
;
3207 BBState
.ExitIsSetup
= BBState
.EntryIsSetup
;
3210 // Update stack state by checking contents of MBB.
3211 for (const auto &I
: *MBB
) {
3212 if (I
.getOpcode() == FrameSetupOpcode
) {
3213 if (BBState
.ExitIsSetup
)
3214 report("FrameSetup is after another FrameSetup", &I
);
3215 BBState
.ExitValue
-= TII
->getFrameTotalSize(I
);
3216 BBState
.ExitIsSetup
= true;
3219 if (I
.getOpcode() == FrameDestroyOpcode
) {
3220 int Size
= TII
->getFrameTotalSize(I
);
3221 if (!BBState
.ExitIsSetup
)
3222 report("FrameDestroy is not after a FrameSetup", &I
);
3223 int AbsSPAdj
= BBState
.ExitValue
< 0 ? -BBState
.ExitValue
:
3225 if (BBState
.ExitIsSetup
&& AbsSPAdj
!= Size
) {
3226 report("FrameDestroy <n> is after FrameSetup <m>", &I
);
3227 errs() << "FrameDestroy <" << Size
<< "> is after FrameSetup <"
3228 << AbsSPAdj
<< ">.\n";
3230 BBState
.ExitValue
+= Size
;
3231 BBState
.ExitIsSetup
= false;
3234 SPState
[MBB
->getNumber()] = BBState
;
3236 // Make sure the exit state of any predecessor is consistent with the entry
3238 for (const MachineBasicBlock
*Pred
: MBB
->predecessors()) {
3239 if (Reachable
.count(Pred
) &&
3240 (SPState
[Pred
->getNumber()].ExitValue
!= BBState
.EntryValue
||
3241 SPState
[Pred
->getNumber()].ExitIsSetup
!= BBState
.EntryIsSetup
)) {
3242 report("The exit stack state of a predecessor is inconsistent.", MBB
);
3243 errs() << "Predecessor " << printMBBReference(*Pred
)
3244 << " has exit state (" << SPState
[Pred
->getNumber()].ExitValue
3245 << ", " << SPState
[Pred
->getNumber()].ExitIsSetup
<< "), while "
3246 << printMBBReference(*MBB
) << " has entry state ("
3247 << BBState
.EntryValue
<< ", " << BBState
.EntryIsSetup
<< ").\n";
3251 // Make sure the entry state of any successor is consistent with the exit
3253 for (const MachineBasicBlock
*Succ
: MBB
->successors()) {
3254 if (Reachable
.count(Succ
) &&
3255 (SPState
[Succ
->getNumber()].EntryValue
!= BBState
.ExitValue
||
3256 SPState
[Succ
->getNumber()].EntryIsSetup
!= BBState
.ExitIsSetup
)) {
3257 report("The entry stack state of a successor is inconsistent.", MBB
);
3258 errs() << "Successor " << printMBBReference(*Succ
)
3259 << " has entry state (" << SPState
[Succ
->getNumber()].EntryValue
3260 << ", " << SPState
[Succ
->getNumber()].EntryIsSetup
<< "), while "
3261 << printMBBReference(*MBB
) << " has exit state ("
3262 << BBState
.ExitValue
<< ", " << BBState
.ExitIsSetup
<< ").\n";
3266 // Make sure a basic block with return ends with zero stack adjustment.
3267 if (!MBB
->empty() && MBB
->back().isReturn()) {
3268 if (BBState
.ExitIsSetup
)
3269 report("A return block ends with a FrameSetup.", MBB
);
3270 if (BBState
.ExitValue
)
3271 report("A return block ends with a nonzero stack adjustment.", MBB
);