1 //===- MachineVerifier.cpp - Machine Code Verifier ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Pass to verify generated machine code. The following is checked:
12 // Operand counts: All explicit operands must be present.
14 // Register classes: All physical and virtual register operands must be
15 // compatible with the register class required by the instruction descriptor.
17 // Register live intervals: Registers must be defined only once, and must be
18 // defined before use.
20 // The machine code verifier is enabled from LLVMTargetMachine.cpp with the
21 // command-line option -verify-machineinstrs, or by defining the environment
22 // variable LLVM_VERIFY_MACHINEINSTRS to the name of a file that will receive
23 // the verifier errors.
24 //===----------------------------------------------------------------------===//
26 #include "LiveRangeCalc.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/DepthFirstIterator.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SetOperations.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/Twine.h"
37 #include "llvm/Analysis/EHPersonalities.h"
38 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
39 #include "llvm/CodeGen/LiveInterval.h"
40 #include "llvm/CodeGen/LiveIntervals.h"
41 #include "llvm/CodeGen/LiveStacks.h"
42 #include "llvm/CodeGen/LiveVariables.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineFunctionPass.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBundle.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/PseudoSourceValue.h"
53 #include "llvm/CodeGen/SlotIndexes.h"
54 #include "llvm/CodeGen/StackMaps.h"
55 #include "llvm/CodeGen/TargetInstrInfo.h"
56 #include "llvm/CodeGen/TargetOpcodes.h"
57 #include "llvm/CodeGen/TargetRegisterInfo.h"
58 #include "llvm/CodeGen/TargetSubtargetInfo.h"
59 #include "llvm/IR/BasicBlock.h"
60 #include "llvm/IR/Function.h"
61 #include "llvm/IR/InlineAsm.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/MC/LaneBitmask.h"
64 #include "llvm/MC/MCAsmInfo.h"
65 #include "llvm/MC/MCInstrDesc.h"
66 #include "llvm/MC/MCRegisterInfo.h"
67 #include "llvm/MC/MCTargetOptions.h"
68 #include "llvm/Pass.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/LowLevelTypeImpl.h"
72 #include "llvm/Support/MathExtras.h"
73 #include "llvm/Support/raw_ostream.h"
74 #include "llvm/Target/TargetMachine.h"
87 struct MachineVerifier
{
88 MachineVerifier(Pass
*pass
, const char *b
) : PASS(pass
), Banner(b
) {}
90 unsigned verify(MachineFunction
&MF
);
94 const MachineFunction
*MF
;
95 const TargetMachine
*TM
;
96 const TargetInstrInfo
*TII
;
97 const TargetRegisterInfo
*TRI
;
98 const MachineRegisterInfo
*MRI
;
100 unsigned foundErrors
;
102 // Avoid querying the MachineFunctionProperties for each operand.
103 bool isFunctionRegBankSelected
;
104 bool isFunctionSelected
;
106 using RegVector
= SmallVector
<unsigned, 16>;
107 using RegMaskVector
= SmallVector
<const uint32_t *, 4>;
108 using RegSet
= DenseSet
<unsigned>;
109 using RegMap
= DenseMap
<unsigned, const MachineInstr
*>;
110 using BlockSet
= SmallPtrSet
<const MachineBasicBlock
*, 8>;
112 const MachineInstr
*FirstNonPHI
;
113 const MachineInstr
*FirstTerminator
;
114 BlockSet FunctionBlocks
;
116 BitVector regsReserved
;
118 RegVector regsDefined
, regsDead
, regsKilled
;
119 RegMaskVector regMasks
;
123 // Add Reg and any sub-registers to RV
124 void addRegWithSubRegs(RegVector
&RV
, unsigned Reg
) {
126 if (TargetRegisterInfo::isPhysicalRegister(Reg
))
127 for (MCSubRegIterator
SubRegs(Reg
, TRI
); SubRegs
.isValid(); ++SubRegs
)
128 RV
.push_back(*SubRegs
);
132 // Is this MBB reachable from the MF entry point?
133 bool reachable
= false;
135 // Vregs that must be live in because they are used without being
136 // defined. Map value is the user.
139 // Regs killed in MBB. They may be defined again, and will then be in both
140 // regsKilled and regsLiveOut.
143 // Regs defined in MBB and live out. Note that vregs passing through may
144 // be live out without being mentioned here.
147 // Vregs that pass through MBB untouched. This set is disjoint from
148 // regsKilled and regsLiveOut.
151 // Vregs that must pass through MBB because they are needed by a successor
152 // block. This set is disjoint from regsLiveOut.
153 RegSet vregsRequired
;
155 // Set versions of block's predecessor and successor lists.
156 BlockSet Preds
, Succs
;
160 // Add register to vregsPassed if it belongs there. Return true if
162 bool addPassed(unsigned Reg
) {
163 if (!TargetRegisterInfo::isVirtualRegister(Reg
))
165 if (regsKilled
.count(Reg
) || regsLiveOut
.count(Reg
))
167 return vregsPassed
.insert(Reg
).second
;
170 // Same for a full set.
171 bool addPassed(const RegSet
&RS
) {
172 bool changed
= false;
173 for (RegSet::const_iterator I
= RS
.begin(), E
= RS
.end(); I
!= E
; ++I
)
179 // Add register to vregsRequired if it belongs there. Return true if
181 bool addRequired(unsigned Reg
) {
182 if (!TargetRegisterInfo::isVirtualRegister(Reg
))
184 if (regsLiveOut
.count(Reg
))
186 return vregsRequired
.insert(Reg
).second
;
189 // Same for a full set.
190 bool addRequired(const RegSet
&RS
) {
191 bool changed
= false;
192 for (RegSet::const_iterator I
= RS
.begin(), E
= RS
.end(); I
!= E
; ++I
)
198 // Same for a full map.
199 bool addRequired(const RegMap
&RM
) {
200 bool changed
= false;
201 for (RegMap::const_iterator I
= RM
.begin(), E
= RM
.end(); I
!= E
; ++I
)
202 if (addRequired(I
->first
))
207 // Live-out registers are either in regsLiveOut or vregsPassed.
208 bool isLiveOut(unsigned Reg
) const {
209 return regsLiveOut
.count(Reg
) || vregsPassed
.count(Reg
);
213 // Extra register info per MBB.
214 DenseMap
<const MachineBasicBlock
*, BBInfo
> MBBInfoMap
;
216 bool isReserved(unsigned Reg
) {
217 return Reg
< regsReserved
.size() && regsReserved
.test(Reg
);
220 bool isAllocatable(unsigned Reg
) const {
221 return Reg
< TRI
->getNumRegs() && TRI
->isInAllocatableClass(Reg
) &&
222 !regsReserved
.test(Reg
);
225 // Analysis information if available
226 LiveVariables
*LiveVars
;
227 LiveIntervals
*LiveInts
;
228 LiveStacks
*LiveStks
;
229 SlotIndexes
*Indexes
;
231 void visitMachineFunctionBefore();
232 void visitMachineBasicBlockBefore(const MachineBasicBlock
*MBB
);
233 void visitMachineBundleBefore(const MachineInstr
*MI
);
234 void visitMachineInstrBefore(const MachineInstr
*MI
);
235 void visitMachineOperand(const MachineOperand
*MO
, unsigned MONum
);
236 void visitMachineInstrAfter(const MachineInstr
*MI
);
237 void visitMachineBundleAfter(const MachineInstr
*MI
);
238 void visitMachineBasicBlockAfter(const MachineBasicBlock
*MBB
);
239 void visitMachineFunctionAfter();
241 void report(const char *msg
, const MachineFunction
*MF
);
242 void report(const char *msg
, const MachineBasicBlock
*MBB
);
243 void report(const char *msg
, const MachineInstr
*MI
);
244 void report(const char *msg
, const MachineOperand
*MO
, unsigned MONum
,
245 LLT MOVRegType
= LLT
{});
247 void report_context(const LiveInterval
&LI
) const;
248 void report_context(const LiveRange
&LR
, unsigned VRegUnit
,
249 LaneBitmask LaneMask
) const;
250 void report_context(const LiveRange::Segment
&S
) const;
251 void report_context(const VNInfo
&VNI
) const;
252 void report_context(SlotIndex Pos
) const;
253 void report_context_liverange(const LiveRange
&LR
) const;
254 void report_context_lanemask(LaneBitmask LaneMask
) const;
255 void report_context_vreg(unsigned VReg
) const;
256 void report_context_vreg_regunit(unsigned VRegOrUnit
) const;
258 void verifyInlineAsm(const MachineInstr
*MI
);
260 void checkLiveness(const MachineOperand
*MO
, unsigned MONum
);
261 void checkLivenessAtUse(const MachineOperand
*MO
, unsigned MONum
,
262 SlotIndex UseIdx
, const LiveRange
&LR
, unsigned VRegOrUnit
,
263 LaneBitmask LaneMask
= LaneBitmask::getNone());
264 void checkLivenessAtDef(const MachineOperand
*MO
, unsigned MONum
,
265 SlotIndex DefIdx
, const LiveRange
&LR
, unsigned VRegOrUnit
,
266 bool SubRangeCheck
= false,
267 LaneBitmask LaneMask
= LaneBitmask::getNone());
269 void markReachable(const MachineBasicBlock
*MBB
);
270 void calcRegsPassed();
271 void checkPHIOps(const MachineBasicBlock
&MBB
);
273 void calcRegsRequired();
274 void verifyLiveVariables();
275 void verifyLiveIntervals();
276 void verifyLiveInterval(const LiveInterval
&);
277 void verifyLiveRangeValue(const LiveRange
&, const VNInfo
*, unsigned,
279 void verifyLiveRangeSegment(const LiveRange
&,
280 const LiveRange::const_iterator I
, unsigned,
282 void verifyLiveRange(const LiveRange
&, unsigned,
283 LaneBitmask LaneMask
= LaneBitmask::getNone());
285 void verifyStackFrame();
287 void verifySlotIndexes() const;
288 void verifyProperties(const MachineFunction
&MF
);
291 struct MachineVerifierPass
: public MachineFunctionPass
{
292 static char ID
; // Pass ID, replacement for typeid
294 const std::string Banner
;
296 MachineVerifierPass(std::string banner
= std::string())
297 : MachineFunctionPass(ID
), Banner(std::move(banner
)) {
298 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
301 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
302 AU
.setPreservesAll();
303 MachineFunctionPass::getAnalysisUsage(AU
);
306 bool runOnMachineFunction(MachineFunction
&MF
) override
{
307 unsigned FoundErrors
= MachineVerifier(this, Banner
.c_str()).verify(MF
);
309 report_fatal_error("Found "+Twine(FoundErrors
)+" machine code errors.");
314 } // end anonymous namespace
316 char MachineVerifierPass::ID
= 0;
318 INITIALIZE_PASS(MachineVerifierPass
, "machineverifier",
319 "Verify generated machine code", false, false)
321 FunctionPass
*llvm::createMachineVerifierPass(const std::string
&Banner
) {
322 return new MachineVerifierPass(Banner
);
325 bool MachineFunction::verify(Pass
*p
, const char *Banner
, bool AbortOnErrors
)
327 MachineFunction
&MF
= const_cast<MachineFunction
&>(*this);
328 unsigned FoundErrors
= MachineVerifier(p
, Banner
).verify(MF
);
329 if (AbortOnErrors
&& FoundErrors
)
330 report_fatal_error("Found "+Twine(FoundErrors
)+" machine code errors.");
331 return FoundErrors
== 0;
334 void MachineVerifier::verifySlotIndexes() const {
335 if (Indexes
== nullptr)
338 // Ensure the IdxMBB list is sorted by slot indexes.
340 for (SlotIndexes::MBBIndexIterator I
= Indexes
->MBBIndexBegin(),
341 E
= Indexes
->MBBIndexEnd(); I
!= E
; ++I
) {
342 assert(!Last
.isValid() || I
->first
> Last
);
347 void MachineVerifier::verifyProperties(const MachineFunction
&MF
) {
348 // If a pass has introduced virtual registers without clearing the
349 // NoVRegs property (or set it without allocating the vregs)
350 // then report an error.
351 if (MF
.getProperties().hasProperty(
352 MachineFunctionProperties::Property::NoVRegs
) &&
353 MRI
->getNumVirtRegs())
354 report("Function has NoVRegs property but there are VReg operands", &MF
);
357 unsigned MachineVerifier::verify(MachineFunction
&MF
) {
361 TM
= &MF
.getTarget();
362 TII
= MF
.getSubtarget().getInstrInfo();
363 TRI
= MF
.getSubtarget().getRegisterInfo();
364 MRI
= &MF
.getRegInfo();
366 const bool isFunctionFailedISel
= MF
.getProperties().hasProperty(
367 MachineFunctionProperties::Property::FailedISel
);
369 // If we're mid-GlobalISel and we already triggered the fallback path then
370 // it's expected that the MIR is somewhat broken but that's ok since we'll
371 // reset it and clear the FailedISel attribute in ResetMachineFunctions.
372 if (isFunctionFailedISel
)
375 isFunctionRegBankSelected
=
376 !isFunctionFailedISel
&&
377 MF
.getProperties().hasProperty(
378 MachineFunctionProperties::Property::RegBankSelected
);
379 isFunctionSelected
= !isFunctionFailedISel
&&
380 MF
.getProperties().hasProperty(
381 MachineFunctionProperties::Property::Selected
);
387 LiveInts
= PASS
->getAnalysisIfAvailable
<LiveIntervals
>();
388 // We don't want to verify LiveVariables if LiveIntervals is available.
390 LiveVars
= PASS
->getAnalysisIfAvailable
<LiveVariables
>();
391 LiveStks
= PASS
->getAnalysisIfAvailable
<LiveStacks
>();
392 Indexes
= PASS
->getAnalysisIfAvailable
<SlotIndexes
>();
397 verifyProperties(MF
);
399 visitMachineFunctionBefore();
400 for (MachineFunction::const_iterator MFI
= MF
.begin(), MFE
= MF
.end();
402 visitMachineBasicBlockBefore(&*MFI
);
403 // Keep track of the current bundle header.
404 const MachineInstr
*CurBundle
= nullptr;
405 // Do we expect the next instruction to be part of the same bundle?
406 bool InBundle
= false;
408 for (MachineBasicBlock::const_instr_iterator MBBI
= MFI
->instr_begin(),
409 MBBE
= MFI
->instr_end(); MBBI
!= MBBE
; ++MBBI
) {
410 if (MBBI
->getParent() != &*MFI
) {
411 report("Bad instruction parent pointer", &*MFI
);
412 errs() << "Instruction: " << *MBBI
;
416 // Check for consistent bundle flags.
417 if (InBundle
&& !MBBI
->isBundledWithPred())
418 report("Missing BundledPred flag, "
419 "BundledSucc was set on predecessor",
421 if (!InBundle
&& MBBI
->isBundledWithPred())
422 report("BundledPred flag is set, "
423 "but BundledSucc not set on predecessor",
426 // Is this a bundle header?
427 if (!MBBI
->isInsideBundle()) {
429 visitMachineBundleAfter(CurBundle
);
431 visitMachineBundleBefore(CurBundle
);
432 } else if (!CurBundle
)
433 report("No bundle header", &*MBBI
);
434 visitMachineInstrBefore(&*MBBI
);
435 for (unsigned I
= 0, E
= MBBI
->getNumOperands(); I
!= E
; ++I
) {
436 const MachineInstr
&MI
= *MBBI
;
437 const MachineOperand
&Op
= MI
.getOperand(I
);
438 if (Op
.getParent() != &MI
) {
439 // Make sure to use correct addOperand / RemoveOperand / ChangeTo
440 // functions when replacing operands of a MachineInstr.
441 report("Instruction has operand with wrong parent set", &MI
);
444 visitMachineOperand(&Op
, I
);
447 visitMachineInstrAfter(&*MBBI
);
449 // Was this the last bundled instruction?
450 InBundle
= MBBI
->isBundledWithSucc();
453 visitMachineBundleAfter(CurBundle
);
455 report("BundledSucc flag set on last instruction in block", &MFI
->back());
456 visitMachineBasicBlockAfter(&*MFI
);
458 visitMachineFunctionAfter();
471 void MachineVerifier::report(const char *msg
, const MachineFunction
*MF
) {
474 if (!foundErrors
++) {
476 errs() << "# " << Banner
<< '\n';
477 if (LiveInts
!= nullptr)
478 LiveInts
->print(errs());
480 MF
->print(errs(), Indexes
);
482 errs() << "*** Bad machine code: " << msg
<< " ***\n"
483 << "- function: " << MF
->getName() << "\n";
486 void MachineVerifier::report(const char *msg
, const MachineBasicBlock
*MBB
) {
488 report(msg
, MBB
->getParent());
489 errs() << "- basic block: " << printMBBReference(*MBB
) << ' '
490 << MBB
->getName() << " (" << (const void *)MBB
<< ')';
492 errs() << " [" << Indexes
->getMBBStartIdx(MBB
)
493 << ';' << Indexes
->getMBBEndIdx(MBB
) << ')';
497 void MachineVerifier::report(const char *msg
, const MachineInstr
*MI
) {
499 report(msg
, MI
->getParent());
500 errs() << "- instruction: ";
501 if (Indexes
&& Indexes
->hasIndex(*MI
))
502 errs() << Indexes
->getInstructionIndex(*MI
) << '\t';
503 MI
->print(errs(), /*SkipOpers=*/true);
506 void MachineVerifier::report(const char *msg
, const MachineOperand
*MO
,
507 unsigned MONum
, LLT MOVRegType
) {
509 report(msg
, MO
->getParent());
510 errs() << "- operand " << MONum
<< ": ";
511 MO
->print(errs(), MOVRegType
, TRI
);
515 void MachineVerifier::report_context(SlotIndex Pos
) const {
516 errs() << "- at: " << Pos
<< '\n';
519 void MachineVerifier::report_context(const LiveInterval
&LI
) const {
520 errs() << "- interval: " << LI
<< '\n';
523 void MachineVerifier::report_context(const LiveRange
&LR
, unsigned VRegUnit
,
524 LaneBitmask LaneMask
) const {
525 report_context_liverange(LR
);
526 report_context_vreg_regunit(VRegUnit
);
528 report_context_lanemask(LaneMask
);
531 void MachineVerifier::report_context(const LiveRange::Segment
&S
) const {
532 errs() << "- segment: " << S
<< '\n';
535 void MachineVerifier::report_context(const VNInfo
&VNI
) const {
536 errs() << "- ValNo: " << VNI
.id
<< " (def " << VNI
.def
<< ")\n";
539 void MachineVerifier::report_context_liverange(const LiveRange
&LR
) const {
540 errs() << "- liverange: " << LR
<< '\n';
543 void MachineVerifier::report_context_vreg(unsigned VReg
) const {
544 errs() << "- v. register: " << printReg(VReg
, TRI
) << '\n';
547 void MachineVerifier::report_context_vreg_regunit(unsigned VRegOrUnit
) const {
548 if (TargetRegisterInfo::isVirtualRegister(VRegOrUnit
)) {
549 report_context_vreg(VRegOrUnit
);
551 errs() << "- regunit: " << printRegUnit(VRegOrUnit
, TRI
) << '\n';
555 void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask
) const {
556 errs() << "- lanemask: " << PrintLaneMask(LaneMask
) << '\n';
559 void MachineVerifier::markReachable(const MachineBasicBlock
*MBB
) {
560 BBInfo
&MInfo
= MBBInfoMap
[MBB
];
561 if (!MInfo
.reachable
) {
562 MInfo
.reachable
= true;
563 for (MachineBasicBlock::const_succ_iterator SuI
= MBB
->succ_begin(),
564 SuE
= MBB
->succ_end(); SuI
!= SuE
; ++SuI
)
569 void MachineVerifier::visitMachineFunctionBefore() {
570 lastIndex
= SlotIndex();
571 regsReserved
= MRI
->reservedRegsFrozen() ? MRI
->getReservedRegs()
572 : TRI
->getReservedRegs(*MF
);
575 markReachable(&MF
->front());
577 // Build a set of the basic blocks in the function.
578 FunctionBlocks
.clear();
579 for (const auto &MBB
: *MF
) {
580 FunctionBlocks
.insert(&MBB
);
581 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
583 MInfo
.Preds
.insert(MBB
.pred_begin(), MBB
.pred_end());
584 if (MInfo
.Preds
.size() != MBB
.pred_size())
585 report("MBB has duplicate entries in its predecessor list.", &MBB
);
587 MInfo
.Succs
.insert(MBB
.succ_begin(), MBB
.succ_end());
588 if (MInfo
.Succs
.size() != MBB
.succ_size())
589 report("MBB has duplicate entries in its successor list.", &MBB
);
592 // Check that the register use lists are sane.
593 MRI
->verifyUseLists();
599 // Does iterator point to a and b as the first two elements?
600 static bool matchPair(MachineBasicBlock::const_succ_iterator i
,
601 const MachineBasicBlock
*a
, const MachineBasicBlock
*b
) {
610 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock
*MBB
) {
611 FirstTerminator
= nullptr;
612 FirstNonPHI
= nullptr;
614 if (!MF
->getProperties().hasProperty(
615 MachineFunctionProperties::Property::NoPHIs
) && MRI
->tracksLiveness()) {
616 // If this block has allocatable physical registers live-in, check that
617 // it is an entry block or landing pad.
618 for (const auto &LI
: MBB
->liveins()) {
619 if (isAllocatable(LI
.PhysReg
) && !MBB
->isEHPad() &&
620 MBB
->getIterator() != MBB
->getParent()->begin()) {
621 report("MBB has allocatable live-in, but isn't entry or landing-pad.", MBB
);
626 // Count the number of landing pad successors.
627 SmallPtrSet
<MachineBasicBlock
*, 4> LandingPadSuccs
;
628 for (MachineBasicBlock::const_succ_iterator I
= MBB
->succ_begin(),
629 E
= MBB
->succ_end(); I
!= E
; ++I
) {
631 LandingPadSuccs
.insert(*I
);
632 if (!FunctionBlocks
.count(*I
))
633 report("MBB has successor that isn't part of the function.", MBB
);
634 if (!MBBInfoMap
[*I
].Preds
.count(MBB
)) {
635 report("Inconsistent CFG", MBB
);
636 errs() << "MBB is not in the predecessor list of the successor "
637 << printMBBReference(*(*I
)) << ".\n";
641 // Check the predecessor list.
642 for (MachineBasicBlock::const_pred_iterator I
= MBB
->pred_begin(),
643 E
= MBB
->pred_end(); I
!= E
; ++I
) {
644 if (!FunctionBlocks
.count(*I
))
645 report("MBB has predecessor that isn't part of the function.", MBB
);
646 if (!MBBInfoMap
[*I
].Succs
.count(MBB
)) {
647 report("Inconsistent CFG", MBB
);
648 errs() << "MBB is not in the successor list of the predecessor "
649 << printMBBReference(*(*I
)) << ".\n";
653 const MCAsmInfo
*AsmInfo
= TM
->getMCAsmInfo();
654 const BasicBlock
*BB
= MBB
->getBasicBlock();
655 const Function
&F
= MF
->getFunction();
656 if (LandingPadSuccs
.size() > 1 &&
658 AsmInfo
->getExceptionHandlingType() == ExceptionHandling::SjLj
&&
659 BB
&& isa
<SwitchInst
>(BB
->getTerminator())) &&
660 !isScopedEHPersonality(classifyEHPersonality(F
.getPersonalityFn())))
661 report("MBB has more than one landing pad successor", MBB
);
663 // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
664 MachineBasicBlock
*TBB
= nullptr, *FBB
= nullptr;
665 SmallVector
<MachineOperand
, 4> Cond
;
666 if (!TII
->analyzeBranch(*const_cast<MachineBasicBlock
*>(MBB
), TBB
, FBB
,
668 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
669 // check whether its answers match up with reality.
671 // Block falls through to its successor.
672 MachineFunction::const_iterator MBBI
= MBB
->getIterator();
674 if (MBBI
== MF
->end()) {
675 // It's possible that the block legitimately ends with a noreturn
676 // call or an unreachable, in which case it won't actually fall
677 // out the bottom of the function.
678 } else if (MBB
->succ_size() == LandingPadSuccs
.size()) {
679 // It's possible that the block legitimately ends with a noreturn
680 // call or an unreachable, in which case it won't actuall fall
682 } else if (MBB
->succ_size() != 1+LandingPadSuccs
.size()) {
683 report("MBB exits via unconditional fall-through but doesn't have "
684 "exactly one CFG successor!", MBB
);
685 } else if (!MBB
->isSuccessor(&*MBBI
)) {
686 report("MBB exits via unconditional fall-through but its successor "
687 "differs from its CFG successor!", MBB
);
689 if (!MBB
->empty() && MBB
->back().isBarrier() &&
690 !TII
->isPredicated(MBB
->back())) {
691 report("MBB exits via unconditional fall-through but ends with a "
692 "barrier instruction!", MBB
);
695 report("MBB exits via unconditional fall-through but has a condition!",
698 } else if (TBB
&& !FBB
&& Cond
.empty()) {
699 // Block unconditionally branches somewhere.
700 // If the block has exactly one successor, that happens to be a
701 // landingpad, accept it as valid control flow.
702 if (MBB
->succ_size() != 1+LandingPadSuccs
.size() &&
703 (MBB
->succ_size() != 1 || LandingPadSuccs
.size() != 1 ||
704 *MBB
->succ_begin() != *LandingPadSuccs
.begin())) {
705 report("MBB exits via unconditional branch but doesn't have "
706 "exactly one CFG successor!", MBB
);
707 } else if (!MBB
->isSuccessor(TBB
)) {
708 report("MBB exits via unconditional branch but the CFG "
709 "successor doesn't match the actual successor!", MBB
);
712 report("MBB exits via unconditional branch but doesn't contain "
713 "any instructions!", MBB
);
714 } else if (!MBB
->back().isBarrier()) {
715 report("MBB exits via unconditional branch but doesn't end with a "
716 "barrier instruction!", MBB
);
717 } else if (!MBB
->back().isTerminator()) {
718 report("MBB exits via unconditional branch but the branch isn't a "
719 "terminator instruction!", MBB
);
721 } else if (TBB
&& !FBB
&& !Cond
.empty()) {
722 // Block conditionally branches somewhere, otherwise falls through.
723 MachineFunction::const_iterator MBBI
= MBB
->getIterator();
725 if (MBBI
== MF
->end()) {
726 report("MBB conditionally falls through out of function!", MBB
);
727 } else if (MBB
->succ_size() == 1) {
728 // A conditional branch with only one successor is weird, but allowed.
730 report("MBB exits via conditional branch/fall-through but only has "
731 "one CFG successor!", MBB
);
732 else if (TBB
!= *MBB
->succ_begin())
733 report("MBB exits via conditional branch/fall-through but the CFG "
734 "successor don't match the actual successor!", MBB
);
735 } else if (MBB
->succ_size() != 2) {
736 report("MBB exits via conditional branch/fall-through but doesn't have "
737 "exactly two CFG successors!", MBB
);
738 } else if (!matchPair(MBB
->succ_begin(), TBB
, &*MBBI
)) {
739 report("MBB exits via conditional branch/fall-through but the CFG "
740 "successors don't match the actual successors!", MBB
);
743 report("MBB exits via conditional branch/fall-through but doesn't "
744 "contain any instructions!", MBB
);
745 } else if (MBB
->back().isBarrier()) {
746 report("MBB exits via conditional branch/fall-through but ends with a "
747 "barrier instruction!", MBB
);
748 } else if (!MBB
->back().isTerminator()) {
749 report("MBB exits via conditional branch/fall-through but the branch "
750 "isn't a terminator instruction!", MBB
);
752 } else if (TBB
&& FBB
) {
753 // Block conditionally branches somewhere, otherwise branches
755 if (MBB
->succ_size() == 1) {
756 // A conditional branch with only one successor is weird, but allowed.
758 report("MBB exits via conditional branch/branch through but only has "
759 "one CFG successor!", MBB
);
760 else if (TBB
!= *MBB
->succ_begin())
761 report("MBB exits via conditional branch/branch through but the CFG "
762 "successor don't match the actual successor!", MBB
);
763 } else if (MBB
->succ_size() != 2) {
764 report("MBB exits via conditional branch/branch but doesn't have "
765 "exactly two CFG successors!", MBB
);
766 } else if (!matchPair(MBB
->succ_begin(), TBB
, FBB
)) {
767 report("MBB exits via conditional branch/branch but the CFG "
768 "successors don't match the actual successors!", MBB
);
771 report("MBB exits via conditional branch/branch but doesn't "
772 "contain any instructions!", MBB
);
773 } else if (!MBB
->back().isBarrier()) {
774 report("MBB exits via conditional branch/branch but doesn't end with a "
775 "barrier instruction!", MBB
);
776 } else if (!MBB
->back().isTerminator()) {
777 report("MBB exits via conditional branch/branch but the branch "
778 "isn't a terminator instruction!", MBB
);
781 report("MBB exits via conditinal branch/branch but there's no "
785 report("AnalyzeBranch returned invalid data!", MBB
);
790 if (MRI
->tracksLiveness()) {
791 for (const auto &LI
: MBB
->liveins()) {
792 if (!TargetRegisterInfo::isPhysicalRegister(LI
.PhysReg
)) {
793 report("MBB live-in list contains non-physical register", MBB
);
796 for (MCSubRegIterator
SubRegs(LI
.PhysReg
, TRI
, /*IncludeSelf=*/true);
797 SubRegs
.isValid(); ++SubRegs
)
798 regsLive
.insert(*SubRegs
);
802 const MachineFrameInfo
&MFI
= MF
->getFrameInfo();
803 BitVector PR
= MFI
.getPristineRegs(*MF
);
804 for (unsigned I
: PR
.set_bits()) {
805 for (MCSubRegIterator
SubRegs(I
, TRI
, /*IncludeSelf=*/true);
806 SubRegs
.isValid(); ++SubRegs
)
807 regsLive
.insert(*SubRegs
);
814 lastIndex
= Indexes
->getMBBStartIdx(MBB
);
817 // This function gets called for all bundle headers, including normal
818 // stand-alone unbundled instructions.
819 void MachineVerifier::visitMachineBundleBefore(const MachineInstr
*MI
) {
820 if (Indexes
&& Indexes
->hasIndex(*MI
)) {
821 SlotIndex idx
= Indexes
->getInstructionIndex(*MI
);
822 if (!(idx
> lastIndex
)) {
823 report("Instruction index out of order", MI
);
824 errs() << "Last instruction was at " << lastIndex
<< '\n';
829 // Ensure non-terminators don't follow terminators.
830 // Ignore predicated terminators formed by if conversion.
831 // FIXME: If conversion shouldn't need to violate this rule.
832 if (MI
->isTerminator() && !TII
->isPredicated(*MI
)) {
833 if (!FirstTerminator
)
834 FirstTerminator
= MI
;
835 } else if (FirstTerminator
) {
836 report("Non-terminator instruction after the first terminator", MI
);
837 errs() << "First terminator was:\t" << *FirstTerminator
;
841 // The operands on an INLINEASM instruction must follow a template.
842 // Verify that the flag operands make sense.
843 void MachineVerifier::verifyInlineAsm(const MachineInstr
*MI
) {
844 // The first two operands on INLINEASM are the asm string and global flags.
845 if (MI
->getNumOperands() < 2) {
846 report("Too few operands on inline asm", MI
);
849 if (!MI
->getOperand(0).isSymbol())
850 report("Asm string must be an external symbol", MI
);
851 if (!MI
->getOperand(1).isImm())
852 report("Asm flags must be an immediate", MI
);
853 // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
854 // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16,
855 // and Extra_IsConvergent = 32.
856 if (!isUInt
<6>(MI
->getOperand(1).getImm()))
857 report("Unknown asm flags", &MI
->getOperand(1), 1);
859 static_assert(InlineAsm::MIOp_FirstOperand
== 2, "Asm format changed");
861 unsigned OpNo
= InlineAsm::MIOp_FirstOperand
;
863 for (unsigned e
= MI
->getNumOperands(); OpNo
< e
; OpNo
+= NumOps
) {
864 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
865 // There may be implicit ops after the fixed operands.
868 NumOps
= 1 + InlineAsm::getNumOperandRegisters(MO
.getImm());
871 if (OpNo
> MI
->getNumOperands())
872 report("Missing operands in last group", MI
);
874 // An optional MDNode follows the groups.
875 if (OpNo
< MI
->getNumOperands() && MI
->getOperand(OpNo
).isMetadata())
878 // All trailing operands must be implicit registers.
879 for (unsigned e
= MI
->getNumOperands(); OpNo
< e
; ++OpNo
) {
880 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
881 if (!MO
.isReg() || !MO
.isImplicit())
882 report("Expected implicit register after groups", &MO
, OpNo
);
886 void MachineVerifier::visitMachineInstrBefore(const MachineInstr
*MI
) {
887 const MCInstrDesc
&MCID
= MI
->getDesc();
888 if (MI
->getNumOperands() < MCID
.getNumOperands()) {
889 report("Too few operands", MI
);
890 errs() << MCID
.getNumOperands() << " operands expected, but "
891 << MI
->getNumOperands() << " given.\n";
895 if (MF
->getProperties().hasProperty(
896 MachineFunctionProperties::Property::NoPHIs
))
897 report("Found PHI instruction with NoPHIs property set", MI
);
900 report("Found PHI instruction after non-PHI", MI
);
901 } else if (FirstNonPHI
== nullptr)
904 // Check the tied operands.
905 if (MI
->isInlineAsm())
908 // Check the MachineMemOperands for basic consistency.
909 for (MachineInstr::mmo_iterator I
= MI
->memoperands_begin(),
910 E
= MI
->memoperands_end();
912 if ((*I
)->isLoad() && !MI
->mayLoad())
913 report("Missing mayLoad flag", MI
);
914 if ((*I
)->isStore() && !MI
->mayStore())
915 report("Missing mayStore flag", MI
);
918 // Debug values must not have a slot index.
919 // Other instructions must have one, unless they are inside a bundle.
921 bool mapped
= !LiveInts
->isNotInMIMap(*MI
);
922 if (MI
->isDebugInstr()) {
924 report("Debug instruction has a slot index", MI
);
925 } else if (MI
->isInsideBundle()) {
927 report("Instruction inside bundle has a slot index", MI
);
930 report("Missing slot index", MI
);
934 if (isPreISelGenericOpcode(MCID
.getOpcode())) {
935 if (isFunctionSelected
)
936 report("Unexpected generic instruction in a Selected function", MI
);
939 SmallVector
<LLT
, 4> Types
;
940 for (unsigned I
= 0; I
< MCID
.getNumOperands(); ++I
) {
941 if (!MCID
.OpInfo
[I
].isGenericType())
943 // Generic instructions specify type equality constraints between some of
944 // their operands. Make sure these are consistent.
945 size_t TypeIdx
= MCID
.OpInfo
[I
].getGenericTypeIndex();
946 Types
.resize(std::max(TypeIdx
+ 1, Types
.size()));
948 const MachineOperand
*MO
= &MI
->getOperand(I
);
949 LLT OpTy
= MRI
->getType(MO
->getReg());
950 // Don't report a type mismatch if there is no actual mismatch, only a
951 // type missing, to reduce noise:
952 if (OpTy
.isValid()) {
953 // Only the first valid type for a type index will be printed: don't
954 // overwrite it later so it's always clear which type was expected:
955 if (!Types
[TypeIdx
].isValid())
956 Types
[TypeIdx
] = OpTy
;
957 else if (Types
[TypeIdx
] != OpTy
)
958 report("Type mismatch in generic instruction", MO
, I
, OpTy
);
960 // Generic instructions must have types attached to their operands.
961 report("Generic instruction is missing a virtual register type", MO
, I
);
965 // Generic opcodes must not have physical register operands.
966 for (unsigned I
= 0; I
< MI
->getNumOperands(); ++I
) {
967 const MachineOperand
*MO
= &MI
->getOperand(I
);
968 if (MO
->isReg() && TargetRegisterInfo::isPhysicalRegister(MO
->getReg()))
969 report("Generic instruction cannot have physical register", MO
, I
);
974 if (!TII
->verifyInstruction(*MI
, ErrorInfo
))
975 report(ErrorInfo
.data(), MI
);
977 // Verify properties of various specific instruction types
978 switch(MI
->getOpcode()) {
981 case TargetOpcode::G_LOAD
:
982 case TargetOpcode::G_STORE
:
983 // Generic loads and stores must have a single MachineMemOperand
984 // describing that access.
985 if (!MI
->hasOneMemOperand())
986 report("Generic instruction accessing memory must have one mem operand",
989 case TargetOpcode::G_PHI
: {
990 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
991 if (!DstTy
.isValid() ||
992 !std::all_of(MI
->operands_begin() + 1, MI
->operands_end(),
993 [this, &DstTy
](const MachineOperand
&MO
) {
996 LLT Ty
= MRI
->getType(MO
.getReg());
997 if (!Ty
.isValid() || (Ty
!= DstTy
))
1001 report("Generic Instruction G_PHI has operands with incompatible/missing "
1006 case TargetOpcode::G_SEXT
:
1007 case TargetOpcode::G_ZEXT
:
1008 case TargetOpcode::G_ANYEXT
:
1009 case TargetOpcode::G_TRUNC
:
1010 case TargetOpcode::G_FPEXT
:
1011 case TargetOpcode::G_FPTRUNC
: {
1012 // Number of operands and presense of types is already checked (and
1013 // reported in case of any issues), so no need to report them again. As
1014 // we're trying to report as many issues as possible at once, however, the
1015 // instructions aren't guaranteed to have the right number of operands or
1016 // types attached to them at this point
1017 assert(MCID
.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}");
1018 if (MI
->getNumOperands() < MCID
.getNumOperands())
1020 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1021 LLT SrcTy
= MRI
->getType(MI
->getOperand(1).getReg());
1022 if (!DstTy
.isValid() || !SrcTy
.isValid())
1025 LLT DstElTy
= DstTy
.isVector() ? DstTy
.getElementType() : DstTy
;
1026 LLT SrcElTy
= SrcTy
.isVector() ? SrcTy
.getElementType() : SrcTy
;
1027 if (DstElTy
.isPointer() || SrcElTy
.isPointer())
1028 report("Generic extend/truncate can not operate on pointers", MI
);
1030 if (DstTy
.isVector() != SrcTy
.isVector()) {
1031 report("Generic extend/truncate must be all-vector or all-scalar", MI
);
1032 // Generally we try to report as many issues as possible at once, but in
1033 // this case it's not clear what should we be comparing the size of the
1034 // scalar with: the size of the whole vector or its lane. Instead of
1035 // making an arbitrary choice and emitting not so helpful message, let's
1036 // avoid the extra noise and stop here.
1039 if (DstTy
.isVector() && DstTy
.getNumElements() != SrcTy
.getNumElements())
1040 report("Generic vector extend/truncate must preserve number of lanes",
1042 unsigned DstSize
= DstElTy
.getSizeInBits();
1043 unsigned SrcSize
= SrcElTy
.getSizeInBits();
1044 switch (MI
->getOpcode()) {
1046 if (DstSize
<= SrcSize
)
1047 report("Generic extend has destination type no larger than source", MI
);
1049 case TargetOpcode::G_TRUNC
:
1050 case TargetOpcode::G_FPTRUNC
:
1051 if (DstSize
>= SrcSize
)
1052 report("Generic truncate has destination type no smaller than source",
1058 case TargetOpcode::COPY
: {
1061 const MachineOperand
&DstOp
= MI
->getOperand(0);
1062 const MachineOperand
&SrcOp
= MI
->getOperand(1);
1063 LLT DstTy
= MRI
->getType(DstOp
.getReg());
1064 LLT SrcTy
= MRI
->getType(SrcOp
.getReg());
1065 if (SrcTy
.isValid() && DstTy
.isValid()) {
1066 // If both types are valid, check that the types are the same.
1067 if (SrcTy
!= DstTy
) {
1068 report("Copy Instruction is illegal with mismatching types", MI
);
1069 errs() << "Def = " << DstTy
<< ", Src = " << SrcTy
<< "\n";
1072 if (SrcTy
.isValid() || DstTy
.isValid()) {
1073 // If one of them have valid types, let's just check they have the same
1075 unsigned SrcSize
= TRI
->getRegSizeInBits(SrcOp
.getReg(), *MRI
);
1076 unsigned DstSize
= TRI
->getRegSizeInBits(DstOp
.getReg(), *MRI
);
1077 assert(SrcSize
&& "Expecting size here");
1078 assert(DstSize
&& "Expecting size here");
1079 if (SrcSize
!= DstSize
)
1080 if (!DstOp
.getSubReg() && !SrcOp
.getSubReg()) {
1081 report("Copy Instruction is illegal with mismatching sizes", MI
);
1082 errs() << "Def Size = " << DstSize
<< ", Src Size = " << SrcSize
1088 case TargetOpcode::STATEPOINT
:
1089 if (!MI
->getOperand(StatepointOpers::IDPos
).isImm() ||
1090 !MI
->getOperand(StatepointOpers::NBytesPos
).isImm() ||
1091 !MI
->getOperand(StatepointOpers::NCallArgsPos
).isImm())
1092 report("meta operands to STATEPOINT not constant!", MI
);
1095 auto VerifyStackMapConstant
= [&](unsigned Offset
) {
1096 if (!MI
->getOperand(Offset
).isImm() ||
1097 MI
->getOperand(Offset
).getImm() != StackMaps::ConstantOp
||
1098 !MI
->getOperand(Offset
+ 1).isImm())
1099 report("stack map constant to STATEPOINT not well formed!", MI
);
1101 const unsigned VarStart
= StatepointOpers(MI
).getVarIdx();
1102 VerifyStackMapConstant(VarStart
+ StatepointOpers::CCOffset
);
1103 VerifyStackMapConstant(VarStart
+ StatepointOpers::FlagsOffset
);
1104 VerifyStackMapConstant(VarStart
+ StatepointOpers::NumDeoptOperandsOffset
);
1106 // TODO: verify we have properly encoded deopt arguments
1111 MachineVerifier::visitMachineOperand(const MachineOperand
*MO
, unsigned MONum
) {
1112 const MachineInstr
*MI
= MO
->getParent();
1113 const MCInstrDesc
&MCID
= MI
->getDesc();
1114 unsigned NumDefs
= MCID
.getNumDefs();
1115 if (MCID
.getOpcode() == TargetOpcode::PATCHPOINT
)
1116 NumDefs
= (MONum
== 0 && MO
->isReg()) ? NumDefs
: 0;
1118 // The first MCID.NumDefs operands must be explicit register defines
1119 if (MONum
< NumDefs
) {
1120 const MCOperandInfo
&MCOI
= MCID
.OpInfo
[MONum
];
1122 report("Explicit definition must be a register", MO
, MONum
);
1123 else if (!MO
->isDef() && !MCOI
.isOptionalDef())
1124 report("Explicit definition marked as use", MO
, MONum
);
1125 else if (MO
->isImplicit())
1126 report("Explicit definition marked as implicit", MO
, MONum
);
1127 } else if (MONum
< MCID
.getNumOperands()) {
1128 const MCOperandInfo
&MCOI
= MCID
.OpInfo
[MONum
];
1129 // Don't check if it's the last operand in a variadic instruction. See,
1130 // e.g., LDM_RET in the arm back end.
1132 !(MI
->isVariadic() && MONum
== MCID
.getNumOperands()-1)) {
1133 if (MO
->isDef() && !MCOI
.isOptionalDef())
1134 report("Explicit operand marked as def", MO
, MONum
);
1135 if (MO
->isImplicit())
1136 report("Explicit operand marked as implicit", MO
, MONum
);
1139 int TiedTo
= MCID
.getOperandConstraint(MONum
, MCOI::TIED_TO
);
1142 report("Tied use must be a register", MO
, MONum
);
1143 else if (!MO
->isTied())
1144 report("Operand should be tied", MO
, MONum
);
1145 else if (unsigned(TiedTo
) != MI
->findTiedOperandIdx(MONum
))
1146 report("Tied def doesn't match MCInstrDesc", MO
, MONum
);
1147 else if (TargetRegisterInfo::isPhysicalRegister(MO
->getReg())) {
1148 const MachineOperand
&MOTied
= MI
->getOperand(TiedTo
);
1149 if (!MOTied
.isReg())
1150 report("Tied counterpart must be a register", &MOTied
, TiedTo
);
1151 else if (TargetRegisterInfo::isPhysicalRegister(MOTied
.getReg()) &&
1152 MO
->getReg() != MOTied
.getReg())
1153 report("Tied physical registers must match.", &MOTied
, TiedTo
);
1155 } else if (MO
->isReg() && MO
->isTied())
1156 report("Explicit operand should not be tied", MO
, MONum
);
1158 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
1159 if (MO
->isReg() && !MO
->isImplicit() && !MI
->isVariadic() && MO
->getReg())
1160 report("Extra explicit operand on non-variadic instruction", MO
, MONum
);
1163 switch (MO
->getType()) {
1164 case MachineOperand::MO_Register
: {
1165 const unsigned Reg
= MO
->getReg();
1168 if (MRI
->tracksLiveness() && !MI
->isDebugValue())
1169 checkLiveness(MO
, MONum
);
1171 // Verify the consistency of tied operands.
1173 unsigned OtherIdx
= MI
->findTiedOperandIdx(MONum
);
1174 const MachineOperand
&OtherMO
= MI
->getOperand(OtherIdx
);
1175 if (!OtherMO
.isReg())
1176 report("Must be tied to a register", MO
, MONum
);
1177 if (!OtherMO
.isTied())
1178 report("Missing tie flags on tied operand", MO
, MONum
);
1179 if (MI
->findTiedOperandIdx(OtherIdx
) != MONum
)
1180 report("Inconsistent tie links", MO
, MONum
);
1181 if (MONum
< MCID
.getNumDefs()) {
1182 if (OtherIdx
< MCID
.getNumOperands()) {
1183 if (-1 == MCID
.getOperandConstraint(OtherIdx
, MCOI::TIED_TO
))
1184 report("Explicit def tied to explicit use without tie constraint",
1187 if (!OtherMO
.isImplicit())
1188 report("Explicit def should be tied to implicit use", MO
, MONum
);
1193 // Verify two-address constraints after leaving SSA form.
1195 if (!MRI
->isSSA() && MO
->isUse() &&
1196 MI
->isRegTiedToDefOperand(MONum
, &DefIdx
) &&
1197 Reg
!= MI
->getOperand(DefIdx
).getReg())
1198 report("Two-address instruction operands must be identical", MO
, MONum
);
1200 // Check register classes.
1201 unsigned SubIdx
= MO
->getSubReg();
1203 if (TargetRegisterInfo::isPhysicalRegister(Reg
)) {
1205 report("Illegal subregister index for physical register", MO
, MONum
);
1208 if (MONum
< MCID
.getNumOperands()) {
1209 if (const TargetRegisterClass
*DRC
=
1210 TII
->getRegClass(MCID
, MONum
, TRI
, *MF
)) {
1211 if (!DRC
->contains(Reg
)) {
1212 report("Illegal physical register for instruction", MO
, MONum
);
1213 errs() << printReg(Reg
, TRI
) << " is not a "
1214 << TRI
->getRegClassName(DRC
) << " register.\n";
1218 if (MO
->isRenamable()) {
1219 if (MRI
->isReserved(Reg
)) {
1220 report("isRenamable set on reserved register", MO
, MONum
);
1224 if (MI
->isDebugValue() && MO
->isUse() && !MO
->isDebug()) {
1225 report("Use-reg is not IsDebug in a DBG_VALUE", MO
, MONum
);
1229 // Virtual register.
1230 const TargetRegisterClass
*RC
= MRI
->getRegClassOrNull(Reg
);
1232 // This is a generic virtual register.
1234 // If we're post-Select, we can't have gvregs anymore.
1235 if (isFunctionSelected
) {
1236 report("Generic virtual register invalid in a Selected function",
1241 // The gvreg must have a type and it must not have a SubIdx.
1242 LLT Ty
= MRI
->getType(Reg
);
1243 if (!Ty
.isValid()) {
1244 report("Generic virtual register must have a valid type", MO
,
1249 const RegisterBank
*RegBank
= MRI
->getRegBankOrNull(Reg
);
1251 // If we're post-RegBankSelect, the gvreg must have a bank.
1252 if (!RegBank
&& isFunctionRegBankSelected
) {
1253 report("Generic virtual register must have a bank in a "
1254 "RegBankSelected function",
1259 // Make sure the register fits into its register bank if any.
1260 if (RegBank
&& Ty
.isValid() &&
1261 RegBank
->getSize() < Ty
.getSizeInBits()) {
1262 report("Register bank is too small for virtual register", MO
,
1264 errs() << "Register bank " << RegBank
->getName() << " too small("
1265 << RegBank
->getSize() << ") to fit " << Ty
.getSizeInBits()
1270 report("Generic virtual register does not subregister index", MO
,
1275 // If this is a target specific instruction and this operand
1276 // has register class constraint, the virtual register must
1278 if (!isPreISelGenericOpcode(MCID
.getOpcode()) &&
1279 MONum
< MCID
.getNumOperands() &&
1280 TII
->getRegClass(MCID
, MONum
, TRI
, *MF
)) {
1281 report("Virtual register does not match instruction constraint", MO
,
1283 errs() << "Expect register class "
1284 << TRI
->getRegClassName(
1285 TII
->getRegClass(MCID
, MONum
, TRI
, *MF
))
1286 << " but got nothing\n";
1293 const TargetRegisterClass
*SRC
=
1294 TRI
->getSubClassWithSubReg(RC
, SubIdx
);
1296 report("Invalid subregister index for virtual register", MO
, MONum
);
1297 errs() << "Register class " << TRI
->getRegClassName(RC
)
1298 << " does not support subreg index " << SubIdx
<< "\n";
1302 report("Invalid register class for subregister index", MO
, MONum
);
1303 errs() << "Register class " << TRI
->getRegClassName(RC
)
1304 << " does not fully support subreg index " << SubIdx
<< "\n";
1308 if (MONum
< MCID
.getNumOperands()) {
1309 if (const TargetRegisterClass
*DRC
=
1310 TII
->getRegClass(MCID
, MONum
, TRI
, *MF
)) {
1312 const TargetRegisterClass
*SuperRC
=
1313 TRI
->getLargestLegalSuperClass(RC
, *MF
);
1315 report("No largest legal super class exists.", MO
, MONum
);
1318 DRC
= TRI
->getMatchingSuperRegClass(SuperRC
, DRC
, SubIdx
);
1320 report("No matching super-reg register class.", MO
, MONum
);
1324 if (!RC
->hasSuperClassEq(DRC
)) {
1325 report("Illegal virtual register for instruction", MO
, MONum
);
1326 errs() << "Expected a " << TRI
->getRegClassName(DRC
)
1327 << " register, but got a " << TRI
->getRegClassName(RC
)
1336 case MachineOperand::MO_RegisterMask
:
1337 regMasks
.push_back(MO
->getRegMask());
1340 case MachineOperand::MO_MachineBasicBlock
:
1341 if (MI
->isPHI() && !MO
->getMBB()->isSuccessor(MI
->getParent()))
1342 report("PHI operand is not in the CFG", MO
, MONum
);
1345 case MachineOperand::MO_FrameIndex
:
1346 if (LiveStks
&& LiveStks
->hasInterval(MO
->getIndex()) &&
1347 LiveInts
&& !LiveInts
->isNotInMIMap(*MI
)) {
1348 int FI
= MO
->getIndex();
1349 LiveInterval
&LI
= LiveStks
->getInterval(FI
);
1350 SlotIndex Idx
= LiveInts
->getInstructionIndex(*MI
);
1352 bool stores
= MI
->mayStore();
1353 bool loads
= MI
->mayLoad();
1354 // For a memory-to-memory move, we need to check if the frame
1355 // index is used for storing or loading, by inspecting the
1357 if (stores
&& loads
) {
1358 for (auto *MMO
: MI
->memoperands()) {
1359 const PseudoSourceValue
*PSV
= MMO
->getPseudoValue();
1360 if (PSV
== nullptr) continue;
1361 const FixedStackPseudoSourceValue
*Value
=
1362 dyn_cast
<FixedStackPseudoSourceValue
>(PSV
);
1363 if (Value
== nullptr) continue;
1364 if (Value
->getFrameIndex() != FI
) continue;
1372 if (loads
== stores
)
1373 report("Missing fixed stack memoperand.", MI
);
1375 if (loads
&& !LI
.liveAt(Idx
.getRegSlot(true))) {
1376 report("Instruction loads from dead spill slot", MO
, MONum
);
1377 errs() << "Live stack: " << LI
<< '\n';
1379 if (stores
&& !LI
.liveAt(Idx
.getRegSlot())) {
1380 report("Instruction stores to dead spill slot", MO
, MONum
);
1381 errs() << "Live stack: " << LI
<< '\n';
1391 void MachineVerifier::checkLivenessAtUse(const MachineOperand
*MO
,
1392 unsigned MONum
, SlotIndex UseIdx
, const LiveRange
&LR
, unsigned VRegOrUnit
,
1393 LaneBitmask LaneMask
) {
1394 LiveQueryResult LRQ
= LR
.Query(UseIdx
);
1395 // Check if we have a segment at the use, note however that we only need one
1396 // live subregister range, the others may be dead.
1397 if (!LRQ
.valueIn() && LaneMask
.none()) {
1398 report("No live segment at use", MO
, MONum
);
1399 report_context_liverange(LR
);
1400 report_context_vreg_regunit(VRegOrUnit
);
1401 report_context(UseIdx
);
1403 if (MO
->isKill() && !LRQ
.isKill()) {
1404 report("Live range continues after kill flag", MO
, MONum
);
1405 report_context_liverange(LR
);
1406 report_context_vreg_regunit(VRegOrUnit
);
1408 report_context_lanemask(LaneMask
);
1409 report_context(UseIdx
);
1413 void MachineVerifier::checkLivenessAtDef(const MachineOperand
*MO
,
1414 unsigned MONum
, SlotIndex DefIdx
, const LiveRange
&LR
, unsigned VRegOrUnit
,
1415 bool SubRangeCheck
, LaneBitmask LaneMask
) {
1416 if (const VNInfo
*VNI
= LR
.getVNInfoAt(DefIdx
)) {
1417 assert(VNI
&& "NULL valno is not allowed");
1418 if (VNI
->def
!= DefIdx
) {
1419 report("Inconsistent valno->def", MO
, MONum
);
1420 report_context_liverange(LR
);
1421 report_context_vreg_regunit(VRegOrUnit
);
1423 report_context_lanemask(LaneMask
);
1424 report_context(*VNI
);
1425 report_context(DefIdx
);
1428 report("No live segment at def", MO
, MONum
);
1429 report_context_liverange(LR
);
1430 report_context_vreg_regunit(VRegOrUnit
);
1432 report_context_lanemask(LaneMask
);
1433 report_context(DefIdx
);
1435 // Check that, if the dead def flag is present, LiveInts agree.
1437 LiveQueryResult LRQ
= LR
.Query(DefIdx
);
1438 if (!LRQ
.isDeadDef()) {
1439 assert(TargetRegisterInfo::isVirtualRegister(VRegOrUnit
) &&
1440 "Expecting a virtual register.");
1441 // A dead subreg def only tells us that the specific subreg is dead. There
1442 // could be other non-dead defs of other subregs, or we could have other
1443 // parts of the register being live through the instruction. So unless we
1444 // are checking liveness for a subrange it is ok for the live range to
1445 // continue, given that we have a dead def of a subregister.
1446 if (SubRangeCheck
|| MO
->getSubReg() == 0) {
1447 report("Live range continues after dead def flag", MO
, MONum
);
1448 report_context_liverange(LR
);
1449 report_context_vreg_regunit(VRegOrUnit
);
1451 report_context_lanemask(LaneMask
);
1457 void MachineVerifier::checkLiveness(const MachineOperand
*MO
, unsigned MONum
) {
1458 const MachineInstr
*MI
= MO
->getParent();
1459 const unsigned Reg
= MO
->getReg();
1461 // Both use and def operands can read a register.
1462 if (MO
->readsReg()) {
1464 addRegWithSubRegs(regsKilled
, Reg
);
1466 // Check that LiveVars knows this kill.
1467 if (LiveVars
&& TargetRegisterInfo::isVirtualRegister(Reg
) &&
1469 LiveVariables::VarInfo
&VI
= LiveVars
->getVarInfo(Reg
);
1470 if (!is_contained(VI
.Kills
, MI
))
1471 report("Kill missing from LiveVariables", MO
, MONum
);
1474 // Check LiveInts liveness and kill.
1475 if (LiveInts
&& !LiveInts
->isNotInMIMap(*MI
)) {
1476 SlotIndex UseIdx
= LiveInts
->getInstructionIndex(*MI
);
1477 // Check the cached regunit intervals.
1478 if (TargetRegisterInfo::isPhysicalRegister(Reg
) && !isReserved(Reg
)) {
1479 for (MCRegUnitIterator
Units(Reg
, TRI
); Units
.isValid(); ++Units
) {
1480 if (MRI
->isReservedRegUnit(*Units
))
1482 if (const LiveRange
*LR
= LiveInts
->getCachedRegUnit(*Units
))
1483 checkLivenessAtUse(MO
, MONum
, UseIdx
, *LR
, *Units
);
1487 if (TargetRegisterInfo::isVirtualRegister(Reg
)) {
1488 if (LiveInts
->hasInterval(Reg
)) {
1489 // This is a virtual register interval.
1490 const LiveInterval
&LI
= LiveInts
->getInterval(Reg
);
1491 checkLivenessAtUse(MO
, MONum
, UseIdx
, LI
, Reg
);
1493 if (LI
.hasSubRanges() && !MO
->isDef()) {
1494 unsigned SubRegIdx
= MO
->getSubReg();
1495 LaneBitmask MOMask
= SubRegIdx
!= 0
1496 ? TRI
->getSubRegIndexLaneMask(SubRegIdx
)
1497 : MRI
->getMaxLaneMaskForVReg(Reg
);
1498 LaneBitmask LiveInMask
;
1499 for (const LiveInterval::SubRange
&SR
: LI
.subranges()) {
1500 if ((MOMask
& SR
.LaneMask
).none())
1502 checkLivenessAtUse(MO
, MONum
, UseIdx
, SR
, Reg
, SR
.LaneMask
);
1503 LiveQueryResult LRQ
= SR
.Query(UseIdx
);
1505 LiveInMask
|= SR
.LaneMask
;
1507 // At least parts of the register has to be live at the use.
1508 if ((LiveInMask
& MOMask
).none()) {
1509 report("No live subrange at use", MO
, MONum
);
1511 report_context(UseIdx
);
1515 report("Virtual register has no live interval", MO
, MONum
);
1520 // Use of a dead register.
1521 if (!regsLive
.count(Reg
)) {
1522 if (TargetRegisterInfo::isPhysicalRegister(Reg
)) {
1523 // Reserved registers may be used even when 'dead'.
1524 bool Bad
= !isReserved(Reg
);
1525 // We are fine if just any subregister has a defined value.
1527 for (MCSubRegIterator
SubRegs(Reg
, TRI
); SubRegs
.isValid();
1529 if (regsLive
.count(*SubRegs
)) {
1535 // If there is an additional implicit-use of a super register we stop
1536 // here. By definition we are fine if the super register is not
1537 // (completely) dead, if the complete super register is dead we will
1538 // get a report for its operand.
1540 for (const MachineOperand
&MOP
: MI
->uses()) {
1541 if (!MOP
.isReg() || !MOP
.isImplicit())
1544 if (!TargetRegisterInfo::isPhysicalRegister(MOP
.getReg()))
1547 for (MCSubRegIterator
SubRegs(MOP
.getReg(), TRI
); SubRegs
.isValid();
1549 if (*SubRegs
== Reg
) {
1557 report("Using an undefined physical register", MO
, MONum
);
1558 } else if (MRI
->def_empty(Reg
)) {
1559 report("Reading virtual register without a def", MO
, MONum
);
1561 BBInfo
&MInfo
= MBBInfoMap
[MI
->getParent()];
1562 // We don't know which virtual registers are live in, so only complain
1563 // if vreg was killed in this MBB. Otherwise keep track of vregs that
1564 // must be live in. PHI instructions are handled separately.
1565 if (MInfo
.regsKilled
.count(Reg
))
1566 report("Using a killed virtual register", MO
, MONum
);
1567 else if (!MI
->isPHI())
1568 MInfo
.vregsLiveIn
.insert(std::make_pair(Reg
, MI
));
1574 // Register defined.
1575 // TODO: verify that earlyclobber ops are not used.
1577 addRegWithSubRegs(regsDead
, Reg
);
1579 addRegWithSubRegs(regsDefined
, Reg
);
1582 if (MRI
->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg
) &&
1583 std::next(MRI
->def_begin(Reg
)) != MRI
->def_end())
1584 report("Multiple virtual register defs in SSA form", MO
, MONum
);
1586 // Check LiveInts for a live segment, but only for virtual registers.
1587 if (LiveInts
&& !LiveInts
->isNotInMIMap(*MI
)) {
1588 SlotIndex DefIdx
= LiveInts
->getInstructionIndex(*MI
);
1589 DefIdx
= DefIdx
.getRegSlot(MO
->isEarlyClobber());
1591 if (TargetRegisterInfo::isVirtualRegister(Reg
)) {
1592 if (LiveInts
->hasInterval(Reg
)) {
1593 const LiveInterval
&LI
= LiveInts
->getInterval(Reg
);
1594 checkLivenessAtDef(MO
, MONum
, DefIdx
, LI
, Reg
);
1596 if (LI
.hasSubRanges()) {
1597 unsigned SubRegIdx
= MO
->getSubReg();
1598 LaneBitmask MOMask
= SubRegIdx
!= 0
1599 ? TRI
->getSubRegIndexLaneMask(SubRegIdx
)
1600 : MRI
->getMaxLaneMaskForVReg(Reg
);
1601 for (const LiveInterval::SubRange
&SR
: LI
.subranges()) {
1602 if ((SR
.LaneMask
& MOMask
).none())
1604 checkLivenessAtDef(MO
, MONum
, DefIdx
, SR
, Reg
, true, SR
.LaneMask
);
1608 report("Virtual register has no Live interval", MO
, MONum
);
1615 void MachineVerifier::visitMachineInstrAfter(const MachineInstr
*MI
) {}
1617 // This function gets called after visiting all instructions in a bundle. The
1618 // argument points to the bundle header.
1619 // Normal stand-alone instructions are also considered 'bundles', and this
1620 // function is called for all of them.
1621 void MachineVerifier::visitMachineBundleAfter(const MachineInstr
*MI
) {
1622 BBInfo
&MInfo
= MBBInfoMap
[MI
->getParent()];
1623 set_union(MInfo
.regsKilled
, regsKilled
);
1624 set_subtract(regsLive
, regsKilled
); regsKilled
.clear();
1625 // Kill any masked registers.
1626 while (!regMasks
.empty()) {
1627 const uint32_t *Mask
= regMasks
.pop_back_val();
1628 for (RegSet::iterator I
= regsLive
.begin(), E
= regsLive
.end(); I
!= E
; ++I
)
1629 if (TargetRegisterInfo::isPhysicalRegister(*I
) &&
1630 MachineOperand::clobbersPhysReg(Mask
, *I
))
1631 regsDead
.push_back(*I
);
1633 set_subtract(regsLive
, regsDead
); regsDead
.clear();
1634 set_union(regsLive
, regsDefined
); regsDefined
.clear();
1638 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock
*MBB
) {
1639 MBBInfoMap
[MBB
].regsLiveOut
= regsLive
;
1643 SlotIndex stop
= Indexes
->getMBBEndIdx(MBB
);
1644 if (!(stop
> lastIndex
)) {
1645 report("Block ends before last instruction index", MBB
);
1646 errs() << "Block ends at " << stop
1647 << " last instruction was at " << lastIndex
<< '\n';
1653 // Calculate the largest possible vregsPassed sets. These are the registers that
1654 // can pass through an MBB live, but may not be live every time. It is assumed
1655 // that all vregsPassed sets are empty before the call.
1656 void MachineVerifier::calcRegsPassed() {
1657 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
1658 // have any vregsPassed.
1659 SmallPtrSet
<const MachineBasicBlock
*, 8> todo
;
1660 for (const auto &MBB
: *MF
) {
1661 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
1662 if (!MInfo
.reachable
)
1664 for (MachineBasicBlock::const_succ_iterator SuI
= MBB
.succ_begin(),
1665 SuE
= MBB
.succ_end(); SuI
!= SuE
; ++SuI
) {
1666 BBInfo
&SInfo
= MBBInfoMap
[*SuI
];
1667 if (SInfo
.addPassed(MInfo
.regsLiveOut
))
1672 // Iteratively push vregsPassed to successors. This will converge to the same
1673 // final state regardless of DenseSet iteration order.
1674 while (!todo
.empty()) {
1675 const MachineBasicBlock
*MBB
= *todo
.begin();
1677 BBInfo
&MInfo
= MBBInfoMap
[MBB
];
1678 for (MachineBasicBlock::const_succ_iterator SuI
= MBB
->succ_begin(),
1679 SuE
= MBB
->succ_end(); SuI
!= SuE
; ++SuI
) {
1682 BBInfo
&SInfo
= MBBInfoMap
[*SuI
];
1683 if (SInfo
.addPassed(MInfo
.vregsPassed
))
1689 // Calculate the set of virtual registers that must be passed through each basic
1690 // block in order to satisfy the requirements of successor blocks. This is very
1691 // similar to calcRegsPassed, only backwards.
1692 void MachineVerifier::calcRegsRequired() {
1693 // First push live-in regs to predecessors' vregsRequired.
1694 SmallPtrSet
<const MachineBasicBlock
*, 8> todo
;
1695 for (const auto &MBB
: *MF
) {
1696 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
1697 for (MachineBasicBlock::const_pred_iterator PrI
= MBB
.pred_begin(),
1698 PrE
= MBB
.pred_end(); PrI
!= PrE
; ++PrI
) {
1699 BBInfo
&PInfo
= MBBInfoMap
[*PrI
];
1700 if (PInfo
.addRequired(MInfo
.vregsLiveIn
))
1705 // Iteratively push vregsRequired to predecessors. This will converge to the
1706 // same final state regardless of DenseSet iteration order.
1707 while (!todo
.empty()) {
1708 const MachineBasicBlock
*MBB
= *todo
.begin();
1710 BBInfo
&MInfo
= MBBInfoMap
[MBB
];
1711 for (MachineBasicBlock::const_pred_iterator PrI
= MBB
->pred_begin(),
1712 PrE
= MBB
->pred_end(); PrI
!= PrE
; ++PrI
) {
1715 BBInfo
&SInfo
= MBBInfoMap
[*PrI
];
1716 if (SInfo
.addRequired(MInfo
.vregsRequired
))
1722 // Check PHI instructions at the beginning of MBB. It is assumed that
1723 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
1724 void MachineVerifier::checkPHIOps(const MachineBasicBlock
&MBB
) {
1725 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
1727 SmallPtrSet
<const MachineBasicBlock
*, 8> seen
;
1728 for (const MachineInstr
&Phi
: MBB
) {
1733 const MachineOperand
&MODef
= Phi
.getOperand(0);
1734 if (!MODef
.isReg() || !MODef
.isDef()) {
1735 report("Expected first PHI operand to be a register def", &MODef
, 0);
1738 if (MODef
.isTied() || MODef
.isImplicit() || MODef
.isInternalRead() ||
1739 MODef
.isEarlyClobber() || MODef
.isDebug())
1740 report("Unexpected flag on PHI operand", &MODef
, 0);
1741 unsigned DefReg
= MODef
.getReg();
1742 if (!TargetRegisterInfo::isVirtualRegister(DefReg
))
1743 report("Expected first PHI operand to be a virtual register", &MODef
, 0);
1745 for (unsigned I
= 1, E
= Phi
.getNumOperands(); I
!= E
; I
+= 2) {
1746 const MachineOperand
&MO0
= Phi
.getOperand(I
);
1748 report("Expected PHI operand to be a register", &MO0
, I
);
1751 if (MO0
.isImplicit() || MO0
.isInternalRead() || MO0
.isEarlyClobber() ||
1752 MO0
.isDebug() || MO0
.isTied())
1753 report("Unexpected flag on PHI operand", &MO0
, I
);
1755 const MachineOperand
&MO1
= Phi
.getOperand(I
+ 1);
1757 report("Expected PHI operand to be a basic block", &MO1
, I
+ 1);
1761 const MachineBasicBlock
&Pre
= *MO1
.getMBB();
1762 if (!Pre
.isSuccessor(&MBB
)) {
1763 report("PHI input is not a predecessor block", &MO1
, I
+ 1);
1767 if (MInfo
.reachable
) {
1769 BBInfo
&PrInfo
= MBBInfoMap
[&Pre
];
1770 if (!MO0
.isUndef() && PrInfo
.reachable
&&
1771 !PrInfo
.isLiveOut(MO0
.getReg()))
1772 report("PHI operand is not live-out from predecessor", &MO0
, I
);
1776 // Did we see all predecessors?
1777 if (MInfo
.reachable
) {
1778 for (MachineBasicBlock
*Pred
: MBB
.predecessors()) {
1779 if (!seen
.count(Pred
)) {
1780 report("Missing PHI operand", &Phi
);
1781 errs() << printMBBReference(*Pred
)
1782 << " is a predecessor according to the CFG.\n";
1789 void MachineVerifier::visitMachineFunctionAfter() {
1792 for (const MachineBasicBlock
&MBB
: *MF
)
1795 // Now check liveness info if available
1798 // Check for killed virtual registers that should be live out.
1799 for (const auto &MBB
: *MF
) {
1800 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
1801 for (RegSet::iterator
1802 I
= MInfo
.vregsRequired
.begin(), E
= MInfo
.vregsRequired
.end(); I
!= E
;
1804 if (MInfo
.regsKilled
.count(*I
)) {
1805 report("Virtual register killed in block, but needed live out.", &MBB
);
1806 errs() << "Virtual register " << printReg(*I
)
1807 << " is used after the block.\n";
1812 BBInfo
&MInfo
= MBBInfoMap
[&MF
->front()];
1813 for (RegSet::iterator
1814 I
= MInfo
.vregsRequired
.begin(), E
= MInfo
.vregsRequired
.end(); I
!= E
;
1816 report("Virtual register defs don't dominate all uses.", MF
);
1817 report_context_vreg(*I
);
1822 verifyLiveVariables();
1824 verifyLiveIntervals();
1827 void MachineVerifier::verifyLiveVariables() {
1828 assert(LiveVars
&& "Don't call verifyLiveVariables without LiveVars");
1829 for (unsigned i
= 0, e
= MRI
->getNumVirtRegs(); i
!= e
; ++i
) {
1830 unsigned Reg
= TargetRegisterInfo::index2VirtReg(i
);
1831 LiveVariables::VarInfo
&VI
= LiveVars
->getVarInfo(Reg
);
1832 for (const auto &MBB
: *MF
) {
1833 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
1835 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1836 if (MInfo
.vregsRequired
.count(Reg
)) {
1837 if (!VI
.AliveBlocks
.test(MBB
.getNumber())) {
1838 report("LiveVariables: Block missing from AliveBlocks", &MBB
);
1839 errs() << "Virtual register " << printReg(Reg
)
1840 << " must be live through the block.\n";
1843 if (VI
.AliveBlocks
.test(MBB
.getNumber())) {
1844 report("LiveVariables: Block should not be in AliveBlocks", &MBB
);
1845 errs() << "Virtual register " << printReg(Reg
)
1846 << " is not needed live through the block.\n";
1853 void MachineVerifier::verifyLiveIntervals() {
1854 assert(LiveInts
&& "Don't call verifyLiveIntervals without LiveInts");
1855 for (unsigned i
= 0, e
= MRI
->getNumVirtRegs(); i
!= e
; ++i
) {
1856 unsigned Reg
= TargetRegisterInfo::index2VirtReg(i
);
1858 // Spilling and splitting may leave unused registers around. Skip them.
1859 if (MRI
->reg_nodbg_empty(Reg
))
1862 if (!LiveInts
->hasInterval(Reg
)) {
1863 report("Missing live interval for virtual register", MF
);
1864 errs() << printReg(Reg
, TRI
) << " still has defs or uses\n";
1868 const LiveInterval
&LI
= LiveInts
->getInterval(Reg
);
1869 assert(Reg
== LI
.reg
&& "Invalid reg to interval mapping");
1870 verifyLiveInterval(LI
);
1873 // Verify all the cached regunit intervals.
1874 for (unsigned i
= 0, e
= TRI
->getNumRegUnits(); i
!= e
; ++i
)
1875 if (const LiveRange
*LR
= LiveInts
->getCachedRegUnit(i
))
1876 verifyLiveRange(*LR
, i
);
1879 void MachineVerifier::verifyLiveRangeValue(const LiveRange
&LR
,
1880 const VNInfo
*VNI
, unsigned Reg
,
1881 LaneBitmask LaneMask
) {
1882 if (VNI
->isUnused())
1885 const VNInfo
*DefVNI
= LR
.getVNInfoAt(VNI
->def
);
1888 report("Value not live at VNInfo def and not marked unused", MF
);
1889 report_context(LR
, Reg
, LaneMask
);
1890 report_context(*VNI
);
1894 if (DefVNI
!= VNI
) {
1895 report("Live segment at def has different VNInfo", MF
);
1896 report_context(LR
, Reg
, LaneMask
);
1897 report_context(*VNI
);
1901 const MachineBasicBlock
*MBB
= LiveInts
->getMBBFromIndex(VNI
->def
);
1903 report("Invalid VNInfo definition index", MF
);
1904 report_context(LR
, Reg
, LaneMask
);
1905 report_context(*VNI
);
1909 if (VNI
->isPHIDef()) {
1910 if (VNI
->def
!= LiveInts
->getMBBStartIdx(MBB
)) {
1911 report("PHIDef VNInfo is not defined at MBB start", MBB
);
1912 report_context(LR
, Reg
, LaneMask
);
1913 report_context(*VNI
);
1919 const MachineInstr
*MI
= LiveInts
->getInstructionFromIndex(VNI
->def
);
1921 report("No instruction at VNInfo def index", MBB
);
1922 report_context(LR
, Reg
, LaneMask
);
1923 report_context(*VNI
);
1928 bool hasDef
= false;
1929 bool isEarlyClobber
= false;
1930 for (ConstMIBundleOperands
MOI(*MI
); MOI
.isValid(); ++MOI
) {
1931 if (!MOI
->isReg() || !MOI
->isDef())
1933 if (TargetRegisterInfo::isVirtualRegister(Reg
)) {
1934 if (MOI
->getReg() != Reg
)
1937 if (!TargetRegisterInfo::isPhysicalRegister(MOI
->getReg()) ||
1938 !TRI
->hasRegUnit(MOI
->getReg(), Reg
))
1941 if (LaneMask
.any() &&
1942 (TRI
->getSubRegIndexLaneMask(MOI
->getSubReg()) & LaneMask
).none())
1945 if (MOI
->isEarlyClobber())
1946 isEarlyClobber
= true;
1950 report("Defining instruction does not modify register", MI
);
1951 report_context(LR
, Reg
, LaneMask
);
1952 report_context(*VNI
);
1955 // Early clobber defs begin at USE slots, but other defs must begin at
1957 if (isEarlyClobber
) {
1958 if (!VNI
->def
.isEarlyClobber()) {
1959 report("Early clobber def must be at an early-clobber slot", MBB
);
1960 report_context(LR
, Reg
, LaneMask
);
1961 report_context(*VNI
);
1963 } else if (!VNI
->def
.isRegister()) {
1964 report("Non-PHI, non-early clobber def must be at a register slot", MBB
);
1965 report_context(LR
, Reg
, LaneMask
);
1966 report_context(*VNI
);
1971 void MachineVerifier::verifyLiveRangeSegment(const LiveRange
&LR
,
1972 const LiveRange::const_iterator I
,
1973 unsigned Reg
, LaneBitmask LaneMask
)
1975 const LiveRange::Segment
&S
= *I
;
1976 const VNInfo
*VNI
= S
.valno
;
1977 assert(VNI
&& "Live segment has no valno");
1979 if (VNI
->id
>= LR
.getNumValNums() || VNI
!= LR
.getValNumInfo(VNI
->id
)) {
1980 report("Foreign valno in live segment", MF
);
1981 report_context(LR
, Reg
, LaneMask
);
1983 report_context(*VNI
);
1986 if (VNI
->isUnused()) {
1987 report("Live segment valno is marked unused", MF
);
1988 report_context(LR
, Reg
, LaneMask
);
1992 const MachineBasicBlock
*MBB
= LiveInts
->getMBBFromIndex(S
.start
);
1994 report("Bad start of live segment, no basic block", MF
);
1995 report_context(LR
, Reg
, LaneMask
);
1999 SlotIndex MBBStartIdx
= LiveInts
->getMBBStartIdx(MBB
);
2000 if (S
.start
!= MBBStartIdx
&& S
.start
!= VNI
->def
) {
2001 report("Live segment must begin at MBB entry or valno def", MBB
);
2002 report_context(LR
, Reg
, LaneMask
);
2006 const MachineBasicBlock
*EndMBB
=
2007 LiveInts
->getMBBFromIndex(S
.end
.getPrevSlot());
2009 report("Bad end of live segment, no basic block", MF
);
2010 report_context(LR
, Reg
, LaneMask
);
2015 // No more checks for live-out segments.
2016 if (S
.end
== LiveInts
->getMBBEndIdx(EndMBB
))
2019 // RegUnit intervals are allowed dead phis.
2020 if (!TargetRegisterInfo::isVirtualRegister(Reg
) && VNI
->isPHIDef() &&
2021 S
.start
== VNI
->def
&& S
.end
== VNI
->def
.getDeadSlot())
2024 // The live segment is ending inside EndMBB
2025 const MachineInstr
*MI
=
2026 LiveInts
->getInstructionFromIndex(S
.end
.getPrevSlot());
2028 report("Live segment doesn't end at a valid instruction", EndMBB
);
2029 report_context(LR
, Reg
, LaneMask
);
2034 // The block slot must refer to a basic block boundary.
2035 if (S
.end
.isBlock()) {
2036 report("Live segment ends at B slot of an instruction", EndMBB
);
2037 report_context(LR
, Reg
, LaneMask
);
2041 if (S
.end
.isDead()) {
2042 // Segment ends on the dead slot.
2043 // That means there must be a dead def.
2044 if (!SlotIndex::isSameInstr(S
.start
, S
.end
)) {
2045 report("Live segment ending at dead slot spans instructions", EndMBB
);
2046 report_context(LR
, Reg
, LaneMask
);
2051 // A live segment can only end at an early-clobber slot if it is being
2052 // redefined by an early-clobber def.
2053 if (S
.end
.isEarlyClobber()) {
2054 if (I
+1 == LR
.end() || (I
+1)->start
!= S
.end
) {
2055 report("Live segment ending at early clobber slot must be "
2056 "redefined by an EC def in the same instruction", EndMBB
);
2057 report_context(LR
, Reg
, LaneMask
);
2062 // The following checks only apply to virtual registers. Physreg liveness
2063 // is too weird to check.
2064 if (TargetRegisterInfo::isVirtualRegister(Reg
)) {
2065 // A live segment can end with either a redefinition, a kill flag on a
2066 // use, or a dead flag on a def.
2067 bool hasRead
= false;
2068 bool hasSubRegDef
= false;
2069 bool hasDeadDef
= false;
2070 for (ConstMIBundleOperands
MOI(*MI
); MOI
.isValid(); ++MOI
) {
2071 if (!MOI
->isReg() || MOI
->getReg() != Reg
)
2073 unsigned Sub
= MOI
->getSubReg();
2074 LaneBitmask SLM
= Sub
!= 0 ? TRI
->getSubRegIndexLaneMask(Sub
)
2075 : LaneBitmask::getAll();
2078 hasSubRegDef
= true;
2079 // An operand %0:sub0 reads %0:sub1..n. Invert the lane
2080 // mask for subregister defs. Read-undef defs will be handled by
2087 if (LaneMask
.any() && (LaneMask
& SLM
).none())
2089 if (MOI
->readsReg())
2092 if (S
.end
.isDead()) {
2093 // Make sure that the corresponding machine operand for a "dead" live
2094 // range has the dead flag. We cannot perform this check for subregister
2095 // liveranges as partially dead values are allowed.
2096 if (LaneMask
.none() && !hasDeadDef
) {
2097 report("Instruction ending live segment on dead slot has no dead flag",
2099 report_context(LR
, Reg
, LaneMask
);
2104 // When tracking subregister liveness, the main range must start new
2105 // values on partial register writes, even if there is no read.
2106 if (!MRI
->shouldTrackSubRegLiveness(Reg
) || LaneMask
.any() ||
2108 report("Instruction ending live segment doesn't read the register",
2110 report_context(LR
, Reg
, LaneMask
);
2117 // Now check all the basic blocks in this live segment.
2118 MachineFunction::const_iterator MFI
= MBB
->getIterator();
2119 // Is this live segment the beginning of a non-PHIDef VN?
2120 if (S
.start
== VNI
->def
&& !VNI
->isPHIDef()) {
2121 // Not live-in to any blocks.
2128 SmallVector
<SlotIndex
, 4> Undefs
;
2129 if (LaneMask
.any()) {
2130 LiveInterval
&OwnerLI
= LiveInts
->getInterval(Reg
);
2131 OwnerLI
.computeSubRangeUndefs(Undefs
, LaneMask
, *MRI
, *Indexes
);
2135 assert(LiveInts
->isLiveInToMBB(LR
, &*MFI
));
2136 // We don't know how to track physregs into a landing pad.
2137 if (!TargetRegisterInfo::isVirtualRegister(Reg
) &&
2139 if (&*MFI
== EndMBB
)
2145 // Is VNI a PHI-def in the current block?
2146 bool IsPHI
= VNI
->isPHIDef() &&
2147 VNI
->def
== LiveInts
->getMBBStartIdx(&*MFI
);
2149 // Check that VNI is live-out of all predecessors.
2150 for (MachineBasicBlock::const_pred_iterator PI
= MFI
->pred_begin(),
2151 PE
= MFI
->pred_end(); PI
!= PE
; ++PI
) {
2152 SlotIndex PEnd
= LiveInts
->getMBBEndIdx(*PI
);
2153 const VNInfo
*PVNI
= LR
.getVNInfoBefore(PEnd
);
2155 // All predecessors must have a live-out value. However for a phi
2156 // instruction with subregister intervals
2157 // only one of the subregisters (not necessarily the current one) needs to
2159 if (!PVNI
&& (LaneMask
.none() || !IsPHI
)) {
2160 if (LiveRangeCalc::isJointlyDominated(*PI
, Undefs
, *Indexes
))
2162 report("Register not marked live out of predecessor", *PI
);
2163 report_context(LR
, Reg
, LaneMask
);
2164 report_context(*VNI
);
2165 errs() << " live into " << printMBBReference(*MFI
) << '@'
2166 << LiveInts
->getMBBStartIdx(&*MFI
) << ", not live before "
2171 // Only PHI-defs can take different predecessor values.
2172 if (!IsPHI
&& PVNI
!= VNI
) {
2173 report("Different value live out of predecessor", *PI
);
2174 report_context(LR
, Reg
, LaneMask
);
2175 errs() << "Valno #" << PVNI
->id
<< " live out of "
2176 << printMBBReference(*(*PI
)) << '@' << PEnd
<< "\nValno #"
2177 << VNI
->id
<< " live into " << printMBBReference(*MFI
) << '@'
2178 << LiveInts
->getMBBStartIdx(&*MFI
) << '\n';
2181 if (&*MFI
== EndMBB
)
2187 void MachineVerifier::verifyLiveRange(const LiveRange
&LR
, unsigned Reg
,
2188 LaneBitmask LaneMask
) {
2189 for (const VNInfo
*VNI
: LR
.valnos
)
2190 verifyLiveRangeValue(LR
, VNI
, Reg
, LaneMask
);
2192 for (LiveRange::const_iterator I
= LR
.begin(), E
= LR
.end(); I
!= E
; ++I
)
2193 verifyLiveRangeSegment(LR
, I
, Reg
, LaneMask
);
2196 void MachineVerifier::verifyLiveInterval(const LiveInterval
&LI
) {
2197 unsigned Reg
= LI
.reg
;
2198 assert(TargetRegisterInfo::isVirtualRegister(Reg
));
2199 verifyLiveRange(LI
, Reg
);
2202 LaneBitmask MaxMask
= MRI
->getMaxLaneMaskForVReg(Reg
);
2203 for (const LiveInterval::SubRange
&SR
: LI
.subranges()) {
2204 if ((Mask
& SR
.LaneMask
).any()) {
2205 report("Lane masks of sub ranges overlap in live interval", MF
);
2208 if ((SR
.LaneMask
& ~MaxMask
).any()) {
2209 report("Subrange lanemask is invalid", MF
);
2213 report("Subrange must not be empty", MF
);
2214 report_context(SR
, LI
.reg
, SR
.LaneMask
);
2216 Mask
|= SR
.LaneMask
;
2217 verifyLiveRange(SR
, LI
.reg
, SR
.LaneMask
);
2218 if (!LI
.covers(SR
)) {
2219 report("A Subrange is not covered by the main range", MF
);
2224 // Check the LI only has one connected component.
2225 ConnectedVNInfoEqClasses
ConEQ(*LiveInts
);
2226 unsigned NumComp
= ConEQ
.Classify(LI
);
2228 report("Multiple connected components in live interval", MF
);
2230 for (unsigned comp
= 0; comp
!= NumComp
; ++comp
) {
2231 errs() << comp
<< ": valnos";
2232 for (LiveInterval::const_vni_iterator I
= LI
.vni_begin(),
2233 E
= LI
.vni_end(); I
!=E
; ++I
)
2234 if (comp
== ConEQ
.getEqClass(*I
))
2235 errs() << ' ' << (*I
)->id
;
2243 // FrameSetup and FrameDestroy can have zero adjustment, so using a single
2244 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
2246 // We use a bool plus an integer to capture the stack state.
2247 struct StackStateOfBB
{
2248 StackStateOfBB() = default;
2249 StackStateOfBB(int EntryVal
, int ExitVal
, bool EntrySetup
, bool ExitSetup
) :
2250 EntryValue(EntryVal
), ExitValue(ExitVal
), EntryIsSetup(EntrySetup
),
2251 ExitIsSetup(ExitSetup
) {}
2253 // Can be negative, which means we are setting up a frame.
2256 bool EntryIsSetup
= false;
2257 bool ExitIsSetup
= false;
2260 } // end anonymous namespace
2262 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
2263 /// by a FrameDestroy <n>, stack adjustments are identical on all
2264 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
2265 void MachineVerifier::verifyStackFrame() {
2266 unsigned FrameSetupOpcode
= TII
->getCallFrameSetupOpcode();
2267 unsigned FrameDestroyOpcode
= TII
->getCallFrameDestroyOpcode();
2268 if (FrameSetupOpcode
== ~0u && FrameDestroyOpcode
== ~0u)
2271 SmallVector
<StackStateOfBB
, 8> SPState
;
2272 SPState
.resize(MF
->getNumBlockIDs());
2273 df_iterator_default_set
<const MachineBasicBlock
*> Reachable
;
2275 // Visit the MBBs in DFS order.
2276 for (df_ext_iterator
<const MachineFunction
*,
2277 df_iterator_default_set
<const MachineBasicBlock
*>>
2278 DFI
= df_ext_begin(MF
, Reachable
), DFE
= df_ext_end(MF
, Reachable
);
2279 DFI
!= DFE
; ++DFI
) {
2280 const MachineBasicBlock
*MBB
= *DFI
;
2282 StackStateOfBB BBState
;
2283 // Check the exit state of the DFS stack predecessor.
2284 if (DFI
.getPathLength() >= 2) {
2285 const MachineBasicBlock
*StackPred
= DFI
.getPath(DFI
.getPathLength() - 2);
2286 assert(Reachable
.count(StackPred
) &&
2287 "DFS stack predecessor is already visited.\n");
2288 BBState
.EntryValue
= SPState
[StackPred
->getNumber()].ExitValue
;
2289 BBState
.EntryIsSetup
= SPState
[StackPred
->getNumber()].ExitIsSetup
;
2290 BBState
.ExitValue
= BBState
.EntryValue
;
2291 BBState
.ExitIsSetup
= BBState
.EntryIsSetup
;
2294 // Update stack state by checking contents of MBB.
2295 for (const auto &I
: *MBB
) {
2296 if (I
.getOpcode() == FrameSetupOpcode
) {
2297 if (BBState
.ExitIsSetup
)
2298 report("FrameSetup is after another FrameSetup", &I
);
2299 BBState
.ExitValue
-= TII
->getFrameTotalSize(I
);
2300 BBState
.ExitIsSetup
= true;
2303 if (I
.getOpcode() == FrameDestroyOpcode
) {
2304 int Size
= TII
->getFrameTotalSize(I
);
2305 if (!BBState
.ExitIsSetup
)
2306 report("FrameDestroy is not after a FrameSetup", &I
);
2307 int AbsSPAdj
= BBState
.ExitValue
< 0 ? -BBState
.ExitValue
:
2309 if (BBState
.ExitIsSetup
&& AbsSPAdj
!= Size
) {
2310 report("FrameDestroy <n> is after FrameSetup <m>", &I
);
2311 errs() << "FrameDestroy <" << Size
<< "> is after FrameSetup <"
2312 << AbsSPAdj
<< ">.\n";
2314 BBState
.ExitValue
+= Size
;
2315 BBState
.ExitIsSetup
= false;
2318 SPState
[MBB
->getNumber()] = BBState
;
2320 // Make sure the exit state of any predecessor is consistent with the entry
2322 for (MachineBasicBlock::const_pred_iterator I
= MBB
->pred_begin(),
2323 E
= MBB
->pred_end(); I
!= E
; ++I
) {
2324 if (Reachable
.count(*I
) &&
2325 (SPState
[(*I
)->getNumber()].ExitValue
!= BBState
.EntryValue
||
2326 SPState
[(*I
)->getNumber()].ExitIsSetup
!= BBState
.EntryIsSetup
)) {
2327 report("The exit stack state of a predecessor is inconsistent.", MBB
);
2328 errs() << "Predecessor " << printMBBReference(*(*I
))
2329 << " has exit state (" << SPState
[(*I
)->getNumber()].ExitValue
2330 << ", " << SPState
[(*I
)->getNumber()].ExitIsSetup
<< "), while "
2331 << printMBBReference(*MBB
) << " has entry state ("
2332 << BBState
.EntryValue
<< ", " << BBState
.EntryIsSetup
<< ").\n";
2336 // Make sure the entry state of any successor is consistent with the exit
2338 for (MachineBasicBlock::const_succ_iterator I
= MBB
->succ_begin(),
2339 E
= MBB
->succ_end(); I
!= E
; ++I
) {
2340 if (Reachable
.count(*I
) &&
2341 (SPState
[(*I
)->getNumber()].EntryValue
!= BBState
.ExitValue
||
2342 SPState
[(*I
)->getNumber()].EntryIsSetup
!= BBState
.ExitIsSetup
)) {
2343 report("The entry stack state of a successor is inconsistent.", MBB
);
2344 errs() << "Successor " << printMBBReference(*(*I
))
2345 << " has entry state (" << SPState
[(*I
)->getNumber()].EntryValue
2346 << ", " << SPState
[(*I
)->getNumber()].EntryIsSetup
<< "), while "
2347 << printMBBReference(*MBB
) << " has exit state ("
2348 << BBState
.ExitValue
<< ", " << BBState
.ExitIsSetup
<< ").\n";
2352 // Make sure a basic block with return ends with zero stack adjustment.
2353 if (!MBB
->empty() && MBB
->back().isReturn()) {
2354 if (BBState
.ExitIsSetup
)
2355 report("A return block ends with a FrameSetup.", MBB
);
2356 if (BBState
.ExitValue
)
2357 report("A return block ends with a nonzero stack adjustment.", MBB
);