LLVM 24.0.0git
MachineVerifier.cpp
Go to the documentation of this file.
1//===- MachineVerifier.cpp - Machine Code Verifier ------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Pass to verify generated machine code. The following is checked:
10//
11// Operand counts: All explicit operands must be present.
12//
13// Register classes: All physical and virtual register operands must be
14// compatible with the register class required by the instruction descriptor.
15//
16// Register live intervals: Registers must be defined only once, and must be
17// defined before use.
18//
19// The machine code verifier is enabled with the command-line option
20// -verify-machineinstrs.
21//===----------------------------------------------------------------------===//
22
24#include "llvm/ADT/BitVector.h"
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/DenseSet.h"
29#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/StringRef.h"
34#include "llvm/ADT/Twine.h"
63#include "llvm/IR/BasicBlock.h"
64#include "llvm/IR/Constants.h"
66#include "llvm/IR/Function.h"
67#include "llvm/IR/InlineAsm.h"
70#include "llvm/MC/LaneBitmask.h"
71#include "llvm/MC/MCDwarf.h"
72#include "llvm/MC/MCInstrDesc.h"
75#include "llvm/Pass.h"
80#include "llvm/Support/ModRef.h"
81#include "llvm/Support/Mutex.h"
84#include <algorithm>
85#include <cassert>
86#include <cstddef>
87#include <cstdint>
88#include <iterator>
89#include <string>
90#include <utility>
91
92using namespace llvm;
93
94namespace {
95
96/// Used the by the ReportedErrors class to guarantee only one error is reported
97/// at one time.
98static ManagedStatic<sys::SmartMutex<true>> ReportedErrorsLock;
99
100static bool hasPhysRegClassForType(const TargetRegisterInfo &TRI,
101 MCRegister Reg, LLT Ty) {
102 assert(Reg.isPhysical() && "reg must be a physical register");
103 assert(Ty.isValid() && "expected a valid type");
104
105 const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(Reg);
106 if (TRI.isTypeLegalForClass(*RC, Ty))
107 return true;
108
109 return llvm::any_of(TRI.regclasses(), [&](const TargetRegisterClass &RC) {
110 return RC.contains(Reg) && TRI.isTypeLegalForClass(RC, Ty);
111 });
112}
113
114struct MachineVerifier {
115 MachineVerifier(MachineFunctionAnalysisManager &MFAM, const char *b,
116 raw_ostream *OS, bool AbortOnError = true)
117 : MFAM(&MFAM), OS(OS ? *OS : nulls()), Banner(b),
118 ReportedErrs(AbortOnError) {}
119
120 MachineVerifier(Pass *pass, const char *b, raw_ostream *OS,
121 bool AbortOnError = true)
122 : PASS(pass), OS(OS ? *OS : nulls()), Banner(b),
123 ReportedErrs(AbortOnError) {}
124
125 MachineVerifier(const char *b, LiveIntervals *LiveInts, LiveStacks *LiveStks,
126 SlotIndexes *Indexes, raw_ostream *OS,
127 bool AbortOnError = true)
128 : OS(OS ? *OS : nulls()), Banner(b), LiveInts(LiveInts),
129 LiveStks(LiveStks), Indexes(Indexes), ReportedErrs(AbortOnError) {}
130
131 /// \returns true if no problems were found.
132 bool verify(const MachineFunction &MF);
133
134 MachineFunctionAnalysisManager *MFAM = nullptr;
135 Pass *const PASS = nullptr;
136 raw_ostream &OS;
137 const char *Banner;
138 const MachineFunction *MF = nullptr;
139 const TargetMachine *TM = nullptr;
140 const TargetInstrInfo *TII = nullptr;
141 const TargetRegisterInfo *TRI = nullptr;
142 const MachineRegisterInfo *MRI = nullptr;
143 const RegisterBankInfo *RBI = nullptr;
144
145 // Avoid querying the MachineFunctionProperties for each operand.
146 bool isFunctionRegBankSelected = false;
147 bool isFunctionSelected = false;
148 bool isFunctionTracksDebugUserValues = false;
149
150 using RegVector = SmallVector<Register, 16>;
151 using RegMaskVector = SmallVector<const uint32_t *, 4>;
152 using RegSet = DenseSet<Register>;
153 using RegMap = DenseMap<Register, const MachineInstr *>;
154 using BlockSet = SmallPtrSet<const MachineBasicBlock *, 8>;
155
156 const MachineInstr *FirstNonPHI = nullptr;
157 const MachineInstr *FirstTerminator = nullptr;
158 BlockSet FunctionBlocks;
159
160 BitVector regsReserved;
161 RegSet regsLive;
162 RegVector regsDefined, regsDead, regsKilled;
163 RegMaskVector regMasks;
164
165 // Live physical register defs of the current instruction, and the operand
166 // indices of its dead physical register defs.
167 SmallVector<MCRegister, 4> LivePhysDefs;
168 SmallVector<unsigned, 4> DeadPhysDefOps;
169
170 SlotIndex lastIndex;
171
172 // Add Reg and any sub-registers to RV
173 void addRegWithSubRegs(RegVector &RV, Register Reg) {
174 RV.push_back(Reg);
175 if (Reg.isPhysical())
176 append_range(RV, TRI->subregs(Reg.asMCReg()));
177 }
178
179 struct BBInfo {
180 // Is this MBB reachable from the MF entry point?
181 bool reachable = false;
182
183 // Vregs that must be live in because they are used without being
184 // defined. Map value is the user. vregsLiveIn doesn't include regs
185 // that only are used by PHI nodes.
186 RegMap vregsLiveIn;
187
188 // Regs killed in MBB. They may be defined again, and will then be in both
189 // regsKilled and regsLiveOut.
190 RegSet regsKilled;
191
192 // Regs defined in MBB and live out. Note that vregs passing through may
193 // be live out without being mentioned here.
194 RegSet regsLiveOut;
195
196 // Vregs that pass through MBB untouched. This set is disjoint from
197 // regsKilled and regsLiveOut.
198 RegSet vregsPassed;
199
200 // Vregs that must pass through MBB because they are needed by a successor
201 // block. This set is disjoint from regsLiveOut.
202 RegSet vregsRequired;
203
204 // Set versions of block's predecessor and successor lists.
205 BlockSet Preds, Succs;
206
207 BBInfo() = default;
208
209 // Add register to vregsRequired if it belongs there. Return true if
210 // anything changed.
211 bool addRequired(Register Reg) {
212 if (!Reg.isVirtual())
213 return false;
214 if (regsLiveOut.count(Reg))
215 return false;
216 return vregsRequired.insert(Reg).second;
217 }
218
219 // Same for a full set.
220 bool addRequired(const RegSet &RS) {
221 bool Changed = false;
222 for (Register Reg : RS)
223 Changed |= addRequired(Reg);
224 return Changed;
225 }
226
227 // Same for a full map.
228 bool addRequired(const RegMap &RM) {
229 bool Changed = false;
230 for (const auto &I : RM)
231 Changed |= addRequired(I.first);
232 return Changed;
233 }
234
235 // Live-out registers are either in regsLiveOut or vregsPassed.
236 bool isLiveOut(Register Reg) const {
237 return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
238 }
239 };
240
241 // Extra register info per MBB.
242 DenseMap<const MachineBasicBlock *, BBInfo> MBBInfoMap;
243
244 bool isReserved(Register Reg) {
245 return Reg.id() < regsReserved.size() && regsReserved.test(Reg.id());
246 }
247
248 bool isAllocatable(Register Reg) const {
249 return Reg.id() < TRI->getNumRegs() && TRI->isInAllocatableClass(Reg) &&
250 !regsReserved.test(Reg.id());
251 }
252
253 // Analysis information if available
254 LiveIntervals *LiveInts = nullptr;
255 LiveStacks *LiveStks = nullptr;
256 SlotIndexes *Indexes = nullptr;
257
258 /// A class to track the number of reported error and to guarantee that only
259 /// one error is reported at one time.
260 class ReportedErrors {
261 unsigned NumReported = 0;
262 bool AbortOnError;
263
264 public:
265 /// \param AbortOnError -- If set, abort after printing the first error.
266 ReportedErrors(bool AbortOnError) : AbortOnError(AbortOnError) {}
267
268 ~ReportedErrors() {
269 if (!hasError())
270 return;
271 if (AbortOnError)
272 report_fatal_error("Found " + Twine(NumReported) +
273 " machine code errors.");
274 // Since we haven't aborted, release the lock to allow other threads to
275 // report errors.
276 ReportedErrorsLock->unlock();
277 }
278
279 /// Increment the number of reported errors.
280 /// \returns true if this is the first reported error.
281 bool increment() {
282 // If this is the first error this thread has encountered, grab the lock
283 // to prevent other threads from reporting errors at the same time.
284 // Otherwise we assume we already have the lock.
285 if (!hasError())
286 ReportedErrorsLock->lock();
287 ++NumReported;
288 return NumReported == 1;
289 }
290
291 /// \returns true if an error was reported.
292 bool hasError() { return NumReported; }
293 };
294 ReportedErrors ReportedErrs;
295
296 // This is calculated only when trying to verify convergence control tokens.
297 // Similar to the LLVM IR verifier, we calculate this locally instead of
298 // relying on the pass manager.
299 MachineDominatorTree DT;
300
301 void visitMachineFunctionBefore();
302 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
303 void visitMachineBundleBefore(const MachineInstr *MI);
304
305 /// Verify that all of \p MI's virtual register operands are scalars.
306 /// \returns True if all virtual register operands are scalar. False
307 /// otherwise.
308 bool verifyAllRegOpsScalar(const MachineInstr &MI,
309 const MachineRegisterInfo &MRI);
310 bool verifyVectorElementMatch(LLT Ty0, LLT Ty1, const MachineInstr *MI);
311
312 bool verifyGIntrinsicSideEffects(const MachineInstr *MI);
313 bool verifyGIntrinsicConvergence(const MachineInstr *MI);
314 void verifyPreISelGenericInstruction(const MachineInstr *MI);
315
316 void visitMachineInstrBefore(const MachineInstr *MI);
317 void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
318 void visitMachineInstrAfter(const MachineInstr *MI);
319 void visitMachineBundleAfter(const MachineInstr *MI);
320 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
321 void visitMachineFunctionAfter();
322
323 void report(const char *msg, const MachineFunction *MF);
324 void report(const char *msg, const MachineBasicBlock *MBB);
325 void report(const char *msg, const MachineInstr *MI);
326 void report(const char *msg, const MachineOperand *MO, unsigned MONum,
327 LLT MOVRegType = LLT{});
328 void report(const Twine &Msg, const MachineInstr *MI);
329
330 void report_context(const LiveInterval &LI) const;
331 void report_context(const LiveRange &LR, VirtRegOrUnit VRegOrUnit,
332 LaneBitmask LaneMask) const;
333 void report_context(const LiveRange::Segment &S) const;
334 void report_context(const VNInfo &VNI) const;
335 void report_context(SlotIndex Pos) const;
336 void report_context(MCPhysReg PhysReg) const;
337 void report_context_liverange(const LiveRange &LR) const;
338 void report_context_lanemask(LaneBitmask LaneMask) const;
339 void report_context_vreg(Register VReg) const;
340 void report_context_vreg_regunit(VirtRegOrUnit VRegOrUnit) const;
341
342 void verifyInlineAsm(const MachineInstr *MI);
343
344 void checkLiveness(const MachineOperand *MO, unsigned MONum);
345 void checkLivenessAtUse(const MachineOperand *MO, unsigned MONum,
346 SlotIndex UseIdx, const LiveRange &LR,
347 VirtRegOrUnit VRegOrUnit,
348 LaneBitmask LaneMask = LaneBitmask::getNone());
349 void checkLivenessAtDef(const MachineOperand *MO, unsigned MONum,
350 SlotIndex DefIdx, const LiveRange &LR,
351 VirtRegOrUnit VRegOrUnit, bool SubRangeCheck = false,
352 LaneBitmask LaneMask = LaneBitmask::getNone());
353
354 void markReachable(const MachineBasicBlock *MBB);
355 void calcRegsPassed();
356 void checkPHIOps(const MachineBasicBlock &MBB);
357
358 void calcRegsRequired();
359 void verifyLiveIntervals();
360 void verifyLiveInterval(const LiveInterval &);
361 void verifyLiveRangeValue(const LiveRange &, const VNInfo *, VirtRegOrUnit,
362 LaneBitmask);
363 void verifyLiveRangeSegment(const LiveRange &,
364 const LiveRange::const_iterator I, VirtRegOrUnit,
365 LaneBitmask);
366 void verifyLiveRange(const LiveRange &, VirtRegOrUnit,
367 LaneBitmask LaneMask = LaneBitmask::getNone());
368
369 void verifyStackFrame();
370 /// Check that the stack protector is the top-most object in the stack.
371 void verifyStackProtector();
372
373 void verifySlotIndexes() const;
374 void verifyProperties(const MachineFunction &MF);
375};
376
377struct MachineVerifierLegacyPass : public MachineFunctionPass {
378 static char ID; // Pass ID, replacement for typeid
379
380 const std::string Banner;
381
382 MachineVerifierLegacyPass(std::string banner = std::string())
383 : MachineFunctionPass(ID), Banner(std::move(banner)) {}
384
385 void getAnalysisUsage(AnalysisUsage &AU) const override {
386 AU.addUsedIfAvailable<LiveStacksWrapperLegacy>();
387 AU.addUsedIfAvailable<SlotIndexesWrapperPass>();
388 AU.addUsedIfAvailable<LiveIntervalsWrapperPass>();
389 AU.setPreservesAll();
391 }
392
393 bool runOnMachineFunction(MachineFunction &MF) override {
394 // Skip functions that have known verification problems.
395 // FIXME: Remove this mechanism when all problematic passes have been
396 // fixed.
397 if (MF.getProperties().hasFailsVerification())
398 return false;
399
400 MachineVerifier(this, Banner.c_str(), &errs()).verify(MF);
401 return false;
402 }
403};
404
405} // end anonymous namespace
406
410 // Skip functions that have known verification problems.
411 // FIXME: Remove this mechanism when all problematic passes have been
412 // fixed.
413 if (MF.getProperties().hasFailsVerification())
414 return PreservedAnalyses::all();
415 MachineVerifier(MFAM, Banner.c_str(), &errs()).verify(MF);
416 return PreservedAnalyses::all();
417}
418
419char MachineVerifierLegacyPass::ID = 0;
420
421INITIALIZE_PASS(MachineVerifierLegacyPass, "machineverifier",
422 "Verify generated machine code", false, false)
423
425 return new MachineVerifierLegacyPass(Banner);
426}
427
428void llvm::verifyMachineFunction(const std::string &Banner,
429 const MachineFunction &MF) {
430 // TODO: Use MFAM after porting below analyses.
431 // LiveIntervals *LiveInts;
432 // LiveStacks *LiveStks;
433 // SlotIndexes *Indexes;
434 MachineVerifier(nullptr, Banner.c_str(), &errs()).verify(MF);
435}
436
437bool MachineFunction::verify(Pass *p, const char *Banner, raw_ostream *OS,
438 bool AbortOnError) const {
439 return MachineVerifier(p, Banner, OS, AbortOnError).verify(*this);
440}
441
443 const char *Banner, raw_ostream *OS,
444 bool AbortOnError) const {
445 return MachineVerifier(MFAM, Banner, OS, AbortOnError).verify(*this);
446}
447
449 const char *Banner, raw_ostream *OS,
450 bool AbortOnError) const {
451 return MachineVerifier(Banner, LiveInts, /*LiveStks=*/nullptr, Indexes, OS,
452 AbortOnError)
453 .verify(*this);
454}
455
456void MachineVerifier::verifySlotIndexes() const {
457 if (Indexes == nullptr)
458 return;
459
460 // Ensure the IdxMBB list is sorted by slot indexes.
463 E = Indexes->MBBIndexEnd(); I != E; ++I) {
464 assert(!Last.isValid() || I->first > Last);
465 Last = I->first;
466 }
467}
468
469void MachineVerifier::verifyProperties(const MachineFunction &MF) {
470 // If a pass has introduced virtual registers without clearing the
471 // NoVRegs property (or set it without allocating the vregs)
472 // then report an error.
473 if (MF.getProperties().hasNoVRegs() && MRI->getNumVirtRegs())
474 report("Function has NoVRegs property but there are VReg operands", &MF);
475}
476
477bool MachineVerifier::verify(const MachineFunction &MF) {
478 this->MF = &MF;
479 TM = &MF.getTarget();
482 RBI = MF.getSubtarget().getRegBankInfo();
483 MRI = &MF.getRegInfo();
484
485 const MachineFunctionProperties &Props = MF.getProperties();
486 const bool isFunctionFailedISel = Props.hasFailedISel();
487
488 // If we're mid-GlobalISel and we already triggered the fallback path then
489 // it's expected that the MIR is somewhat broken but that's ok since we'll
490 // reset it and clear the FailedISel attribute in ResetMachineFunctions.
491 if (isFunctionFailedISel)
492 return true;
493
494 isFunctionRegBankSelected = Props.hasRegBankSelected();
495 isFunctionSelected = Props.hasSelected();
496 isFunctionTracksDebugUserValues = Props.hasTracksDebugUserValues();
497
498 if (PASS) {
499 auto *LISWrapper = PASS->getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
500 LiveInts = LISWrapper ? &LISWrapper->getLIS() : nullptr;
501 auto *LSWrapper = PASS->getAnalysisIfAvailable<LiveStacksWrapperLegacy>();
502 LiveStks = LSWrapper ? &LSWrapper->getLS() : nullptr;
503 auto *SIWrapper = PASS->getAnalysisIfAvailable<SlotIndexesWrapperPass>();
504 Indexes = SIWrapper ? &SIWrapper->getSI() : nullptr;
505 }
506 if (MFAM) {
507 MachineFunction &Func = const_cast<MachineFunction &>(MF);
508 LiveInts = MFAM->getCachedResult<LiveIntervalsAnalysis>(Func);
509 // TODO: LiveStks = MFAM->getCachedResult<LiveStacksAnalysis>(Func);
510 Indexes = MFAM->getCachedResult<SlotIndexesAnalysis>(Func);
511 }
512
513 verifySlotIndexes();
514
515 verifyProperties(MF);
516
517 visitMachineFunctionBefore();
518 for (const MachineBasicBlock &MBB : MF) {
519 visitMachineBasicBlockBefore(&MBB);
520 // Keep track of the current bundle header.
521 const MachineInstr *CurBundle = nullptr;
522 // Do we expect the next instruction to be part of the same bundle?
523 bool InBundle = false;
524
525 for (const MachineInstr &MI : MBB.instrs()) {
526 if (MI.getParent() != &MBB) {
527 report("Bad instruction parent pointer", &MBB);
528 OS << "Instruction: " << MI;
529 continue;
530 }
531
532 // Check for consistent bundle flags.
533 if (InBundle && !MI.isBundledWithPred())
534 report("Missing BundledPred flag, "
535 "BundledSucc was set on predecessor",
536 &MI);
537 if (!InBundle && MI.isBundledWithPred())
538 report("BundledPred flag is set, "
539 "but BundledSucc not set on predecessor",
540 &MI);
541
542 // Is this a bundle header?
543 if (!MI.isInsideBundle()) {
544 if (CurBundle)
545 visitMachineBundleAfter(CurBundle);
546 CurBundle = &MI;
547 visitMachineBundleBefore(CurBundle);
548 } else if (!CurBundle)
549 report("No bundle header", &MI);
550 visitMachineInstrBefore(&MI);
551 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
552 const MachineOperand &Op = MI.getOperand(I);
553 if (Op.getParent() != &MI) {
554 // Make sure to use correct addOperand / removeOperand / ChangeTo
555 // functions when replacing operands of a MachineInstr.
556 report("Instruction has operand with wrong parent set", &MI);
557 }
558
559 visitMachineOperand(&Op, I);
560 }
561 visitMachineInstrAfter(&MI);
562
563 // Was this the last bundled instruction?
564 InBundle = MI.isBundledWithSucc();
565 }
566 if (CurBundle)
567 visitMachineBundleAfter(CurBundle);
568 if (InBundle)
569 report("BundledSucc flag set on last instruction in block", &MBB.back());
570 visitMachineBasicBlockAfter(&MBB);
571 }
572 visitMachineFunctionAfter();
573
574 // Clean up.
575 regsLive.clear();
576 regsDefined.clear();
577 regsDead.clear();
578 regsKilled.clear();
579 regMasks.clear();
580 MBBInfoMap.clear();
581
582 return !ReportedErrs.hasError();
583}
584
585void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
586 assert(MF);
587 OS << '\n';
588 if (ReportedErrs.increment()) {
589 if (Banner)
590 OS << "# " << Banner << '\n';
591
592 if (LiveInts != nullptr)
593 LiveInts->print(OS);
594 else
595 MF->print(OS, Indexes);
596 }
597
598 OS << "*** Bad machine code: " << msg << " ***\n"
599 << "- function: " << MF->getName() << '\n';
600}
601
602void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
603 assert(MBB);
604 report(msg, MBB->getParent());
605 OS << "- basic block: " << printMBBReference(*MBB) << ' ' << MBB->getName()
606 << " (" << (const void *)MBB << ')';
607 if (Indexes)
608 OS << " [" << Indexes->getMBBStartIdx(MBB) << ';'
609 << Indexes->getMBBEndIdx(MBB) << ')';
610 OS << '\n';
611}
612
613void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
614 assert(MI);
615 report(msg, MI->getParent());
616 OS << "- instruction: ";
617 if (Indexes && Indexes->hasIndex(*MI))
618 OS << Indexes->getInstructionIndex(*MI) << '\t';
619 MI->print(OS, /*IsStandalone=*/true);
620}
621
622void MachineVerifier::report(const char *msg, const MachineOperand *MO,
623 unsigned MONum, LLT MOVRegType) {
624 assert(MO);
625 report(msg, MO->getParent());
626 OS << "- operand " << MONum << ": ";
627 MO->print(OS, MOVRegType, TRI);
628 OS << '\n';
629}
630
631void MachineVerifier::report(const Twine &Msg, const MachineInstr *MI) {
632 report(Msg.str().c_str(), MI);
633}
634
635void MachineVerifier::report_context(SlotIndex Pos) const {
636 OS << "- at: " << Pos << '\n';
637}
638
639void MachineVerifier::report_context(const LiveInterval &LI) const {
640 OS << "- interval: " << LI << '\n';
641}
642
643void MachineVerifier::report_context(const LiveRange &LR,
644 VirtRegOrUnit VRegOrUnit,
645 LaneBitmask LaneMask) const {
646 report_context_liverange(LR);
647 report_context_vreg_regunit(VRegOrUnit);
648 if (LaneMask.any())
649 report_context_lanemask(LaneMask);
650}
651
652void MachineVerifier::report_context(const LiveRange::Segment &S) const {
653 OS << "- segment: " << S << '\n';
654}
655
656void MachineVerifier::report_context(const VNInfo &VNI) const {
657 OS << "- ValNo: " << VNI.id << " (def " << VNI.def << ")\n";
658}
659
660void MachineVerifier::report_context_liverange(const LiveRange &LR) const {
661 OS << "- liverange: " << LR << '\n';
662}
663
664void MachineVerifier::report_context(MCPhysReg PReg) const {
665 OS << "- p. register: " << printReg(PReg, TRI) << '\n';
666}
667
668void MachineVerifier::report_context_vreg(Register VReg) const {
669 OS << "- v. register: " << printReg(VReg, TRI) << '\n';
670}
671
672void MachineVerifier::report_context_vreg_regunit(
673 VirtRegOrUnit VRegOrUnit) const {
674 if (VRegOrUnit.isVirtualReg()) {
675 report_context_vreg(VRegOrUnit.asVirtualReg());
676 } else {
677 OS << "- regunit: " << printRegUnit(VRegOrUnit.asMCRegUnit(), TRI)
678 << '\n';
679 }
680}
681
682void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask) const {
683 OS << "- lanemask: " << PrintLaneMask(LaneMask) << '\n';
684}
685
686void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
687 BBInfo &MInfo = MBBInfoMap[MBB];
688 if (!MInfo.reachable) {
689 MInfo.reachable = true;
690 for (const MachineBasicBlock *Succ : MBB->successors())
691 markReachable(Succ);
692 }
693}
694
695void MachineVerifier::visitMachineFunctionBefore() {
696 lastIndex = SlotIndex();
697 regsReserved = MRI->reservedRegsFrozen() ? MRI->getReservedRegs()
698 : TRI->getReservedRegs(*MF);
699
700 if (!MF->empty())
701 markReachable(&MF->front());
702
703 // Build a set of the basic blocks in the function.
704 FunctionBlocks.clear();
705 for (const auto &MBB : *MF) {
706 FunctionBlocks.insert(&MBB);
707 BBInfo &MInfo = MBBInfoMap[&MBB];
708
709 MInfo.Preds.insert_range(MBB.predecessors());
710 if (MInfo.Preds.size() != MBB.pred_size())
711 report("MBB has duplicate entries in its predecessor list.", &MBB);
712
713 MInfo.Succs.insert_range(MBB.successors());
714 if (MInfo.Succs.size() != MBB.succ_size())
715 report("MBB has duplicate entries in its successor list.", &MBB);
716 }
717
718 // Check that the register use lists are sane.
720
721 if (!MF->empty()) {
722 verifyStackFrame();
723 verifyStackProtector();
724 }
725}
726
727static bool hasPHIs(const MachineFunction &MF) {
728 return !MF.getProperties().hasNoPHIs() &&
729 any_of(MF, [](const MachineBasicBlock &MBB) {
730 return !MBB.phis().empty();
731 });
732}
733
734void
735MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
736 FirstTerminator = nullptr;
737 FirstNonPHI = nullptr;
738
739 if (MRI->tracksLiveness() && hasPHIs(*MF)) {
740 // If this block has allocatable physical registers live-in, check that
741 // it is an entry block or landing pad.
742 for (const auto &LI : MBB->liveins()) {
743 if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() &&
744 MBB->getIterator() != MBB->getParent()->begin() &&
746 report("MBB has allocatable live-in, but isn't entry, landing-pad, or "
747 "inlineasm-br-indirect-target.",
748 MBB);
749 report_context(LI.PhysReg);
750 }
751 }
752 }
753
754 if (MBB->isIRBlockAddressTaken()) {
756 report("ir-block-address-taken is associated with basic block not used by "
757 "a blockaddress.",
758 MBB);
759 }
760
761 // Count the number of landing pad successors.
763 for (const auto *succ : MBB->successors()) {
764 if (succ->isEHPad())
765 LandingPadSuccs.insert(succ);
766 if (!FunctionBlocks.count(succ))
767 report("MBB has successor that isn't part of the function.", MBB);
768 if (!MBBInfoMap[succ].Preds.count(MBB)) {
769 report("Inconsistent CFG", MBB);
770 OS << "MBB is not in the predecessor list of the successor "
771 << printMBBReference(*succ) << ".\n";
772 }
773 }
774
775 // Check the predecessor list.
776 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
777 if (!FunctionBlocks.count(Pred))
778 report("MBB has predecessor that isn't part of the function.", MBB);
779 if (!MBBInfoMap[Pred].Succs.count(MBB)) {
780 report("Inconsistent CFG", MBB);
781 OS << "MBB is not in the successor list of the predecessor "
782 << printMBBReference(*Pred) << ".\n";
783 }
784 }
785
786 const BasicBlock *BB = MBB->getBasicBlock();
787 const Function &F = MF->getFunction();
788 if (LandingPadSuccs.size() > 1 &&
789 !(BB && isa<SwitchInst>(BB->getTerminator())) &&
790 !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
791 report("MBB has more than one landing pad successor", MBB);
792
793 // Call analyzeBranch. If it succeeds, there several more conditions to check.
794 const MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
796 if (!TII->analyzeBranch(*MBB, TBB, FBB, Cond)) {
797 // Ok, analyzeBranch thinks it knows what's going on with this block. Let's
798 // check whether its answers match up with reality.
799 if (!TBB && !FBB) {
800 // Block falls through to its successor.
801 if (!MBB->empty() && MBB->back().isBarrier() &&
802 !TII->isPredicated(MBB->back())) {
803 report("MBB exits via unconditional fall-through but ends with a "
804 "barrier instruction!", MBB);
805 }
806 if (!Cond.empty()) {
807 report("MBB exits via unconditional fall-through but has a condition!",
808 MBB);
809 }
810 } else if (TBB && !FBB && Cond.empty()) {
811 // Block unconditionally branches somewhere.
812 if (MBB->empty()) {
813 report("MBB exits via unconditional branch but doesn't contain "
814 "any instructions!", MBB);
815 } else if (!MBB->back().isBarrier()) {
816 report("MBB exits via unconditional branch but doesn't end with a "
817 "barrier instruction!", MBB);
818 } else if (!MBB->back().isTerminator()) {
819 report("MBB exits via unconditional branch but the branch isn't a "
820 "terminator instruction!", MBB);
821 }
822 } else if (TBB && !FBB && !Cond.empty()) {
823 // Block conditionally branches somewhere, otherwise falls through.
824 if (MBB->empty()) {
825 report("MBB exits via conditional branch/fall-through but doesn't "
826 "contain any instructions!", MBB);
827 } else if (MBB->back().isBarrier()) {
828 report("MBB exits via conditional branch/fall-through but ends with a "
829 "barrier instruction!", MBB);
830 } else if (!MBB->back().isTerminator()) {
831 report("MBB exits via conditional branch/fall-through but the branch "
832 "isn't a terminator instruction!", MBB);
833 }
834 } else if (TBB && FBB) {
835 // Block conditionally branches somewhere, otherwise branches
836 // somewhere else.
837 if (MBB->empty()) {
838 report("MBB exits via conditional branch/branch but doesn't "
839 "contain any instructions!", MBB);
840 } else if (!MBB->back().isBarrier()) {
841 report("MBB exits via conditional branch/branch but doesn't end with a "
842 "barrier instruction!", MBB);
843 } else if (!MBB->back().isTerminator()) {
844 report("MBB exits via conditional branch/branch but the branch "
845 "isn't a terminator instruction!", MBB);
846 }
847 if (Cond.empty()) {
848 report("MBB exits via conditional branch/branch but there's no "
849 "condition!", MBB);
850 }
851 } else {
852 report("analyzeBranch returned invalid data!", MBB);
853 }
854
855 // Now check that the successors match up with the answers reported by
856 // analyzeBranch.
857 if (TBB && !MBB->isSuccessor(TBB))
858 report("MBB exits via jump or conditional branch, but its target isn't a "
859 "CFG successor!",
860 MBB);
861 if (FBB && !MBB->isSuccessor(FBB))
862 report("MBB exits via conditional branch, but its target isn't a CFG "
863 "successor!",
864 MBB);
865
866 // There might be a fallthrough to the next block if there's either no
867 // unconditional true branch, or if there's a condition, and one of the
868 // branches is missing.
869 bool Fallthrough = !TBB || (!Cond.empty() && !FBB);
870
871 // A conditional fallthrough must be an actual CFG successor, not
872 // unreachable. (Conversely, an unconditional fallthrough might not really
873 // be a successor, because the block might end in unreachable.)
874 if (!Cond.empty() && !FBB) {
876 if (MBBI == MF->end()) {
877 report("MBB conditionally falls through out of function!", MBB);
878 } else if (!MBB->isSuccessor(&*MBBI))
879 report("MBB exits via conditional branch/fall-through but the CFG "
880 "successors don't match the actual successors!",
881 MBB);
882 }
883
884 // Verify that there aren't any extra un-accounted-for successors.
885 for (const MachineBasicBlock *SuccMBB : MBB->successors()) {
886 // If this successor is one of the branch targets, it's okay.
887 if (SuccMBB == TBB || SuccMBB == FBB)
888 continue;
889 // If we might have a fallthrough, and the successor is the fallthrough
890 // block, that's also ok.
891 if (Fallthrough && SuccMBB == MBB->getNextNode())
892 continue;
893 // Also accept successors which are for exception-handling or might be
894 // inlineasm_br targets.
895 if (SuccMBB->isEHPad() || SuccMBB->isInlineAsmBrIndirectTarget())
896 continue;
897 report("MBB has unexpected successors which are not branch targets, "
898 "fallthrough, EHPads, or inlineasm_br targets.",
899 MBB);
900 }
901 }
902
903 regsLive.clear();
904 if (MRI->tracksLiveness()) {
905 for (const auto &LI : MBB->liveins()) {
906 if (!LI.PhysReg.isPhysical()) {
907 report("MBB live-in list contains non-physical register", MBB);
908 continue;
909 }
910 regsLive.insert_range(TRI->subregs_inclusive(LI.PhysReg));
911 }
912 }
913
914 const MachineFrameInfo &MFI = MF->getFrameInfo();
915 BitVector PR = MFI.getPristineRegs(*MF);
916 for (unsigned I : PR.set_bits())
917 regsLive.insert_range(TRI->subregs_inclusive(I));
918
919 regsKilled.clear();
920 regsDefined.clear();
921
922 if (Indexes)
923 lastIndex = Indexes->getMBBStartIdx(MBB);
924}
925
926// This function gets called for all bundle headers, including normal
927// stand-alone unbundled instructions.
928void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
929 if (Indexes && Indexes->hasIndex(*MI)) {
930 SlotIndex idx = Indexes->getInstructionIndex(*MI);
931 if (!(idx > lastIndex)) {
932 report("Instruction index out of order", MI);
933 OS << "Last instruction was at " << lastIndex << '\n';
934 }
935 lastIndex = idx;
936 }
937
938 // Ensure non-terminators don't follow terminators.
939 if (MI->isTerminator()) {
940 if (!FirstTerminator)
941 FirstTerminator = MI;
942 } else if (FirstTerminator) {
943 // For GlobalISel, G_INVOKE_REGION_START is a terminator that we allow to
944 // precede non-terminators.
945 if (FirstTerminator->getOpcode() != TargetOpcode::G_INVOKE_REGION_START) {
946 report("Non-terminator instruction after the first terminator", MI);
947 OS << "First terminator was:\t" << *FirstTerminator;
948 }
949 }
950}
951
952// The operands on an INLINEASM instruction must follow a template.
953// Verify that the flag operands make sense.
954void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
955 // The first two operands on INLINEASM are the asm string and global flags.
956 if (MI->getNumOperands() < 2) {
957 report("Too few operands on inline asm", MI);
958 return;
959 }
960 if (!MI->getOperand(0).isSymbol())
961 report("Asm string must be an external symbol", MI);
962 if (!MI->getOperand(1).isImm())
963 report("Asm flags must be an immediate", MI);
964 // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
965 // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16,
966 // and Extra_IsConvergent = 32, Extra_MayUnwind = 64.
967 if (!isUInt<7>(MI->getOperand(1).getImm()))
968 report("Unknown asm flags", &MI->getOperand(1), 1);
969
970 static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed");
971
972 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
973 unsigned NumOps;
974 for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
975 const MachineOperand &MO = MI->getOperand(OpNo);
976 // There may be implicit ops after the fixed operands.
977 if (!MO.isImm())
978 break;
979 const InlineAsm::Flag F(MO.getImm());
980 NumOps = 1 + F.getNumOperandRegisters();
981 }
982
983 if (OpNo > MI->getNumOperands())
984 report("Missing operands in last group", MI);
985
986 // An optional MDNode follows the groups.
987 if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
988 ++OpNo;
989
990 // All trailing operands must be implicit registers.
991 for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
992 const MachineOperand &MO = MI->getOperand(OpNo);
993 if (!MO.isReg() || !MO.isImplicit())
994 report("Expected implicit register after groups", &MO, OpNo);
995 }
996
997 if (MI->getOpcode() == TargetOpcode::INLINEASM_BR) {
998 const MachineBasicBlock *MBB = MI->getParent();
999
1000 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = MI->getNumOperands();
1001 i != e; ++i) {
1002 const MachineOperand &MO = MI->getOperand(i);
1003
1004 if (!MO.isMBB())
1005 continue;
1006
1007 // Check the successor & predecessor lists look ok, assume they are
1008 // not. Find the indirect target without going through the successors.
1009 const MachineBasicBlock *IndirectTargetMBB = MO.getMBB();
1010 if (!IndirectTargetMBB) {
1011 report("INLINEASM_BR indirect target does not exist", &MO, i);
1012 break;
1013 }
1014
1015 if (!MBB->isSuccessor(IndirectTargetMBB))
1016 report("INLINEASM_BR indirect target missing from successor list", &MO,
1017 i);
1018
1019 if (!IndirectTargetMBB->isPredecessor(MBB))
1020 report("INLINEASM_BR indirect target predecessor list missing parent",
1021 &MO, i);
1022 }
1023 }
1024}
1025
1026bool MachineVerifier::verifyAllRegOpsScalar(const MachineInstr &MI,
1027 const MachineRegisterInfo &MRI) {
1028 if (none_of(MI.explicit_operands(), [&MRI](const MachineOperand &Op) {
1029 if (!Op.isReg())
1030 return false;
1031 const auto Reg = Op.getReg();
1032 if (Reg.isPhysical())
1033 return false;
1034 return !MRI.getType(Reg).isScalar();
1035 }))
1036 return true;
1037 report("All register operands must have scalar types", &MI);
1038 return false;
1039}
1040
1041/// Check that types are consistent when two operands need to have the same
1042/// number of vector elements.
1043/// \return true if the types are valid.
1044bool MachineVerifier::verifyVectorElementMatch(LLT Ty0, LLT Ty1,
1045 const MachineInstr *MI) {
1046 if (Ty0.isVector() != Ty1.isVector()) {
1047 report("operand types must be all-vector or all-scalar", MI);
1048 // Generally we try to report as many issues as possible at once, but in
1049 // this case it's not clear what should we be comparing the size of the
1050 // scalar with: the size of the whole vector or its lane. Instead of
1051 // making an arbitrary choice and emitting not so helpful message, let's
1052 // avoid the extra noise and stop here.
1053 return false;
1054 }
1055
1056 if (Ty0.isVector() && Ty0.getElementCount() != Ty1.getElementCount()) {
1057 report("operand types must preserve number of vector elements", MI);
1058 return false;
1059 }
1060
1061 return true;
1062}
1063
1064bool MachineVerifier::verifyGIntrinsicSideEffects(const MachineInstr *MI) {
1065 auto Opcode = MI->getOpcode();
1066 bool NoSideEffects = Opcode == TargetOpcode::G_INTRINSIC ||
1067 Opcode == TargetOpcode::G_INTRINSIC_CONVERGENT;
1068 unsigned IntrID = cast<GIntrinsic>(MI)->getIntrinsicID();
1069 if (IntrID != 0 && IntrID < Intrinsic::num_intrinsics) {
1071 MF->getFunction().getContext(), static_cast<Intrinsic::ID>(IntrID));
1072 bool DeclHasSideEffects = !Attrs.getMemoryEffects().doesNotAccessMemory();
1073 if (NoSideEffects && DeclHasSideEffects) {
1074 report(Twine(TII->getName(Opcode),
1075 " used with intrinsic that accesses memory"),
1076 MI);
1077 return false;
1078 }
1079 if (!NoSideEffects && !DeclHasSideEffects) {
1080 report(Twine(TII->getName(Opcode), " used with readnone intrinsic"), MI);
1081 return false;
1082 }
1083 }
1084
1085 return true;
1086}
1087
1088bool MachineVerifier::verifyGIntrinsicConvergence(const MachineInstr *MI) {
1089 auto Opcode = MI->getOpcode();
1090 bool NotConvergent = Opcode == TargetOpcode::G_INTRINSIC ||
1091 Opcode == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS;
1092 unsigned IntrID = cast<GIntrinsic>(MI)->getIntrinsicID();
1093 if (IntrID != 0 && IntrID < Intrinsic::num_intrinsics) {
1095 MF->getFunction().getContext(), static_cast<Intrinsic::ID>(IntrID));
1096 bool DeclIsConvergent = Attrs.hasAttribute(Attribute::Convergent);
1097 if (NotConvergent && DeclIsConvergent) {
1098 report(Twine(TII->getName(Opcode), " used with a convergent intrinsic"),
1099 MI);
1100 return false;
1101 }
1102 if (!NotConvergent && !DeclIsConvergent) {
1103 report(
1104 Twine(TII->getName(Opcode), " used with a non-convergent intrinsic"),
1105 MI);
1106 return false;
1107 }
1108 }
1109
1110 return true;
1111}
1112
1113void MachineVerifier::verifyPreISelGenericInstruction(const MachineInstr *MI) {
1114 if (isFunctionSelected)
1115 report("Unexpected generic instruction in a Selected function", MI);
1116
1117 const MCInstrDesc &MCID = MI->getDesc();
1118 unsigned NumOps = MI->getNumOperands();
1119
1120 // Branches must reference a basic block if they are not indirect
1121 if (MI->isBranch() && !MI->isIndirectBranch()) {
1122 bool HasMBB = false;
1123 for (const MachineOperand &Op : MI->operands()) {
1124 if (Op.isMBB()) {
1125 HasMBB = true;
1126 break;
1127 }
1128 }
1129
1130 if (!HasMBB) {
1131 report("Branch instruction is missing a basic block operand or "
1132 "isIndirectBranch property",
1133 MI);
1134 }
1135 }
1136
1137 // Check types.
1139 for (unsigned I = 0, E = std::min(MCID.getNumOperands(), NumOps);
1140 I != E; ++I) {
1141 if (!MCID.operands()[I].isGenericType())
1142 continue;
1143 // Generic instructions specify type equality constraints between some of
1144 // their operands. Make sure these are consistent.
1145 size_t TypeIdx = MCID.operands()[I].getGenericTypeIndex();
1146 Types.resize(std::max(TypeIdx + 1, Types.size()));
1147
1148 const MachineOperand *MO = &MI->getOperand(I);
1149 if (!MO->isReg()) {
1150 report("generic instruction must use register operands", MI);
1151 continue;
1152 }
1153
1154 LLT OpTy = MRI->getType(MO->getReg());
1155 // Don't report a type mismatch if there is no actual mismatch, only a
1156 // type missing, to reduce noise:
1157 if (OpTy.isValid()) {
1158 // Only the first valid type for a type index will be printed: don't
1159 // overwrite it later so it's always clear which type was expected:
1160 if (!Types[TypeIdx].isValid())
1161 Types[TypeIdx] = OpTy;
1162 else if (Types[TypeIdx] != OpTy)
1163 report("Type mismatch in generic instruction", MO, I, OpTy);
1164 } else {
1165 // Generic instructions must have types attached to their operands.
1166 report("Generic instruction is missing a virtual register type", MO, I);
1167 }
1168 }
1169
1170 // Generic opcodes must not have physical register operands.
1171 for (unsigned I = 0; I < MI->getNumOperands(); ++I) {
1172 const MachineOperand *MO = &MI->getOperand(I);
1173 if (MO->isReg() && MO->getReg().isPhysical())
1174 report("Generic instruction cannot have physical register", MO, I);
1175 }
1176
1177 // Avoid out of bounds in checks below. This was already reported earlier.
1178 if (MI->getNumOperands() < MCID.getNumOperands())
1179 return;
1180
1182 if (!TII->verifyInstruction(*MI, ErrorInfo))
1183 report(ErrorInfo.data(), MI);
1184
1185 // Verify properties of various specific instruction types
1186 unsigned Opc = MI->getOpcode();
1187 switch (Opc) {
1188 case TargetOpcode::G_ASSERT_SEXT:
1189 case TargetOpcode::G_ASSERT_ZEXT: {
1190 std::string OpcName =
1191 Opc == TargetOpcode::G_ASSERT_ZEXT ? "G_ASSERT_ZEXT" : "G_ASSERT_SEXT";
1192 if (!MI->getOperand(2).isImm()) {
1193 report(Twine(OpcName, " expects an immediate operand #2"), MI);
1194 break;
1195 }
1196
1197 Register Dst = MI->getOperand(0).getReg();
1198 Register Src = MI->getOperand(1).getReg();
1199 LLT SrcTy = MRI->getType(Src);
1200 int64_t Imm = MI->getOperand(2).getImm();
1201 if (Imm <= 0) {
1202 report(Twine(OpcName, " size must be >= 1"), MI);
1203 break;
1204 }
1205
1206 if (Imm >= SrcTy.getScalarSizeInBits()) {
1207 report(Twine(OpcName, " size must be less than source bit width"), MI);
1208 break;
1209 }
1210
1211 const RegisterBank *SrcRB = RBI->getRegBank(Src, *MRI, *TRI);
1212 const RegisterBank *DstRB = RBI->getRegBank(Dst, *MRI, *TRI);
1213
1214 // Allow only the source bank to be set.
1215 if ((SrcRB && DstRB && SrcRB != DstRB) || (DstRB && !SrcRB)) {
1216 report(Twine(OpcName, " cannot change register bank"), MI);
1217 break;
1218 }
1219
1220 // Don't allow a class change. Do allow member class->regbank.
1221 const TargetRegisterClass *DstRC = MRI->getRegClassOrNull(Dst);
1222 if (DstRC && DstRC != MRI->getRegClassOrNull(Src)) {
1223 report(
1224 Twine(OpcName, " source and destination register classes must match"),
1225 MI);
1226 break;
1227 }
1228
1229 break;
1230 }
1231
1232 case TargetOpcode::G_CONSTANT:
1233 case TargetOpcode::G_FCONSTANT: {
1234 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1235 if (DstTy.isVector())
1236 report("Instruction cannot use a vector result type", MI);
1237
1238 if (MI->getOpcode() == TargetOpcode::G_CONSTANT) {
1239 if (!MI->getOperand(1).isCImm()) {
1240 report("G_CONSTANT operand must be cimm", MI);
1241 break;
1242 }
1243
1244 const ConstantInt *CI = MI->getOperand(1).getCImm();
1245 if (CI->getBitWidth() != DstTy.getSizeInBits())
1246 report("inconsistent constant size", MI);
1247 } else {
1248 if (!MI->getOperand(1).isFPImm()) {
1249 report("G_FCONSTANT operand must be fpimm", MI);
1250 break;
1251 }
1252 const ConstantFP *CF = MI->getOperand(1).getFPImm();
1253
1255 DstTy.getSizeInBits()) {
1256 report("inconsistent constant size", MI);
1257 }
1258 }
1259
1260 break;
1261 }
1262 case TargetOpcode::G_LOAD:
1263 case TargetOpcode::G_STORE:
1264 case TargetOpcode::G_ZEXTLOAD:
1265 case TargetOpcode::G_SEXTLOAD:
1266 case TargetOpcode::G_FPEXTLOAD:
1267 case TargetOpcode::G_FPTRUNCSTORE: {
1268 LLT ValTy = MRI->getType(MI->getOperand(0).getReg());
1269 LLT PtrTy = MRI->getType(MI->getOperand(1).getReg());
1270 if (!PtrTy.isPointer())
1271 report("Generic memory instruction must access a pointer", MI);
1272
1273 // Generic loads and stores must have a single MachineMemOperand
1274 // describing that access.
1275 if (!MI->hasOneMemOperand()) {
1276 report("Generic instruction accessing memory must have one mem operand",
1277 MI);
1278 } else {
1279 const MachineMemOperand &MMO = **MI->memoperands_begin();
1280 if (isa<GExtLoad>(*MI)) {
1282 ValTy.getSizeInBits()))
1283 report("Generic extload must have a narrower memory type", MI);
1284 } else if (isa<GFPTruncStore>(*MI)) {
1286 ValTy.getSizeInBits()))
1287 report("Generic truncstore must have a narrower memory type", MI);
1288 } else if (MI->getOpcode() == TargetOpcode::G_LOAD) {
1290 ValTy.getSizeInBytes()))
1291 report("load memory size cannot exceed result size", MI);
1292
1293 if (MMO.getRanges()) {
1294 ConstantInt *i =
1296 const LLT RangeTy = LLT::scalar(i->getIntegerType()->getBitWidth());
1297 const LLT MemTy = MMO.getMemoryType();
1298 if (MemTy.getScalarType() != RangeTy ||
1299 ValTy.isScalar() != MemTy.isScalar() ||
1300 (ValTy.isVector() &&
1301 ValTy.getNumElements() != MemTy.getNumElements())) {
1302 report("range is incompatible with the result type", MI);
1303 }
1304 }
1305 } else if (MI->getOpcode() == TargetOpcode::G_STORE) {
1307 MMO.getSize().getValue()))
1308 report("store memory size cannot exceed value size", MI);
1309 }
1310
1311 const AtomicOrdering Order = MMO.getSuccessOrdering();
1312 if (isa<GAnyStore>(*MI)) {
1313 if (Order == AtomicOrdering::Acquire ||
1315 report("atomic store cannot use acquire ordering", MI);
1316
1317 } else {
1318 if (Order == AtomicOrdering::Release ||
1320 report("atomic load cannot use release ordering", MI);
1321 }
1322 }
1323
1324 break;
1325 }
1326 case TargetOpcode::G_PHI: {
1327 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1328 if (!DstTy.isValid() || !all_of(drop_begin(MI->operands()),
1329 [this, &DstTy](const MachineOperand &MO) {
1330 if (!MO.isReg())
1331 return true;
1332 LLT Ty = MRI->getType(MO.getReg());
1333 if (!Ty.isValid() || (Ty != DstTy))
1334 return false;
1335 return true;
1336 }))
1337 report("Generic Instruction G_PHI has operands with incompatible/missing "
1338 "types",
1339 MI);
1340 break;
1341 }
1342 case TargetOpcode::G_BITCAST: {
1343 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1344 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1345 if (!DstTy.isValid() || !SrcTy.isValid())
1346 break;
1347
1348 if (SrcTy.isPointer() != DstTy.isPointer())
1349 report("bitcast cannot convert between pointers and other types", MI);
1350
1351 if (SrcTy.getSizeInBits() != DstTy.getSizeInBits())
1352 report("bitcast sizes must match", MI);
1353
1354 bool SameType = SrcTy.getKind() == DstTy.getKind();
1355 if (SameType && SrcTy.isPointerOrPointerVector())
1356 SameType &= SrcTy.getAddressSpace() == DstTy.getAddressSpace();
1357
1358 SameType &= SrcTy.getScalarSizeInBits() == DstTy.getScalarSizeInBits();
1359
1360 if (SameType && SrcTy.isVector())
1361 SameType &= SrcTy.getElementCount() == DstTy.getElementCount();
1362 if (SameType && SrcTy.isFloatOrFloatVector())
1363 SameType &= SrcTy.getFpSemantics() == DstTy.getFpSemantics();
1364
1365 if (SameType)
1366 report("bitcast must change the type", MI);
1367
1368 break;
1369 }
1370 case TargetOpcode::G_INTTOPTR:
1371 case TargetOpcode::G_PTRTOINT:
1372 case TargetOpcode::G_ADDRSPACE_CAST: {
1373 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1374 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1375 if (!DstTy.isValid() || !SrcTy.isValid())
1376 break;
1377
1378 verifyVectorElementMatch(DstTy, SrcTy, MI);
1379
1380 DstTy = DstTy.getScalarType();
1381 SrcTy = SrcTy.getScalarType();
1382
1383 if (MI->getOpcode() == TargetOpcode::G_INTTOPTR) {
1384 if (!DstTy.isPointer())
1385 report("inttoptr result type must be a pointer", MI);
1386 if (SrcTy.isPointer())
1387 report("inttoptr source type must not be a pointer", MI);
1388 } else if (MI->getOpcode() == TargetOpcode::G_PTRTOINT) {
1389 if (!SrcTy.isPointer())
1390 report("ptrtoint source type must be a pointer", MI);
1391 if (DstTy.isPointer())
1392 report("ptrtoint result type must not be a pointer", MI);
1393 } else {
1394 assert(MI->getOpcode() == TargetOpcode::G_ADDRSPACE_CAST);
1395 if (!SrcTy.isPointer() || !DstTy.isPointer())
1396 report("addrspacecast types must be pointers", MI);
1397 else {
1398 if (SrcTy.getAddressSpace() == DstTy.getAddressSpace())
1399 report("addrspacecast must convert different address spaces", MI);
1400 }
1401 }
1402
1403 break;
1404 }
1405 case TargetOpcode::G_PTR_ADD: {
1406 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1407 LLT PtrTy = MRI->getType(MI->getOperand(1).getReg());
1408 LLT OffsetTy = MRI->getType(MI->getOperand(2).getReg());
1409 if (!DstTy.isValid() || !PtrTy.isValid() || !OffsetTy.isValid())
1410 break;
1411
1412 if (!PtrTy.isPointerOrPointerVector())
1413 report("gep first operand must be a pointer", MI);
1414
1415 if (OffsetTy.isPointerOrPointerVector())
1416 report("gep offset operand must not be a pointer", MI);
1417
1418 if (PtrTy.isPointerOrPointerVector()) {
1419 const DataLayout &DL = MF->getDataLayout();
1420 unsigned AS = PtrTy.getAddressSpace();
1421 unsigned IndexSizeInBits = DL.getIndexSize(AS) * 8;
1422 if (OffsetTy.getScalarSizeInBits() != IndexSizeInBits) {
1423 report("gep offset operand must match index size for address space",
1424 MI);
1425 }
1426 }
1427
1428 // TODO: Is the offset allowed to be a scalar with a vector?
1429 break;
1430 }
1431 case TargetOpcode::G_PTRMASK: {
1432 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1433 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1434 LLT MaskTy = MRI->getType(MI->getOperand(2).getReg());
1435 if (!DstTy.isValid() || !SrcTy.isValid() || !MaskTy.isValid())
1436 break;
1437
1438 if (!DstTy.isPointerOrPointerVector())
1439 report("ptrmask result type must be a pointer", MI);
1440
1441 if (!MaskTy.getScalarType().isScalar())
1442 report("ptrmask mask type must be an integer", MI);
1443
1444 verifyVectorElementMatch(DstTy, MaskTy, MI);
1445 break;
1446 }
1447 case TargetOpcode::G_SEXT:
1448 case TargetOpcode::G_ZEXT:
1449 case TargetOpcode::G_ANYEXT:
1450 case TargetOpcode::G_TRUNC:
1451 case TargetOpcode::G_TRUNC_SSAT_S:
1452 case TargetOpcode::G_TRUNC_SSAT_U:
1453 case TargetOpcode::G_TRUNC_USAT_U:
1454 case TargetOpcode::G_FPEXT:
1455 case TargetOpcode::G_FPTRUNC: {
1456 // Number of operands and presense of types is already checked (and
1457 // reported in case of any issues), so no need to report them again. As
1458 // we're trying to report as many issues as possible at once, however, the
1459 // instructions aren't guaranteed to have the right number of operands or
1460 // types attached to them at this point
1461 assert(MCID.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}");
1462 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1463 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1464 if (!DstTy.isValid() || !SrcTy.isValid())
1465 break;
1466
1468 report("Generic extend/truncate can not operate on pointers", MI);
1469
1470 verifyVectorElementMatch(DstTy, SrcTy, MI);
1471
1472 unsigned DstSize = DstTy.getScalarSizeInBits();
1473 unsigned SrcSize = SrcTy.getScalarSizeInBits();
1474 switch (MI->getOpcode()) {
1475 default:
1476 if (DstSize <= SrcSize)
1477 report("Generic extend has destination type no larger than source", MI);
1478 break;
1479 case TargetOpcode::G_TRUNC:
1480 case TargetOpcode::G_TRUNC_SSAT_S:
1481 case TargetOpcode::G_TRUNC_SSAT_U:
1482 case TargetOpcode::G_TRUNC_USAT_U:
1483 case TargetOpcode::G_FPTRUNC:
1484 if (DstSize >= SrcSize)
1485 report("Generic truncate has destination type no smaller than source",
1486 MI);
1487 break;
1488 }
1489 break;
1490 }
1491 case TargetOpcode::G_SELECT: {
1492 LLT SelTy = MRI->getType(MI->getOperand(0).getReg());
1493 LLT CondTy = MRI->getType(MI->getOperand(1).getReg());
1494 if (!SelTy.isValid() || !CondTy.isValid())
1495 break;
1496
1497 // Scalar condition select on a vector is valid.
1498 if (CondTy.isVector())
1499 verifyVectorElementMatch(SelTy, CondTy, MI);
1500 break;
1501 }
1502 case TargetOpcode::G_MERGE_VALUES: {
1503 // G_MERGE_VALUES should only be used to merge scalars into a larger scalar,
1504 // e.g. s2N = MERGE sN, sN
1505 // Merging multiple scalars into a vector is not allowed, should use
1506 // G_BUILD_VECTOR for that.
1507 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1508 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1509 if (DstTy.isVector() || SrcTy.isVector())
1510 report("G_MERGE_VALUES cannot operate on vectors", MI);
1511
1512 const unsigned NumOps = MI->getNumOperands();
1513 if (DstTy.getSizeInBits() != SrcTy.getSizeInBits() * (NumOps - 1))
1514 report("G_MERGE_VALUES result size is inconsistent", MI);
1515
1516 for (unsigned I = 2; I != NumOps; ++I) {
1517 if (MRI->getType(MI->getOperand(I).getReg()) != SrcTy)
1518 report("G_MERGE_VALUES source types do not match", MI);
1519 }
1520
1521 break;
1522 }
1523 case TargetOpcode::G_UNMERGE_VALUES: {
1524 unsigned NumDsts = MI->getNumOperands() - 1;
1525 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1526 for (unsigned i = 1; i < NumDsts; ++i) {
1527 if (MRI->getType(MI->getOperand(i).getReg()) != DstTy) {
1528 report("G_UNMERGE_VALUES destination types do not match", MI);
1529 break;
1530 }
1531 }
1532
1533 LLT SrcTy = MRI->getType(MI->getOperand(NumDsts).getReg());
1534 if (DstTy.isVector()) {
1535 // This case is the converse of G_CONCAT_VECTORS.
1536 if (!SrcTy.isVector() ||
1537 (SrcTy.getScalarType() != DstTy.getScalarType() &&
1538 !SrcTy.isPointerVector()) ||
1539 SrcTy.isScalableVector() != DstTy.isScalableVector() ||
1540 SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits())
1541 report("G_UNMERGE_VALUES source operand does not match vector "
1542 "destination operands",
1543 MI);
1544 } else if (SrcTy.isVector()) {
1545 // This case is the converse of G_BUILD_VECTOR, but relaxed to allow
1546 // mismatched types as long as the total size matches:
1547 // %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<4 x s32>)
1548 if (SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits())
1549 report("G_UNMERGE_VALUES vector source operand does not match scalar "
1550 "destination operands",
1551 MI);
1552 } else {
1553 // This case is the converse of G_MERGE_VALUES.
1554 if (SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits()) {
1555 report("G_UNMERGE_VALUES scalar source operand does not match scalar "
1556 "destination operands",
1557 MI);
1558 }
1559 }
1560 break;
1561 }
1562 case TargetOpcode::G_BUILD_VECTOR: {
1563 // Source types must be scalars, dest type a vector. Total size of scalars
1564 // must match the dest vector size.
1565 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1566 LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
1567 if (!DstTy.isVector() || SrcEltTy.isVector()) {
1568 report("G_BUILD_VECTOR must produce a vector from scalar operands", MI);
1569 break;
1570 }
1571
1572 if (DstTy.getElementType() != SrcEltTy)
1573 report("G_BUILD_VECTOR result element type must match source type", MI);
1574
1575 if (DstTy.getNumElements() != MI->getNumOperands() - 1)
1576 report("G_BUILD_VECTOR must have an operand for each element", MI);
1577
1578 for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1579 if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
1580 report("G_BUILD_VECTOR source operand types are not homogeneous", MI);
1581
1582 break;
1583 }
1584 case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
1585 // Source types must be scalars, dest type a vector. Scalar types must be
1586 // larger than the dest vector elt type, as this is a truncating operation.
1587 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1588 LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
1589 if (!DstTy.isVector() || SrcEltTy.isVector())
1590 report("G_BUILD_VECTOR_TRUNC must produce a vector from scalar operands",
1591 MI);
1592 for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1593 if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
1594 report("G_BUILD_VECTOR_TRUNC source operand types are not homogeneous",
1595 MI);
1596 if (SrcEltTy.getSizeInBits() <= DstTy.getElementType().getSizeInBits())
1597 report("G_BUILD_VECTOR_TRUNC source operand types are not larger than "
1598 "dest elt type",
1599 MI);
1600 break;
1601 }
1602 case TargetOpcode::G_CONCAT_VECTORS: {
1603 // Source types should be vectors, and total size should match the dest
1604 // vector size.
1605 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1606 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1607 if (!DstTy.isVector() || !SrcTy.isVector())
1608 report("G_CONCAT_VECTOR requires vector source and destination operands",
1609 MI);
1610
1611 if (MI->getNumOperands() < 3)
1612 report("G_CONCAT_VECTOR requires at least 2 source operands", MI);
1613
1614 for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1615 if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
1616 report("G_CONCAT_VECTOR source operand types are not homogeneous", MI);
1617 if (DstTy.getElementCount() !=
1618 SrcTy.getElementCount() * (MI->getNumOperands() - 1))
1619 report("G_CONCAT_VECTOR num dest and source elements should match", MI);
1620 break;
1621 }
1622 case TargetOpcode::G_ICMP:
1623 case TargetOpcode::G_FCMP: {
1624 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1625 LLT SrcTy = MRI->getType(MI->getOperand(2).getReg());
1626
1627 if ((DstTy.isVector() != SrcTy.isVector()) ||
1628 (DstTy.isVector() &&
1629 DstTy.getElementCount() != SrcTy.getElementCount()))
1630 report("Generic vector icmp/fcmp must preserve number of lanes", MI);
1631
1632 break;
1633 }
1634 case TargetOpcode::G_SCMP:
1635 case TargetOpcode::G_UCMP: {
1636 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1637 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1638
1639 if (SrcTy.isPointerOrPointerVector()) {
1640 report("Generic scmp/ucmp does not support pointers as operands", MI);
1641 break;
1642 }
1643
1644 if (DstTy.isPointerOrPointerVector()) {
1645 report("Generic scmp/ucmp does not support pointers as a result", MI);
1646 break;
1647 }
1648
1649 if (DstTy.getScalarSizeInBits() < 2) {
1650 report("Result type must be at least 2 bits wide", MI);
1651 break;
1652 }
1653
1654 if ((DstTy.isVector() != SrcTy.isVector()) ||
1655 (DstTy.isVector() &&
1656 DstTy.getElementCount() != SrcTy.getElementCount())) {
1657 report("Generic vector scmp/ucmp must preserve number of lanes", MI);
1658 break;
1659 }
1660
1661 break;
1662 }
1663 case TargetOpcode::G_EXTRACT: {
1664 const MachineOperand &SrcOp = MI->getOperand(1);
1665 if (!SrcOp.isReg()) {
1666 report("extract source must be a register", MI);
1667 break;
1668 }
1669
1670 const MachineOperand &OffsetOp = MI->getOperand(2);
1671 if (!OffsetOp.isImm()) {
1672 report("extract offset must be a constant", MI);
1673 break;
1674 }
1675
1676 unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits();
1677 unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits();
1678 if (SrcSize == DstSize)
1679 report("extract source must be larger than result", MI);
1680
1681 if (DstSize + OffsetOp.getImm() > SrcSize)
1682 report("extract reads past end of register", MI);
1683 break;
1684 }
1685 case TargetOpcode::G_INSERT: {
1686 const MachineOperand &SrcOp = MI->getOperand(2);
1687 if (!SrcOp.isReg()) {
1688 report("insert source must be a register", MI);
1689 break;
1690 }
1691
1692 const MachineOperand &OffsetOp = MI->getOperand(3);
1693 if (!OffsetOp.isImm()) {
1694 report("insert offset must be a constant", MI);
1695 break;
1696 }
1697
1698 unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits();
1699 unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits();
1700
1701 if (DstSize <= SrcSize)
1702 report("inserted size must be smaller than total register", MI);
1703
1704 if (SrcSize + OffsetOp.getImm() > DstSize)
1705 report("insert writes past end of register", MI);
1706
1707 break;
1708 }
1709 case TargetOpcode::G_JUMP_TABLE: {
1710 if (!MI->getOperand(1).isJTI())
1711 report("G_JUMP_TABLE source operand must be a jump table index", MI);
1712 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1713 if (!DstTy.isPointer())
1714 report("G_JUMP_TABLE dest operand must have a pointer type", MI);
1715 break;
1716 }
1717 case TargetOpcode::G_BRJT: {
1718 if (!MRI->getType(MI->getOperand(0).getReg()).isPointer())
1719 report("G_BRJT src operand 0 must be a pointer type", MI);
1720
1721 if (!MI->getOperand(1).isJTI())
1722 report("G_BRJT src operand 1 must be a jump table index", MI);
1723
1724 const auto &IdxOp = MI->getOperand(2);
1725 if (!IdxOp.isReg() || MRI->getType(IdxOp.getReg()).isPointer())
1726 report("G_BRJT src operand 2 must be a scalar reg type", MI);
1727 break;
1728 }
1729 case TargetOpcode::G_INTRINSIC:
1730 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
1731 case TargetOpcode::G_INTRINSIC_CONVERGENT:
1732 case TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS: {
1733 // TODO: Should verify number of def and use operands, but the current
1734 // interface requires passing in IR types for mangling.
1735 const MachineOperand &IntrIDOp = MI->getOperand(MI->getNumExplicitDefs());
1736 if (!IntrIDOp.isIntrinsicID()) {
1737 report("G_INTRINSIC first src operand must be an intrinsic ID", MI);
1738 break;
1739 }
1740
1741 if (!verifyGIntrinsicSideEffects(MI))
1742 break;
1743 if (!verifyGIntrinsicConvergence(MI))
1744 break;
1745
1746 break;
1747 }
1748 case TargetOpcode::G_SEXT_INREG: {
1749 if (!MI->getOperand(2).isImm()) {
1750 report("G_SEXT_INREG expects an immediate operand #2", MI);
1751 break;
1752 }
1753
1754 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1755 int64_t Imm = MI->getOperand(2).getImm();
1756 if (Imm <= 0)
1757 report("G_SEXT_INREG size must be >= 1", MI);
1758 if (Imm >= SrcTy.getScalarSizeInBits())
1759 report("G_SEXT_INREG size must be less than source bit width", MI);
1760 break;
1761 }
1762 case TargetOpcode::G_BSWAP: {
1763 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1764 if (DstTy.getScalarSizeInBits() % 16 != 0)
1765 report("G_BSWAP size must be a multiple of 16 bits", MI);
1766 break;
1767 }
1768 case TargetOpcode::G_VSCALE: {
1769 if (!MI->getOperand(1).isCImm()) {
1770 report("G_VSCALE operand must be cimm", MI);
1771 break;
1772 }
1773 if (MI->getOperand(1).getCImm()->isZero()) {
1774 report("G_VSCALE immediate cannot be zero", MI);
1775 break;
1776 }
1777 break;
1778 }
1779 case TargetOpcode::G_STEP_VECTOR: {
1780 if (!MI->getOperand(1).isCImm()) {
1781 report("operand must be cimm", MI);
1782 break;
1783 }
1784
1785 if (!MI->getOperand(1).getCImm()->getValue().isStrictlyPositive()) {
1786 report("step must be > 0", MI);
1787 break;
1788 }
1789
1790 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1791 if (!DstTy.isScalableVector()) {
1792 report("Destination type must be a scalable vector", MI);
1793 break;
1794 }
1795
1796 // <vscale x 2 x p0>
1797 if (!DstTy.getElementType().isScalar()) {
1798 report("Destination element type must be scalar", MI);
1799 break;
1800 }
1801
1802 if (MI->getOperand(1).getCImm()->getBitWidth() !=
1804 report("step bitwidth differs from result type element bitwidth", MI);
1805 break;
1806 }
1807 break;
1808 }
1809 case TargetOpcode::G_INSERT_SUBVECTOR: {
1810 const MachineOperand &Src0Op = MI->getOperand(1);
1811 if (!Src0Op.isReg()) {
1812 report("G_INSERT_SUBVECTOR first source must be a register", MI);
1813 break;
1814 }
1815
1816 const MachineOperand &Src1Op = MI->getOperand(2);
1817 if (!Src1Op.isReg()) {
1818 report("G_INSERT_SUBVECTOR second source must be a register", MI);
1819 break;
1820 }
1821
1822 const MachineOperand &IndexOp = MI->getOperand(3);
1823 if (!IndexOp.isImm()) {
1824 report("G_INSERT_SUBVECTOR index must be an immediate", MI);
1825 break;
1826 }
1827
1828 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1829 LLT Src1Ty = MRI->getType(Src1Op.getReg());
1830
1831 if (!DstTy.isVector()) {
1832 report("Destination type must be a vector", MI);
1833 break;
1834 }
1835
1836 if (!Src1Ty.isVector()) {
1837 report("Second source must be a vector", MI);
1838 break;
1839 }
1840
1841 if (DstTy.getElementType() != Src1Ty.getElementType()) {
1842 report("Element type of vectors must be the same", MI);
1843 break;
1844 }
1845
1846 if (!DstTy.isScalable() && Src1Ty.isScalable()) {
1847 report("Cannot insert a scalable vector into a fixed length vector", MI);
1848 break;
1849 }
1850
1851 bool IsMixedFixedIntoScalable =
1852 DstTy.isScalableVector() && Src1Ty.isFixedVector();
1853
1854 if (!IsMixedFixedIntoScalable &&
1856 DstTy.getElementCount())) {
1857 report("Second source must be smaller than destination vector", MI);
1858 break;
1859 }
1860
1861 uint64_t Idx = IndexOp.getImm();
1862 uint64_t Src1MinLen = Src1Ty.getElementCount().getKnownMinValue();
1863 if (IndexOp.getImm() % Src1MinLen != 0) {
1864 report("Index must be a multiple of the second source vector's "
1865 "minimum vector length",
1866 MI);
1867 break;
1868 }
1869
1870 uint64_t DstMinLen = DstTy.getElementCount().getKnownMinValue();
1871 if (Idx >= DstMinLen ||
1872 (!IsMixedFixedIntoScalable && Idx + Src1MinLen > DstMinLen)) {
1873 report("Subvector type and index must not cause insert to overrun the "
1874 "vector being inserted into",
1875 MI);
1876 break;
1877 }
1878
1879 break;
1880 }
1881 case TargetOpcode::G_EXTRACT_SUBVECTOR: {
1882 const MachineOperand &SrcOp = MI->getOperand(1);
1883 if (!SrcOp.isReg()) {
1884 report("G_EXTRACT_SUBVECTOR first source must be a register", MI);
1885 break;
1886 }
1887
1888 const MachineOperand &IndexOp = MI->getOperand(2);
1889 if (!IndexOp.isImm()) {
1890 report("G_EXTRACT_SUBVECTOR index must be an immediate", MI);
1891 break;
1892 }
1893
1894 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1895 LLT SrcTy = MRI->getType(SrcOp.getReg());
1896
1897 if (!DstTy.isVector()) {
1898 report("Destination type must be a vector", MI);
1899 break;
1900 }
1901
1902 if (!SrcTy.isVector()) {
1903 report("Source must be a vector", MI);
1904 break;
1905 }
1906
1907 if (DstTy.getElementType() != SrcTy.getElementType()) {
1908 report("Element type of vectors must be the same", MI);
1909 break;
1910 }
1911
1912 if (DstTy.isScalable() && !SrcTy.isScalable()) {
1913 report("Cannot extract a scalable vector from a fixed length vector", MI);
1914 break;
1915 }
1916
1918 SrcTy.getElementCount())) {
1919 report("Destination vector must be smaller than source vector", MI);
1920 break;
1921 }
1922
1923 uint64_t Idx = IndexOp.getImm();
1924 uint64_t DstMinLen = DstTy.getElementCount().getKnownMinValue();
1925 if (Idx % DstMinLen != 0) {
1926 report("Index must be a multiple of the destination vector's minimum "
1927 "vector length",
1928 MI);
1929 break;
1930 }
1931
1932 bool IsMixedFixedFromScalable =
1933 DstTy.isFixedVector() && SrcTy.isScalableVector();
1934 uint64_t SrcMinLen = SrcTy.getElementCount().getKnownMinValue();
1935 if (Idx >= SrcMinLen ||
1936 (!IsMixedFixedFromScalable && Idx + DstMinLen > SrcMinLen)) {
1937 report("Destination type and index must not cause extract to overrun the "
1938 "source vector",
1939 MI);
1940 break;
1941 }
1942
1943 break;
1944 }
1945 case TargetOpcode::G_SHUFFLE_VECTOR: {
1946 const MachineOperand &MaskOp = MI->getOperand(3);
1947 if (!MaskOp.isShuffleMask()) {
1948 report("Incorrect mask operand type for G_SHUFFLE_VECTOR", MI);
1949 break;
1950 }
1951
1952 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1953 LLT Src0Ty = MRI->getType(MI->getOperand(1).getReg());
1954 LLT Src1Ty = MRI->getType(MI->getOperand(2).getReg());
1955
1956 if (Src0Ty != Src1Ty)
1957 report("Source operands must be the same type", MI);
1958
1959 if (Src0Ty.getScalarType() != DstTy.getScalarType()) {
1960 report("G_SHUFFLE_VECTOR cannot change element type", MI);
1961 break;
1962 }
1963 if (!Src0Ty.isVector()) {
1964 report("G_SHUFFLE_VECTOR must have vector src", MI);
1965 break;
1966 }
1967 if (!DstTy.isVector()) {
1968 report("G_SHUFFLE_VECTOR must have vector dst", MI);
1969 break;
1970 }
1971
1972 // Don't check that all operands are vector because scalars are used in
1973 // place of 1 element vectors.
1974 int SrcNumElts = Src0Ty.getNumElements();
1975 int DstNumElts = DstTy.getNumElements();
1976
1977 ArrayRef<int> MaskIdxes = MaskOp.getShuffleMask();
1978
1979 if (static_cast<int>(MaskIdxes.size()) != DstNumElts)
1980 report("Wrong result type for shufflemask", MI);
1981
1982 for (int Idx : MaskIdxes) {
1983 if (Idx < 0)
1984 continue;
1985
1986 if (Idx >= 2 * SrcNumElts)
1987 report("Out of bounds shuffle index", MI);
1988 }
1989
1990 break;
1991 }
1992
1993 case TargetOpcode::G_SPLAT_VECTOR: {
1994 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
1995 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
1996
1997 if (!DstTy.isVector()) {
1998 report("Destination type must be a vector", MI);
1999 break;
2000 }
2001
2002 if (!SrcTy.isScalar() && !SrcTy.isPointer()) {
2003 report("Source type must be a scalar or pointer", MI);
2004 break;
2005 }
2006
2008 SrcTy.getSizeInBits())) {
2009 report("Element type of the destination must be the same size or smaller "
2010 "than the source type",
2011 MI);
2012 break;
2013 }
2014
2015 break;
2016 }
2017 case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
2018 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2019 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
2020 LLT IdxTy = MRI->getType(MI->getOperand(2).getReg());
2021
2022 if (!DstTy.isScalar() && !DstTy.isPointer()) {
2023 report("Destination type must be a scalar or pointer", MI);
2024 break;
2025 }
2026
2027 if (!SrcTy.isVector()) {
2028 report("First source must be a vector", MI);
2029 break;
2030 }
2031
2032 auto TLI = MF->getSubtarget().getTargetLowering();
2033 if (IdxTy.getSizeInBits() != TLI->getVectorIdxWidth(MF->getDataLayout())) {
2034 report("Index type must match VectorIdxTy", MI);
2035 break;
2036 }
2037
2038 break;
2039 }
2040 case TargetOpcode::G_INSERT_VECTOR_ELT: {
2041 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2042 LLT VecTy = MRI->getType(MI->getOperand(1).getReg());
2043 LLT ScaTy = MRI->getType(MI->getOperand(2).getReg());
2044 LLT IdxTy = MRI->getType(MI->getOperand(3).getReg());
2045
2046 if (!DstTy.isVector()) {
2047 report("Destination type must be a vector", MI);
2048 break;
2049 }
2050
2051 if (VecTy != DstTy) {
2052 report("Destination type and vector type must match", MI);
2053 break;
2054 }
2055
2056 if (!ScaTy.isScalar() && !ScaTy.isPointer()) {
2057 report("Inserted element must be a scalar or pointer", MI);
2058 break;
2059 }
2060
2061 auto TLI = MF->getSubtarget().getTargetLowering();
2062 if (IdxTy.getSizeInBits() != TLI->getVectorIdxWidth(MF->getDataLayout())) {
2063 report("Index type must match VectorIdxTy", MI);
2064 break;
2065 }
2066
2067 break;
2068 }
2069 case TargetOpcode::G_DYN_STACKALLOC: {
2070 const MachineOperand &DstOp = MI->getOperand(0);
2071 const MachineOperand &AllocOp = MI->getOperand(1);
2072 const MachineOperand &AlignOp = MI->getOperand(2);
2073
2074 if (!DstOp.isReg() || !MRI->getType(DstOp.getReg()).isPointer()) {
2075 report("dst operand 0 must be a pointer type", MI);
2076 break;
2077 }
2078
2079 if (!AllocOp.isReg() || !MRI->getType(AllocOp.getReg()).isScalar()) {
2080 report("src operand 1 must be a scalar reg type", MI);
2081 break;
2082 }
2083
2084 if (!AlignOp.isImm()) {
2085 report("src operand 2 must be an immediate type", MI);
2086 break;
2087 }
2088 break;
2089 }
2090 case TargetOpcode::G_MEMCPY_INLINE:
2091 case TargetOpcode::G_MEMCPY:
2092 case TargetOpcode::G_MEMMOVE: {
2093 ArrayRef<MachineMemOperand *> MMOs = MI->memoperands();
2094 if (MMOs.size() != 2) {
2095 report("memcpy/memmove must have 2 memory operands", MI);
2096 break;
2097 }
2098
2099 if ((!MMOs[0]->isStore() || MMOs[0]->isLoad()) ||
2100 (MMOs[1]->isStore() || !MMOs[1]->isLoad())) {
2101 report("wrong memory operand types", MI);
2102 break;
2103 }
2104
2105 if (MMOs[0]->getSize() != MMOs[1]->getSize())
2106 report("inconsistent memory operand sizes", MI);
2107
2108 LLT DstPtrTy = MRI->getType(MI->getOperand(0).getReg());
2109 LLT SrcPtrTy = MRI->getType(MI->getOperand(1).getReg());
2110
2111 if (!DstPtrTy.isPointer() || !SrcPtrTy.isPointer()) {
2112 report("memory instruction operand must be a pointer", MI);
2113 break;
2114 }
2115
2116 if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace())
2117 report("inconsistent store address space", MI);
2118 if (SrcPtrTy.getAddressSpace() != MMOs[1]->getAddrSpace())
2119 report("inconsistent load address space", MI);
2120
2121 if (Opc != TargetOpcode::G_MEMCPY_INLINE)
2122 if (!MI->getOperand(3).isImm() || (MI->getOperand(3).getImm() & ~1LL))
2123 report("'tail' flag (operand 3) must be an immediate 0 or 1", MI);
2124
2125 break;
2126 }
2127 case TargetOpcode::G_BZERO:
2128 case TargetOpcode::G_MEMSET:
2129 case TargetOpcode::G_MEMSET_INLINE: {
2130 ArrayRef<MachineMemOperand *> MMOs = MI->memoperands();
2131 std::string Name = Opc == TargetOpcode::G_MEMSET ? "memset"
2132 : Opc == TargetOpcode::G_MEMSET_INLINE ? "memset_inline"
2133 : "bzero";
2134 if (MMOs.size() != 1) {
2135 report(Twine(Name, " must have 1 memory operand"), MI);
2136 break;
2137 }
2138
2139 if ((!MMOs[0]->isStore() || MMOs[0]->isLoad())) {
2140 report(Twine(Name, " memory operand must be a store"), MI);
2141 break;
2142 }
2143
2144 LLT DstPtrTy = MRI->getType(MI->getOperand(0).getReg());
2145 if (!DstPtrTy.isPointer()) {
2146 report(Twine(Name, " operand must be a pointer"), MI);
2147 break;
2148 }
2149
2150 if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace())
2151 report("inconsistent " + Twine(Name, " address space"), MI);
2152
2153 if (Opc != TargetOpcode::G_MEMSET_INLINE) {
2154 if (!MI->getOperand(MI->getNumOperands() - 1).isImm() ||
2155 (MI->getOperand(MI->getNumOperands() - 1).getImm() & ~1LL))
2156 report("'tail' flag (last operand) must be an immediate 0 or 1", MI);
2157 }
2158
2159 break;
2160 }
2161 case TargetOpcode::G_UBSANTRAP: {
2162 const MachineOperand &KindOp = MI->getOperand(0);
2163 if (!MI->getOperand(0).isImm()) {
2164 report("Crash kind must be an immediate", &KindOp, 0);
2165 break;
2166 }
2167 int64_t Kind = MI->getOperand(0).getImm();
2168 if (!isInt<8>(Kind))
2169 report("Crash kind must be 8 bit wide", &KindOp, 0);
2170 break;
2171 }
2172 case TargetOpcode::G_VECREDUCE_SEQ_FADD:
2173 case TargetOpcode::G_VECREDUCE_SEQ_FMUL: {
2174 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2175 LLT Src1Ty = MRI->getType(MI->getOperand(1).getReg());
2176 LLT Src2Ty = MRI->getType(MI->getOperand(2).getReg());
2177 if (!DstTy.isScalar())
2178 report("Vector reduction requires a scalar destination type", MI);
2179 if (!Src1Ty.isScalar())
2180 report("Sequential FADD/FMUL vector reduction requires a scalar 1st operand", MI);
2181 if (!Src2Ty.isVector())
2182 report("Sequential FADD/FMUL vector reduction must have a vector 2nd operand", MI);
2183 break;
2184 }
2185 case TargetOpcode::G_VECREDUCE_FADD:
2186 case TargetOpcode::G_VECREDUCE_FMUL:
2187 case TargetOpcode::G_VECREDUCE_FMAX:
2188 case TargetOpcode::G_VECREDUCE_FMIN:
2189 case TargetOpcode::G_VECREDUCE_FMAXIMUM:
2190 case TargetOpcode::G_VECREDUCE_FMINIMUM:
2191 case TargetOpcode::G_VECREDUCE_FMAXIMUMNUM:
2192 case TargetOpcode::G_VECREDUCE_FMINIMUMNUM:
2193 case TargetOpcode::G_VECREDUCE_ADD:
2194 case TargetOpcode::G_VECREDUCE_MUL:
2195 case TargetOpcode::G_VECREDUCE_AND:
2196 case TargetOpcode::G_VECREDUCE_OR:
2197 case TargetOpcode::G_VECREDUCE_XOR:
2198 case TargetOpcode::G_VECREDUCE_SMAX:
2199 case TargetOpcode::G_VECREDUCE_SMIN:
2200 case TargetOpcode::G_VECREDUCE_UMAX:
2201 case TargetOpcode::G_VECREDUCE_UMIN: {
2202 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2203 if (!DstTy.isScalar())
2204 report("Vector reduction requires a scalar destination type", MI);
2205 break;
2206 }
2207
2208 case TargetOpcode::G_SBFX:
2209 case TargetOpcode::G_UBFX: {
2210 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2211 if (DstTy.isVector()) {
2212 report("Bitfield extraction is not supported on vectors", MI);
2213 break;
2214 }
2215 break;
2216 }
2217 case TargetOpcode::G_SHL:
2218 case TargetOpcode::G_LSHR:
2219 case TargetOpcode::G_ASHR:
2220 case TargetOpcode::G_ROTR:
2221 case TargetOpcode::G_ROTL: {
2222 LLT Src1Ty = MRI->getType(MI->getOperand(1).getReg());
2223 LLT Src2Ty = MRI->getType(MI->getOperand(2).getReg());
2224 if (Src1Ty.isVector() != Src2Ty.isVector()) {
2225 report("Shifts and rotates require operands to be either all scalars or "
2226 "all vectors",
2227 MI);
2228 break;
2229 }
2230 break;
2231 }
2232 case TargetOpcode::G_LLROUND:
2233 case TargetOpcode::G_LROUND: {
2234 LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2235 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
2236 if (!DstTy.isValid() || !SrcTy.isValid())
2237 break;
2238 if (SrcTy.isPointer() || DstTy.isPointer()) {
2239 StringRef Op = SrcTy.isPointer() ? "Source" : "Destination";
2240 report(Twine(Op, " operand must not be a pointer type"), MI);
2241 } else if (SrcTy.isScalar()) {
2242 verifyAllRegOpsScalar(*MI, *MRI);
2243 break;
2244 } else if (SrcTy.isVector()) {
2245 verifyVectorElementMatch(SrcTy, DstTy, MI);
2246 break;
2247 }
2248 break;
2249 }
2250 case TargetOpcode::G_IS_FPCLASS: {
2251 LLT DestTy = MRI->getType(MI->getOperand(0).getReg());
2252 LLT DestEltTy = DestTy.getScalarType();
2253 if (!DestEltTy.isScalar()) {
2254 report("Destination must be a scalar or vector of scalars", MI);
2255 break;
2256 }
2257 LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
2258 LLT SrcEltTy = SrcTy.getScalarType();
2259 if (!SrcEltTy.isScalar()) {
2260 report("Source must be a scalar or vector of scalars", MI);
2261 break;
2262 }
2263 if (!verifyVectorElementMatch(DestTy, SrcTy, MI))
2264 break;
2265 const MachineOperand &TestMO = MI->getOperand(2);
2266 if (!TestMO.isImm()) {
2267 report("floating-point class set (operand 2) must be an immediate", MI);
2268 break;
2269 }
2270 int64_t Test = TestMO.getImm();
2272 report("Incorrect floating-point class set (operand 2)", MI);
2273 break;
2274 }
2275 break;
2276 }
2277 case TargetOpcode::G_PREFETCH: {
2278 const MachineOperand &AddrOp = MI->getOperand(0);
2279 if (!AddrOp.isReg() || !MRI->getType(AddrOp.getReg()).isPointer()) {
2280 report("addr operand must be a pointer", &AddrOp, 0);
2281 break;
2282 }
2283 const MachineOperand &RWOp = MI->getOperand(1);
2284 if (!RWOp.isImm() || (uint64_t)RWOp.getImm() >= 2) {
2285 report("rw operand must be an immediate 0-1", &RWOp, 1);
2286 break;
2287 }
2288 const MachineOperand &LocalityOp = MI->getOperand(2);
2289 if (!LocalityOp.isImm() || (uint64_t)LocalityOp.getImm() >= 4) {
2290 report("locality operand must be an immediate 0-3", &LocalityOp, 2);
2291 break;
2292 }
2293 const MachineOperand &CacheTypeOp = MI->getOperand(3);
2294 if (!CacheTypeOp.isImm() || (uint64_t)CacheTypeOp.getImm() >= 2) {
2295 report("cache type operand must be an immediate 0-1", &CacheTypeOp, 3);
2296 break;
2297 }
2298 break;
2299 }
2300 case TargetOpcode::G_ASSERT_ALIGN: {
2301 if (MI->getOperand(2).getImm() < 1)
2302 report("alignment immediate must be >= 1", MI);
2303 break;
2304 }
2305 case TargetOpcode::G_CONSTANT_POOL: {
2306 if (!MI->getOperand(1).isCPI())
2307 report("Src operand 1 must be a constant pool index", MI);
2308 if (!MRI->getType(MI->getOperand(0).getReg()).isPointer())
2309 report("Dst operand 0 must be a pointer", MI);
2310 break;
2311 }
2312 case TargetOpcode::G_PTRAUTH_GLOBAL_VALUE: {
2313 const MachineOperand &AddrOp = MI->getOperand(1);
2314 if (!AddrOp.isReg() || !MRI->getType(AddrOp.getReg()).isPointer())
2315 report("addr operand must be a pointer", &AddrOp, 1);
2316 break;
2317 }
2318 case TargetOpcode::G_SMIN:
2319 case TargetOpcode::G_SMAX:
2320 case TargetOpcode::G_UMIN:
2321 case TargetOpcode::G_UMAX: {
2322 const LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
2323 if (DstTy.isPointerOrPointerVector())
2324 report("Generic smin/smax/umin/umax does not support pointer operands",
2325 MI);
2326 break;
2327 }
2328 default:
2329 break;
2330 }
2331}
2332
2333void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
2334 // A dead def is contradictory if the same instruction has a live def of the
2335 // same register. Overlapping dead and live defs of different registers
2336 // describe a partially used def.
2337 if (!LivePhysDefs.empty()) {
2338 for (unsigned MONum : DeadPhysDefOps) {
2339 const MachineOperand &MO = MI->getOperand(MONum);
2340 if (is_contained(LivePhysDefs, MO.getReg().asMCReg())) {
2341 report("Dead def has a live def of the same register on the same "
2342 "instruction",
2343 &MO, MONum);
2344 }
2345 }
2346 }
2347
2348 LivePhysDefs.clear();
2349 DeadPhysDefOps.clear();
2350}
2351
2352void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
2353 const MCInstrDesc &MCID = MI->getDesc();
2354 if (MI->getNumOperands() < MCID.getNumOperands()) {
2355 report("Too few operands", MI);
2356 OS << MCID.getNumOperands() << " operands expected, but "
2357 << MI->getNumOperands() << " given.\n";
2358 }
2359
2360 if (MI->getFlag(MachineInstr::NoConvergent) && !MCID.isConvergent())
2361 report("NoConvergent flag expected only on convergent instructions.", MI);
2362
2363 if (MI->isPHI()) {
2364 if (MF->getProperties().hasNoPHIs())
2365 report("Found PHI instruction with NoPHIs property set", MI);
2366
2367 if (FirstNonPHI)
2368 report("Found PHI instruction after non-PHI", MI);
2369 } else if (FirstNonPHI == nullptr)
2370 FirstNonPHI = MI;
2371
2372 // Check the tied operands.
2373 if (MI->isInlineAsm())
2374 verifyInlineAsm(MI);
2375
2376 // Check that unspillable terminators define a reg and have at most one use.
2377 if (TII->isUnspillableTerminator(MI)) {
2378 if (!MI->getOperand(0).isReg() || !MI->getOperand(0).isDef())
2379 report("Unspillable Terminator does not define a reg", MI);
2380 Register Def = MI->getOperand(0).getReg();
2381 if (Def.isVirtual() && hasPHIs(*MF) &&
2382 std::distance(MRI->use_nodbg_begin(Def), MRI->use_nodbg_end()) > 1)
2383 report("Unspillable Terminator expected to have at most one use!", MI);
2384 }
2385
2386 // A fully-formed DBG_VALUE must have a location. Ignore partially formed
2387 // DBG_VALUEs: these are convenient to use in tests, but should never get
2388 // generated.
2389 if (MI->isDebugValue() && MI->getNumOperands() == 4)
2390 if (!MI->getDebugLoc())
2391 report("Missing DebugLoc for debug instruction", MI);
2392
2393 // Meta instructions should never be the subject of debug value tracking,
2394 // they don't create a value in the output program at all.
2395 if (MI->isMetaInstruction() && MI->peekDebugInstrNum())
2396 report("Metadata instruction should not have a value tracking number", MI);
2397
2398 // Check the MachineMemOperands for basic consistency.
2399 for (MachineMemOperand *Op : MI->memoperands()) {
2400 if (Op->isLoad() && !MI->mayLoad())
2401 report("Missing mayLoad flag", MI);
2402 if (Op->isStore() && !MI->mayStore())
2403 report("Missing mayStore flag", MI);
2404 }
2405
2406 // Debug values must not have a slot index.
2407 // Other instructions must have one, unless they are inside a bundle.
2408 if (LiveInts) {
2409 bool mapped = !LiveInts->isNotInMIMap(*MI);
2410 if (MI->isDebugOrPseudoInstr()) {
2411 if (mapped)
2412 report("Debug instruction has a slot index", MI);
2413 } else if (MI->isInsideBundle()) {
2414 if (mapped)
2415 report("Instruction inside bundle has a slot index", MI);
2416 } else {
2417 if (!mapped)
2418 report("Missing slot index", MI);
2419 }
2420 }
2421
2422 unsigned Opc = MCID.getOpcode();
2424 verifyPreISelGenericInstruction(MI);
2425 return;
2426 }
2427
2429 if (!TII->verifyInstruction(*MI, ErrorInfo))
2430 report(ErrorInfo.data(), MI);
2431
2432 // Verify properties of various specific instruction types
2433 switch (MI->getOpcode()) {
2434 case TargetOpcode::COPY: {
2435 const MachineOperand &DstOp = MI->getOperand(0);
2436 const MachineOperand &SrcOp = MI->getOperand(1);
2437 const Register SrcReg = SrcOp.getReg();
2438 const Register DstReg = DstOp.getReg();
2439
2440 LLT DstTy = MRI->getType(DstReg);
2441 LLT SrcTy = MRI->getType(SrcReg);
2442 if (SrcTy.isValid() && DstTy.isValid()) {
2443 // If both types are valid, check that the types are the same.
2444 if (SrcTy != DstTy) {
2445 report("Copy Instruction is illegal with mismatching types", MI);
2446 OS << "Def = " << DstTy << ", Src = " << SrcTy << '\n';
2447 }
2448
2449 break;
2450 }
2451
2452 if (!SrcTy.isValid() && !DstTy.isValid())
2453 break;
2454
2455 // If we have only one valid type, this is likely a copy between a virtual
2456 // and physical register.
2457 TypeSize SrcSize = TypeSize::getZero();
2458 TypeSize DstSize = TypeSize::getZero();
2459 if (SrcReg.isPhysical() && DstTy.isValid()) {
2460 if (!hasPhysRegClassForType(*TRI, SrcReg, DstTy))
2461 SrcSize = TRI->getRegSizeInBits(SrcReg, *MRI);
2462 } else {
2463 SrcSize = TRI->getRegSizeInBits(SrcReg, *MRI);
2464 }
2465
2466 if (DstReg.isPhysical() && SrcTy.isValid()) {
2467 if (!hasPhysRegClassForType(*TRI, DstReg, SrcTy))
2468 DstSize = TRI->getRegSizeInBits(DstReg, *MRI);
2469 } else {
2470 DstSize = TRI->getRegSizeInBits(DstReg, *MRI);
2471 }
2472
2473 // The next two checks allow COPY between physical and virtual registers,
2474 // when the virtual register has a scalable size and the physical register
2475 // has a fixed size. These checks allow COPY between *potentially*
2476 // mismatched sizes. However, once RegisterBankSelection occurs,
2477 // MachineVerifier should be able to resolve a fixed size for the scalable
2478 // vector, and at that point this function will know for sure whether the
2479 // sizes are mismatched and correctly report a size mismatch.
2480 if (SrcReg.isPhysical() && DstReg.isVirtual() && DstSize.isScalable() &&
2481 !SrcSize.isScalable())
2482 break;
2483 if (SrcReg.isVirtual() && DstReg.isPhysical() && SrcSize.isScalable() &&
2484 !DstSize.isScalable())
2485 break;
2486
2487 if (SrcSize.isNonZero() && DstSize.isNonZero() && SrcSize != DstSize) {
2488 if (!DstOp.getSubReg() && !SrcOp.getSubReg()) {
2489 report("Copy Instruction is illegal with mismatching sizes", MI);
2490 OS << "Def Size = " << DstSize << ", Src Size = " << SrcSize << '\n';
2491 }
2492 }
2493 break;
2494 }
2495 case TargetOpcode::COPY_LANEMASK: {
2496 const MachineOperand &DstOp = MI->getOperand(0);
2497 const MachineOperand &SrcOp = MI->getOperand(1);
2498 const MachineOperand &LaneMaskOp = MI->getOperand(2);
2499 const Register SrcReg = SrcOp.getReg();
2500 const LaneBitmask LaneMask = LaneMaskOp.getLaneMask();
2501 LaneBitmask SrcMaxLaneMask = LaneBitmask::getAll();
2502
2503 if (DstOp.getSubReg())
2504 report("COPY_LANEMASK must not use a subregister index", &DstOp, 0);
2505
2506 if (SrcOp.getSubReg())
2507 report("COPY_LANEMASK must not use a subregister index", &SrcOp, 1);
2508
2509 if (LaneMask.none())
2510 report("COPY_LANEMASK must read at least one lane", MI);
2511
2512 if (SrcReg.isPhysical()) {
2513 const TargetRegisterClass *SrcRC = TRI->getMinimalPhysRegClass(SrcReg);
2514 if (SrcRC)
2515 SrcMaxLaneMask = SrcRC->getLaneMask();
2516 } else {
2517 SrcMaxLaneMask = MRI->getMaxLaneMaskForVReg(SrcReg);
2518 }
2519
2520 // COPY_LANEMASK should be used only for partial copy. For full
2521 // copy, one should strictly use the COPY instruction.
2522 if (SrcMaxLaneMask == LaneMask)
2523 report("COPY_LANEMASK cannot be used to do full copy", MI);
2524
2525 // If LaneMask is greater than the SrcMaxLaneMask, it implies
2526 // COPY_LANEMASK is attempting to read from the lanes that
2527 // don't exists in the source register.
2528 if (SrcMaxLaneMask < LaneMask)
2529 report("COPY_LANEMASK attempts to read from the lanes that "
2530 "don't exist in the source register",
2531 MI);
2532
2533 break;
2534 }
2535 case TargetOpcode::STATEPOINT: {
2536 StatepointOpers SO(MI);
2537 if (!MI->getOperand(SO.getIDPos()).isImm() ||
2538 !MI->getOperand(SO.getNBytesPos()).isImm() ||
2539 !MI->getOperand(SO.getNCallArgsPos()).isImm()) {
2540 report("meta operands to STATEPOINT not constant!", MI);
2541 break;
2542 }
2543
2544 auto VerifyStackMapConstant = [&](unsigned Offset) {
2545 if (Offset >= MI->getNumOperands()) {
2546 report("stack map constant to STATEPOINT is out of range!", MI);
2547 return;
2548 }
2549 if (!MI->getOperand(Offset - 1).isImm() ||
2550 MI->getOperand(Offset - 1).getImm() != StackMaps::ConstantOp ||
2551 !MI->getOperand(Offset).isImm())
2552 report("stack map constant to STATEPOINT not well formed!", MI);
2553 };
2554 VerifyStackMapConstant(SO.getCCIdx());
2555 VerifyStackMapConstant(SO.getFlagsIdx());
2556 VerifyStackMapConstant(SO.getNumDeoptArgsIdx());
2557 VerifyStackMapConstant(SO.getNumGCPtrIdx());
2558 VerifyStackMapConstant(SO.getNumAllocaIdx());
2559 VerifyStackMapConstant(SO.getNumGcMapEntriesIdx());
2560
2561 // Verify that all explicit statepoint defs are tied to gc operands as
2562 // they are expected to be a relocation of gc operands.
2563 unsigned FirstGCPtrIdx = SO.getFirstGCPtrIdx();
2564 unsigned LastGCPtrIdx = SO.getNumAllocaIdx() - 2;
2565 for (unsigned Idx = 0; Idx < MI->getNumDefs(); Idx++) {
2566 unsigned UseOpIdx;
2567 if (!MI->isRegTiedToUseOperand(Idx, &UseOpIdx)) {
2568 report("STATEPOINT defs expected to be tied", MI);
2569 break;
2570 }
2571 if (UseOpIdx < FirstGCPtrIdx || UseOpIdx > LastGCPtrIdx) {
2572 report("STATEPOINT def tied to non-gc operand", MI);
2573 break;
2574 }
2575 }
2576
2577 // TODO: verify we have properly encoded deopt arguments
2578 } break;
2579 case TargetOpcode::INSERT_SUBREG: {
2580 unsigned InsertedSize;
2581 if (unsigned SubIdx = MI->getOperand(2).getSubReg())
2582 InsertedSize = TRI->getSubRegIdxSize(SubIdx);
2583 else
2584 InsertedSize = TRI->getRegSizeInBits(MI->getOperand(2).getReg(), *MRI);
2585 unsigned SubRegSize = TRI->getSubRegIdxSize(MI->getOperand(3).getImm());
2586 if (SubRegSize < InsertedSize) {
2587 report("INSERT_SUBREG expected inserted value to have equal or lesser "
2588 "size than the subreg it was inserted into", MI);
2589 break;
2590 }
2591 } break;
2592 case TargetOpcode::REG_SEQUENCE: {
2593 unsigned NumOps = MI->getNumOperands();
2594 if (!(NumOps & 1)) {
2595 report("Invalid number of operands for REG_SEQUENCE", MI);
2596 break;
2597 }
2598
2599 for (unsigned I = 1; I != NumOps; I += 2) {
2600 const MachineOperand &RegOp = MI->getOperand(I);
2601 const MachineOperand &SubRegOp = MI->getOperand(I + 1);
2602
2603 if (!RegOp.isReg())
2604 report("Invalid register operand for REG_SEQUENCE", &RegOp, I);
2605
2606 if (!SubRegOp.isImm() || SubRegOp.getImm() == 0 ||
2607 SubRegOp.getImm() >= TRI->getNumSubRegIndices()) {
2608 report("Invalid subregister index operand for REG_SEQUENCE",
2609 &SubRegOp, I + 1);
2610 }
2611 }
2612
2613 Register DstReg = MI->getOperand(0).getReg();
2614 if (DstReg.isPhysical())
2615 report("REG_SEQUENCE does not support physical register results", MI);
2616
2617 if (MI->getOperand(0).getSubReg())
2618 report("Invalid subreg result for REG_SEQUENCE", MI);
2619
2620 break;
2621 }
2622 }
2623}
2624
2625void
2626MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
2627 const MachineInstr *MI = MO->getParent();
2628 const MCInstrDesc &MCID = MI->getDesc();
2629 unsigned NumDefs = MCID.getNumDefs();
2630 if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
2631 NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
2632
2633 // The first MCID.NumDefs operands must be explicit register defines
2634 if (MONum < NumDefs) {
2635 const MCOperandInfo &MCOI = MCID.operands()[MONum];
2636 if (!MO->isReg())
2637 report("Explicit definition must be a register", MO, MONum);
2638 else if (!MO->isDef() && !MCOI.isOptionalDef())
2639 report("Explicit definition marked as use", MO, MONum);
2640 else if (MO->isImplicit())
2641 report("Explicit definition marked as implicit", MO, MONum);
2642 } else if (MONum < MCID.getNumOperands()) {
2643 const MCOperandInfo &MCOI = MCID.operands()[MONum];
2644 // Don't check if it's the last operand in a variadic instruction. See,
2645 // e.g., LDM_RET in the arm back end. Check non-variadic operands only.
2646 bool IsOptional = MI->isVariadic() && MONum == MCID.getNumOperands() - 1;
2647 if (!IsOptional) {
2648 if (MO->isReg()) {
2649 if (MO->isDef() && !MCOI.isOptionalDef() && !MCID.variadicOpsAreDefs())
2650 report("Explicit operand marked as def", MO, MONum);
2651 if (MO->isImplicit())
2652 report("Explicit operand marked as implicit", MO, MONum);
2653 }
2654
2655 // Check that an instruction has register operands only as expected.
2656 if (MCOI.OperandType == MCOI::OPERAND_REGISTER &&
2657 !MO->isReg() && !MO->isFI())
2658 report("Expected a register operand.", MO, MONum);
2659 if (MO->isReg()) {
2660 if (MCOI.OperandType == MCOI::OPERAND_IMMEDIATE ||
2661 (MCOI.OperandType == MCOI::OPERAND_PCREL &&
2662 !TII->isPCRelRegisterOperandLegal(*MI, MONum)))
2663 report("Expected a non-register operand.", MO, MONum);
2664 }
2665 }
2666
2667 int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
2668 if (TiedTo != -1) {
2669 if (!MO->isReg())
2670 report("Tied use must be a register", MO, MONum);
2671 else if (!MO->isTied())
2672 report("Operand should be tied", MO, MONum);
2673 else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
2674 report("Tied def doesn't match MCInstrDesc", MO, MONum);
2675 else if (MO->getReg().isPhysical()) {
2676 const MachineOperand &MOTied = MI->getOperand(TiedTo);
2677 if (!MOTied.isReg())
2678 report("Tied counterpart must be a register", &MOTied, TiedTo);
2679 else if (MOTied.getReg().isPhysical() &&
2680 MO->getReg() != MOTied.getReg())
2681 report("Tied physical registers must match.", &MOTied, TiedTo);
2682 }
2683 } else if (MO->isReg() && MO->isTied())
2684 report("Explicit operand should not be tied", MO, MONum);
2685 } else if (!MI->isVariadic()) {
2686 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
2687 if (!MO->isValidExcessOperand())
2688 report("Extra explicit operand on non-variadic instruction", MO, MONum);
2689 }
2690
2691 // Verify earlyClobber def operand
2692 if (MCID.getOperandConstraint(MONum, MCOI::EARLY_CLOBBER) != -1) {
2693 if (!MO->isReg())
2694 report("Early clobber must be a register", MI);
2695 if (!MO->isEarlyClobber())
2696 report("Missing earlyClobber flag", MI);
2697 }
2698
2699 switch (MO->getType()) {
2701 // Verify debug flag on debug instructions. Check this first because reg0
2702 // indicates an undefined debug value.
2703 if (MI->isDebugInstr() && MO->isUse()) {
2704 if (!MO->isDebug())
2705 report("Register operand must be marked debug", MO, MONum);
2706 } else if (MO->isDebug()) {
2707 report("Register operand must not be marked debug", MO, MONum);
2708 }
2709
2710 const Register Reg = MO->getReg();
2711 if (!Reg)
2712 return;
2713 if (MRI->tracksLiveness() && !MI->isDebugInstr())
2714 checkLiveness(MO, MONum);
2715
2716 if (MO->isDef() && MO->isUndef() && !MO->getSubReg() &&
2717 MO->getReg().isVirtual()) // TODO: Apply to physregs too
2718 report("Undef virtual register def operands require a subregister", MO, MONum);
2719
2720 // Verify the consistency of tied operands.
2721 if (MO->isTied()) {
2722 unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
2723 const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
2724 if (!OtherMO.isReg())
2725 report("Must be tied to a register", MO, MONum);
2726 if (!OtherMO.isTied())
2727 report("Missing tie flags on tied operand", MO, MONum);
2728 if (MI->findTiedOperandIdx(OtherIdx) != MONum)
2729 report("Inconsistent tie links", MO, MONum);
2730
2731 // See IsUndef in MachineOperand.h.
2732 if (MO->isUse() && MO->isUndef() && Reg.isVirtual() &&
2733 OtherMO.getReg() != Reg &&
2734 any_of(MI->all_uses(), [&](const MachineOperand &Other) {
2735 return &Other != MO && Other.isUndef() && Other.getReg() == Reg &&
2736 Other.getSubReg() == MO->getSubReg();
2737 }))
2738 report("Tied undef use shares a virtual register with another read", MO,
2739 MONum);
2740
2741 if (MONum < MCID.getNumDefs()) {
2742 if (OtherIdx < MCID.getNumOperands()) {
2743 if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
2744 report("Explicit def tied to explicit use without tie constraint",
2745 MO, MONum);
2746 } else {
2747 if (!OtherMO.isImplicit())
2748 report("Explicit def should be tied to implicit use", MO, MONum);
2749 }
2750 }
2751 }
2752
2753 // Verify two-address constraints after the twoaddressinstruction pass.
2754 // Both twoaddressinstruction pass and phi-node-elimination pass call
2755 // MRI->leaveSSA() to set MF as not IsSSA, we should do the verification
2756 // after twoaddressinstruction pass not after phi-node-elimination pass. So
2757 // we shouldn't use the IsSSA as the condition, we should based on
2758 // TiedOpsRewritten property to verify two-address constraints, this
2759 // property will be set in twoaddressinstruction pass.
2760 unsigned DefIdx;
2761 if (MF->getProperties().hasTiedOpsRewritten() && MO->isUse() &&
2762 MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
2763 Reg != MI->getOperand(DefIdx).getReg())
2764 report("Two-address instruction operands must be identical", MO, MONum);
2765
2766 // Check register classes.
2767 unsigned SubIdx = MO->getSubReg();
2768
2769 if (Reg.isPhysical()) {
2770 if (SubIdx) {
2771 report("Illegal subregister index for physical register", MO, MONum);
2772 return;
2773 }
2774 if (MONum < MCID.getNumOperands()) {
2775 if (const TargetRegisterClass *DRC = TII->getRegClass(MCID, MONum)) {
2776 if (!DRC->contains(Reg)) {
2777 report("Illegal physical register for instruction", MO, MONum);
2778 OS << printReg(Reg, TRI) << " is not a "
2779 << TRI->getRegClassName(DRC) << " register.\n";
2780 }
2781 }
2782 }
2783 if (MO->isRenamable()) {
2784 if (MRI->isReserved(Reg)) {
2785 report("isRenamable set on reserved register", MO, MONum);
2786 return;
2787 }
2788 }
2789 } else {
2790 // Virtual register.
2792 if (!RC) {
2793 // This is a generic virtual register.
2794
2795 // Do not allow undef uses for generic virtual registers. This ensures
2796 // getVRegDef can never fail and return null on a generic register.
2797 //
2798 // FIXME: This restriction should probably be broadened to all SSA
2799 // MIR. However, DetectDeadLanes/ProcessImplicitDefs technically still
2800 // run on the SSA function just before phi elimination.
2801 if (MO->isUndef())
2802 report("Generic virtual register use cannot be undef", MO, MONum);
2803
2804 // Debug value instruction is permitted to use undefined vregs.
2805 // This is a performance measure to skip the overhead of immediately
2806 // pruning unused debug operands. The final undef substitution occurs
2807 // when debug values are allocated in LDVImpl::handleDebugValue, so
2808 // these verifications always apply after this pass.
2809 if (isFunctionTracksDebugUserValues || !MO->isUse() ||
2810 !MI->isDebugValue() || !MRI->def_empty(Reg)) {
2811 // If we're post-Select, we can't have gvregs anymore.
2812 if (isFunctionSelected) {
2813 report("Generic virtual register invalid in a Selected function",
2814 MO, MONum);
2815 return;
2816 }
2817
2818 // The gvreg must have a type and it must not have a SubIdx.
2819 LLT Ty = MRI->getType(Reg);
2820 if (!Ty.isValid()) {
2821 report("Generic virtual register must have a valid type", MO,
2822 MONum);
2823 return;
2824 }
2825
2826 const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg);
2827 const RegisterBankInfo *RBI = MF->getSubtarget().getRegBankInfo();
2828
2829 // If we're post-RegBankSelect, the gvreg must have a bank.
2830 if (!RegBank && isFunctionRegBankSelected) {
2831 report("Generic virtual register must have a bank in a "
2832 "RegBankSelected function",
2833 MO, MONum);
2834 return;
2835 }
2836
2837 // Make sure the register fits into its register bank if any.
2838 if (RegBank && Ty.isValid() && !Ty.isScalableVector() &&
2839 RBI->getMaximumSize(RegBank->getID()) < Ty.getSizeInBits()) {
2840 report("Register bank is too small for virtual register", MO,
2841 MONum);
2842 OS << "Register bank " << RegBank->getName() << " too small("
2843 << RBI->getMaximumSize(RegBank->getID()) << ") to fit "
2844 << Ty.getSizeInBits() << "-bits\n";
2845 return;
2846 }
2847 }
2848
2849 if (SubIdx) {
2850 report("Generic virtual register does not allow subregister index", MO,
2851 MONum);
2852 return;
2853 }
2854
2855 // If this is a target specific instruction and this operand
2856 // has register class constraint, the virtual register must
2857 // comply to it.
2858 if (!isPreISelGenericOpcode(MCID.getOpcode()) &&
2859 MONum < MCID.getNumOperands() && TII->getRegClass(MCID, MONum)) {
2860 report("Virtual register does not match instruction constraint", MO,
2861 MONum);
2862 OS << "Expect register class "
2863 << TRI->getRegClassName(TII->getRegClass(MCID, MONum))
2864 << " but got nothing\n";
2865 return;
2866 }
2867
2868 break;
2869 }
2870 // Validate that SubIdx can be applied to the virtual register.
2871 if (!TRI->isSubRegValidForRegClass(RC, SubIdx)) {
2872 report("Invalid subregister index for virtual register", MO, MONum);
2873 OS << "Register class " << TRI->getRegClassName(RC)
2874 << " does not support subreg index "
2875 << TRI->getSubRegIndexName(SubIdx) << '\n';
2876 return;
2877 }
2878 if (MONum >= MCID.getNumOperands())
2879 break;
2880 const TargetRegisterClass *DRC = TII->getRegClass(MCID, MONum);
2881 if (!DRC)
2882 break;
2883
2884 // If SubIdx is used, verify that RC with SubIdx can be used for an
2885 // operand of class DRC. This is valid if for every register in RC, the
2886 // register obtained by applying SubIdx to it is in DRC.
2887 if (SubIdx && TRI->getMatchingSuperRegClass(RC, DRC, SubIdx) != RC) {
2888 report("Illegal virtual register for instruction", MO, MONum);
2889 OS << TRI->getRegClassName(RC) << "." << TRI->getSubRegIndexName(SubIdx)
2890 << " cannot be used for " << TRI->getRegClassName(DRC)
2891 << " operands.";
2892 }
2893
2894 // If no SubIdx is used, verify that RC is a sub-class of DRC.
2895 if (!SubIdx && !RC->hasSuperClassEq(DRC)) {
2896 report("Illegal virtual register for instruction", MO, MONum);
2897 OS << "Expected a " << TRI->getRegClassName(DRC)
2898 << " register, but got a " << TRI->getRegClassName(RC)
2899 << " register\n";
2900 }
2901 }
2902 break;
2903 }
2904
2906 regMasks.push_back(MO->getRegMask());
2907 break;
2908
2910 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
2911 report("PHI operand is not in the CFG", MO, MONum);
2912 break;
2913
2915 if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
2916 LiveInts && !LiveInts->isNotInMIMap(*MI)) {
2917 int FI = MO->getIndex();
2918 LiveInterval &LI = LiveStks->getInterval(FI);
2919 SlotIndex Idx = LiveInts->getInstructionIndex(*MI);
2920
2921 bool MayStore = MI->mayStore();
2922 bool MayLoad = MI->mayLoad();
2923 // For a memory-to-memory move, we need to check if the frame
2924 // index is used for storing or loading, by inspecting the
2925 // memory operands.
2926 if (MayStore && MayLoad) {
2927 for (const MachineMemOperand *MMO : MI->memoperands()) {
2929 MMO->getPseudoValue());
2930 if (!Value || Value->getFrameIndex() != FI)
2931 continue;
2932
2933 if (MMO->isStore())
2934 MayLoad = false;
2935 else
2936 MayStore = false;
2937 break;
2938 }
2939 if (MayLoad == MayStore)
2940 report("Missing fixed stack memoperand.", MI);
2941 }
2942 if (MayLoad && !LI.liveAt(Idx.getRegSlot(true))) {
2943 report("Instruction loads from dead spill slot", MO, MONum);
2944 OS << "Live stack: " << LI << '\n';
2945 }
2946 if (MayStore && !LI.liveAt(Idx.getRegSlot())) {
2947 report("Instruction stores to dead spill slot", MO, MONum);
2948 OS << "Live stack: " << LI << '\n';
2949 }
2950 }
2951 break;
2952
2954 if (MO->getCFIIndex() >= MF->getFrameInstructions().size())
2955 report("CFI instruction has invalid index", MO, MONum);
2956 break;
2957
2958 default:
2959 break;
2960 }
2961}
2962
2963void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO,
2964 unsigned MONum, SlotIndex UseIdx,
2965 const LiveRange &LR,
2966 VirtRegOrUnit VRegOrUnit,
2967 LaneBitmask LaneMask) {
2968 const MachineInstr *MI = MO->getParent();
2969
2970 if (!LR.verify()) {
2971 report("invalid live range", MO, MONum);
2972 report_context_liverange(LR);
2973 report_context_vreg_regunit(VRegOrUnit);
2974 report_context(UseIdx);
2975 return;
2976 }
2977
2978 LiveQueryResult LRQ = LR.Query(UseIdx);
2979 bool HasValue = LRQ.valueIn() || (MI->isPHI() && LRQ.valueOut());
2980 // Check if we have a segment at the use, note however that we only need one
2981 // live subregister range, the others may be dead.
2982 if (!HasValue && LaneMask.none()) {
2983 report("No live segment at use", MO, MONum);
2984 report_context_liverange(LR);
2985 report_context_vreg_regunit(VRegOrUnit);
2986 report_context(UseIdx);
2987 }
2988 if (MO->isKill() && !LRQ.isKill()) {
2989 report("Live range continues after kill flag", MO, MONum);
2990 report_context_liverange(LR);
2991 report_context_vreg_regunit(VRegOrUnit);
2992 if (LaneMask.any())
2993 report_context_lanemask(LaneMask);
2994 report_context(UseIdx);
2995 }
2996}
2997
2998void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO,
2999 unsigned MONum, SlotIndex DefIdx,
3000 const LiveRange &LR,
3001 VirtRegOrUnit VRegOrUnit,
3002 bool SubRangeCheck,
3003 LaneBitmask LaneMask) {
3004 if (!LR.verify()) {
3005 report("invalid live range", MO, MONum);
3006 report_context_liverange(LR);
3007 report_context_vreg_regunit(VRegOrUnit);
3008 if (LaneMask.any())
3009 report_context_lanemask(LaneMask);
3010 report_context(DefIdx);
3011 }
3012
3013 if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) {
3014 // The LR can correspond to the whole reg and its def slot is not obliged
3015 // to be the same as the MO' def slot. E.g. when we check here "normal"
3016 // subreg MO but there is other EC subreg MO in the same instruction so the
3017 // whole reg has EC def slot and differs from the currently checked MO' def
3018 // slot. For example:
3019 // %0 [16e,32r:0) 0@16e L..3 [16e,32r:0) 0@16e L..C [16r,32r:0) 0@16r
3020 // Check that there is an early-clobber def of the same superregister
3021 // somewhere is performed in visitMachineFunctionAfter()
3022 if (((SubRangeCheck || MO->getSubReg() == 0) && VNI->def != DefIdx) ||
3023 !SlotIndex::isSameInstr(VNI->def, DefIdx) ||
3024 (VNI->def != DefIdx &&
3025 (!VNI->def.isEarlyClobber() || !DefIdx.isRegister()))) {
3026 report("Inconsistent valno->def", MO, MONum);
3027 report_context_liverange(LR);
3028 report_context_vreg_regunit(VRegOrUnit);
3029 if (LaneMask.any())
3030 report_context_lanemask(LaneMask);
3031 report_context(*VNI);
3032 report_context(DefIdx);
3033 }
3034 } else {
3035 report("No live segment at def", MO, MONum);
3036 report_context_liverange(LR);
3037 report_context_vreg_regunit(VRegOrUnit);
3038 if (LaneMask.any())
3039 report_context_lanemask(LaneMask);
3040 report_context(DefIdx);
3041 }
3042 // Check that, if the dead def flag is present, LiveInts agree.
3043 if (MO->isDead()) {
3044 LiveQueryResult LRQ = LR.Query(DefIdx);
3045 if (!LRQ.isDeadDef()) {
3046 assert(VRegOrUnit.isVirtualReg() && "Expecting a virtual register.");
3047 // A dead subreg def only tells us that the specific subreg is dead. There
3048 // could be other non-dead defs of other subregs, or we could have other
3049 // parts of the register being live through the instruction. So unless we
3050 // are checking liveness for a subrange it is ok for the live range to
3051 // continue, given that we have a dead def of a subregister.
3052 if (SubRangeCheck || MO->getSubReg() == 0) {
3053 report("Live range continues after dead def flag", MO, MONum);
3054 report_context_liverange(LR);
3055 report_context_vreg_regunit(VRegOrUnit);
3056 if (LaneMask.any())
3057 report_context_lanemask(LaneMask);
3058 }
3059 }
3060 }
3061}
3062
3063void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
3064 const MachineInstr *MI = MO->getParent();
3065 const Register Reg = MO->getReg();
3066 const unsigned SubRegIdx = MO->getSubReg();
3067
3068 const LiveInterval *LI = nullptr;
3069 if (LiveInts && Reg.isVirtual()) {
3070 if (LiveInts->hasInterval(Reg)) {
3071 LI = &LiveInts->getInterval(Reg);
3072 if (SubRegIdx != 0 && (MO->isDef() || !MO->isUndef()) && !LI->empty() &&
3074 report("Live interval for subreg operand has no subranges", MO, MONum);
3075 } else {
3076 report("Virtual register has no live interval", MO, MONum);
3077 }
3078 }
3079
3080 // Both use and def operands can read a register.
3081 if (MO->readsReg()) {
3082 if (MO->isKill())
3083 addRegWithSubRegs(regsKilled, Reg);
3084
3085 // Check LiveInts liveness and kill.
3086 if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
3087 SlotIndex UseIdx;
3088 if (MI->isPHI()) {
3089 // PHI use occurs on the edge, so check for live out here instead.
3090 UseIdx = LiveInts->getMBBEndIdx(
3091 MI->getOperand(MONum + 1).getMBB()).getPrevSlot();
3092 } else {
3093 UseIdx = LiveInts->getInstructionIndex(*MI);
3094 }
3095 // Check the cached regunit intervals.
3096 if (Reg.isPhysical() && !isReserved(Reg)) {
3097 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg())) {
3098 if (MRI->isReservedRegUnit(Unit))
3099 continue;
3100 if (const LiveRange *LR = LiveInts->getCachedRegUnit(Unit))
3101 checkLivenessAtUse(MO, MONum, UseIdx, *LR, VirtRegOrUnit(Unit));
3102 }
3103 }
3104
3105 if (Reg.isVirtual()) {
3106 // This is a virtual register interval.
3107 checkLivenessAtUse(MO, MONum, UseIdx, *LI, VirtRegOrUnit(Reg));
3108
3109 if (LI->hasSubRanges() && !MO->isDef()) {
3110 LaneBitmask MOMask = SubRegIdx != 0
3111 ? TRI->getSubRegIndexLaneMask(SubRegIdx)
3113 LaneBitmask LiveInMask;
3114 for (const LiveInterval::SubRange &SR : LI->subranges()) {
3115 if ((MOMask & SR.LaneMask).none())
3116 continue;
3117 checkLivenessAtUse(MO, MONum, UseIdx, SR, VirtRegOrUnit(Reg),
3118 SR.LaneMask);
3119 LiveQueryResult LRQ = SR.Query(UseIdx);
3120 if (LRQ.valueIn() || (MI->isPHI() && LRQ.valueOut()))
3121 LiveInMask |= SR.LaneMask;
3122 }
3123 // At least parts of the register has to be live at the use.
3124 if ((LiveInMask & MOMask).none()) {
3125 report("No live subrange at use", MO, MONum);
3126 report_context(*LI);
3127 report_context(UseIdx);
3128 }
3129 // For PHIs all lanes should be live
3130 if (MI->isPHI() && LiveInMask != MOMask) {
3131 report("Not all lanes of PHI source live at use", MO, MONum);
3132 report_context(*LI);
3133 report_context(UseIdx);
3134 }
3135 }
3136 }
3137 }
3138
3139 // Use of a dead register.
3140 if (!regsLive.count(Reg)) {
3141 if (Reg.isPhysical()) {
3142 // Reserved registers may be used even when 'dead'.
3143 bool Bad = !isReserved(Reg);
3144 // We are fine if just any subregister has a defined value.
3145 if (Bad) {
3146
3147 for (const MCPhysReg &SubReg : TRI->subregs(Reg)) {
3148 if (regsLive.count(SubReg)) {
3149 Bad = false;
3150 break;
3151 }
3152 }
3153 }
3154 // If there is an additional implicit-use of a super register we stop
3155 // here. By definition we are fine if the super register is not
3156 // (completely) dead, if the complete super register is dead we will
3157 // get a report for its operand.
3158 if (Bad) {
3159 for (const MachineOperand &MOP : MI->uses()) {
3160 if (!MOP.isReg() || !MOP.isImplicit())
3161 continue;
3162
3163 if (!MOP.getReg().isPhysical())
3164 continue;
3165
3166 if (MOP.getReg() != Reg &&
3167 all_of(TRI->regunits(Reg), [&](const MCRegUnit RegUnit) {
3168 return llvm::is_contained(TRI->regunits(MOP.getReg()),
3169 RegUnit);
3170 }))
3171 Bad = false;
3172 }
3173 }
3174 if (Bad)
3175 report("Using an undefined physical register", MO, MONum);
3176 } else if (MRI->def_empty(Reg)) {
3177 report("Reading virtual register without a def", MO, MONum);
3178 } else {
3179 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
3180 // We don't know which virtual registers are live in, so only complain
3181 // if vreg was killed in this MBB. Otherwise keep track of vregs that
3182 // must be live in. PHI instructions are handled separately.
3183 if (MInfo.regsKilled.count(Reg))
3184 report("Using a killed virtual register", MO, MONum);
3185 else if (!MI->isPHI())
3186 MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
3187 }
3188 }
3189 }
3190
3191 if (MO->isDef()) {
3192 // Register defined.
3193 // TODO: verify that earlyclobber ops are not used.
3194 if (MO->isDead())
3195 addRegWithSubRegs(regsDead, Reg);
3196 else
3197 addRegWithSubRegs(regsDefined, Reg);
3198
3199 if (Reg.isPhysical()) {
3200 if (MO->isDead())
3201 DeadPhysDefOps.push_back(MONum);
3202 else
3203 LivePhysDefs.push_back(Reg.asMCReg());
3204 }
3205
3206 // Verify SSA form.
3207 if (MRI->isSSA() && Reg.isVirtual()) {
3208 if (!MRI->hasOneDef(Reg))
3209 report("Multiple virtual register defs in SSA form", MO, MONum);
3210 if (MO->getSubReg())
3211 report("Subreg def in SSA form", MO, MONum);
3212 }
3213
3214 // Check LiveInts for a live segment, but only for virtual registers.
3215 if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
3216 SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI);
3217 DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
3218
3219 if (Reg.isVirtual()) {
3220 checkLivenessAtDef(MO, MONum, DefIdx, *LI, VirtRegOrUnit(Reg));
3221
3222 if (LI->hasSubRanges()) {
3223 LaneBitmask MOMask = SubRegIdx != 0
3224 ? TRI->getSubRegIndexLaneMask(SubRegIdx)
3226 for (const LiveInterval::SubRange &SR : LI->subranges()) {
3227 if ((SR.LaneMask & MOMask).none())
3228 continue;
3229 checkLivenessAtDef(MO, MONum, DefIdx, SR, VirtRegOrUnit(Reg), true,
3230 SR.LaneMask);
3231 }
3232 }
3233 }
3234 }
3235 }
3236}
3237
3238// This function gets called after visiting all instructions in a bundle. The
3239// argument points to the bundle header.
3240// Normal stand-alone instructions are also considered 'bundles', and this
3241// function is called for all of them.
3242void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
3243 BBInfo &MInfo = MBBInfoMap[MI->getParent()];
3244 set_union(MInfo.regsKilled, regsKilled);
3245 set_subtract(regsLive, regsKilled); regsKilled.clear();
3246 // Kill any masked registers.
3247 while (!regMasks.empty()) {
3248 const uint32_t *Mask = regMasks.pop_back_val();
3249 for (Register Reg : regsLive)
3250 if (Reg.isPhysical() &&
3252 regsDead.push_back(Reg);
3253 }
3254 set_subtract(regsLive, regsDead); regsDead.clear();
3255 set_union(regsLive, regsDefined); regsDefined.clear();
3256}
3257
3258void
3259MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
3260 MBBInfoMap[MBB].regsLiveOut = regsLive;
3261 regsLive.clear();
3262
3263 if (Indexes) {
3264 SlotIndex stop = Indexes->getMBBEndIdx(MBB);
3265 if (!(stop > lastIndex)) {
3266 report("Block ends before last instruction index", MBB);
3267 OS << "Block ends at " << stop << " last instruction was at " << lastIndex
3268 << '\n';
3269 }
3270 lastIndex = stop;
3271 }
3272}
3273
3274namespace {
3275// This implements a set of registers that serves as a filter: can filter other
3276// sets by passing through elements not in the filter and blocking those that
3277// are. Any filter implicitly includes the full set of physical registers upon
3278// creation, thus filtering them all out. The filter itself as a set only grows,
3279// and needs to be as efficient as possible.
3280struct VRegFilter {
3281 // Add elements to the filter itself. \pre Input set \p FromRegSet must have
3282 // no duplicates. Both virtual and physical registers are fine.
3283 template <typename RegSetT> void add(const RegSetT &FromRegSet) {
3284 SmallVector<Register, 0> VRegsBuffer;
3285 filterAndAdd(FromRegSet, VRegsBuffer);
3286 }
3287 // Filter \p FromRegSet through the filter and append passed elements into \p
3288 // ToVRegs. All elements appended are then added to the filter itself.
3289 // \returns true if anything changed.
3290 template <typename RegSetT>
3291 bool filterAndAdd(const RegSetT &FromRegSet,
3292 SmallVectorImpl<Register> &ToVRegs) {
3293 unsigned SparseUniverse = Sparse.size();
3294 unsigned NewSparseUniverse = SparseUniverse;
3295 unsigned NewDenseSize = Dense.size();
3296 size_t Begin = ToVRegs.size();
3297 for (Register Reg : FromRegSet) {
3298 if (!Reg.isVirtual())
3299 continue;
3300 unsigned Index = Reg.virtRegIndex();
3301 if (Index < SparseUniverseMax) {
3302 if (Index < SparseUniverse && Sparse.test(Index))
3303 continue;
3304 NewSparseUniverse = std::max(NewSparseUniverse, Index + 1);
3305 } else {
3306 if (Dense.count(Reg))
3307 continue;
3308 ++NewDenseSize;
3309 }
3310 ToVRegs.push_back(Reg);
3311 }
3312 size_t End = ToVRegs.size();
3313 if (Begin == End)
3314 return false;
3315 // Reserving space in sets once performs better than doing so continuously
3316 // and pays easily for double look-ups (even in Dense with SparseUniverseMax
3317 // tuned all the way down) and double iteration (the second one is over a
3318 // SmallVector, which is a lot cheaper compared to DenseSet or BitVector).
3319 Sparse.resize(NewSparseUniverse);
3320 Dense.reserve(NewDenseSize);
3321 for (unsigned I = Begin; I < End; ++I) {
3322 Register Reg = ToVRegs[I];
3323 unsigned Index = Reg.virtRegIndex();
3324 if (Index < SparseUniverseMax)
3325 Sparse.set(Index);
3326 else
3327 Dense.insert(Reg);
3328 }
3329 return true;
3330 }
3331
3332private:
3333 static constexpr unsigned SparseUniverseMax = 10 * 1024 * 8;
3334 // VRegs indexed within SparseUniverseMax are tracked by Sparse, those beyond
3335 // are tracked by Dense. The only purpose of the threshold and the Dense set
3336 // is to have a reasonably growing memory usage in pathological cases (large
3337 // number of very sparse VRegFilter instances live at the same time). In
3338 // practice even in the worst-by-execution time cases having all elements
3339 // tracked by Sparse (very large SparseUniverseMax scenario) tends to be more
3340 // space efficient than if tracked by Dense. The threshold is set to keep the
3341 // worst-case memory usage within 2x of figures determined empirically for
3342 // "all Dense" scenario in such worst-by-execution-time cases.
3343 BitVector Sparse;
3344 DenseSet<Register> Dense;
3345};
3346
3347// Implements both a transfer function and a (binary, in-place) join operator
3348// for a dataflow over register sets with set union join and filtering transfer
3349// (out_b = in_b \ filter_b). filter_b is expected to be set-up ahead of time.
3350// Maintains out_b as its state, allowing for O(n) iteration over it at any
3351// time, where n is the size of the set (as opposed to O(U) where U is the
3352// universe). filter_b implicitly contains all physical registers at all times.
3353class FilteringVRegSet {
3354 VRegFilter Filter;
3356
3357public:
3358 // Set-up the filter_b. \pre Input register set \p RS must have no duplicates.
3359 // Both virtual and physical registers are fine.
3360 template <typename RegSetT> void addToFilter(const RegSetT &RS) {
3361 Filter.add(RS);
3362 }
3363 // Passes \p RS through the filter_b (transfer function) and adds what's left
3364 // to itself (out_b).
3365 template <typename RegSetT> bool add(const RegSetT &RS) {
3366 // Double-duty the Filter: to maintain VRegs a set (and the join operation
3367 // a set union) just add everything being added here to the Filter as well.
3368 return Filter.filterAndAdd(RS, VRegs);
3369 }
3370 using const_iterator = decltype(VRegs)::const_iterator;
3371 const_iterator begin() const { return VRegs.begin(); }
3372 const_iterator end() const { return VRegs.end(); }
3373 size_t size() const { return VRegs.size(); }
3374};
3375} // namespace
3376
3377// Calculate the largest possible vregsPassed sets. These are the registers that
3378// can pass through an MBB live, but may not be live every time. It is assumed
3379// that all vregsPassed sets are empty before the call.
3380void MachineVerifier::calcRegsPassed() {
3381 if (MF->empty())
3382 // ReversePostOrderTraversal doesn't handle empty functions.
3383 return;
3384
3385 for (const MachineBasicBlock *MB :
3387 FilteringVRegSet VRegs;
3388 BBInfo &Info = MBBInfoMap[MB];
3389 assert(Info.reachable);
3390
3391 VRegs.addToFilter(Info.regsKilled);
3392 VRegs.addToFilter(Info.regsLiveOut);
3393 for (const MachineBasicBlock *Pred : MB->predecessors()) {
3394 const BBInfo &PredInfo = MBBInfoMap[Pred];
3395 if (!PredInfo.reachable)
3396 continue;
3397
3398 VRegs.add(PredInfo.regsLiveOut);
3399 VRegs.add(PredInfo.vregsPassed);
3400 }
3401 Info.vregsPassed.reserve(VRegs.size());
3402 Info.vregsPassed.insert_range(VRegs);
3403 }
3404}
3405
3406// Calculate the set of virtual registers that must be passed through each basic
3407// block in order to satisfy the requirements of successor blocks. This is very
3408// similar to calcRegsPassed, only backwards.
3409void MachineVerifier::calcRegsRequired() {
3410 // First push live-in regs to predecessors' vregsRequired.
3412 for (const auto &MBB : *MF) {
3413 BBInfo &MInfo = MBBInfoMap[&MBB];
3414 for (const MachineBasicBlock *Pred : MBB.predecessors()) {
3415 BBInfo &PInfo = MBBInfoMap[Pred];
3416 if (PInfo.addRequired(MInfo.vregsLiveIn))
3417 todo.insert(Pred);
3418 }
3419
3420 // Handle the PHI node.
3421 for (const MachineInstr &MI : MBB.phis()) {
3422 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
3423 // Skip those Operands which are undef regs or not regs.
3424 if (!MI.getOperand(i).isReg() || !MI.getOperand(i).readsReg())
3425 continue;
3426
3427 // Get register and predecessor for one PHI edge.
3428 Register Reg = MI.getOperand(i).getReg();
3429 const MachineBasicBlock *Pred = MI.getOperand(i + 1).getMBB();
3430
3431 BBInfo &PInfo = MBBInfoMap[Pred];
3432 if (PInfo.addRequired(Reg))
3433 todo.insert(Pred);
3434 }
3435 }
3436 }
3437
3438 // Iteratively push vregsRequired to predecessors. This will converge to the
3439 // same final state regardless of DenseSet iteration order.
3440 while (!todo.empty()) {
3441 const MachineBasicBlock *MBB = *todo.begin();
3442 todo.erase(MBB);
3443 BBInfo &MInfo = MBBInfoMap[MBB];
3444 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
3445 if (Pred == MBB)
3446 continue;
3447 BBInfo &SInfo = MBBInfoMap[Pred];
3448 if (SInfo.addRequired(MInfo.vregsRequired))
3449 todo.insert(Pred);
3450 }
3451 }
3452}
3453
3454// Check PHI instructions at the beginning of MBB. It is assumed that
3455// calcRegsPassed has been run so BBInfo::isLiveOut is valid.
3456void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) {
3457 BBInfo &MInfo = MBBInfoMap[&MBB];
3458
3460 for (const MachineInstr &Phi : MBB) {
3461 if (!Phi.isPHI())
3462 break;
3463 seen.clear();
3464
3465 const MachineOperand &MODef = Phi.getOperand(0);
3466 if (!MODef.isReg() || !MODef.isDef()) {
3467 report("Expected first PHI operand to be a register def", &MODef, 0);
3468 continue;
3469 }
3470 if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() ||
3471 MODef.isEarlyClobber() || MODef.isDebug())
3472 report("Unexpected flag on PHI operand", &MODef, 0);
3473 Register DefReg = MODef.getReg();
3474 if (!DefReg.isVirtual())
3475 report("Expected first PHI operand to be a virtual register", &MODef, 0);
3476
3477 for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) {
3478 const MachineOperand &MO0 = Phi.getOperand(I);
3479 if (!MO0.isReg()) {
3480 report("Expected PHI operand to be a register", &MO0, I);
3481 continue;
3482 }
3483 if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() ||
3484 MO0.isDebug() || MO0.isTied())
3485 report("Unexpected flag on PHI operand", &MO0, I);
3486
3487 const MachineOperand &MO1 = Phi.getOperand(I + 1);
3488 if (!MO1.isMBB()) {
3489 report("Expected PHI operand to be a basic block", &MO1, I + 1);
3490 continue;
3491 }
3492
3493 const MachineBasicBlock &Pre = *MO1.getMBB();
3494 if (!Pre.isSuccessor(&MBB)) {
3495 report("PHI input is not a predecessor block", &MO1, I + 1);
3496 continue;
3497 }
3498
3499 if (MInfo.reachable) {
3500 seen.insert(&Pre);
3501 BBInfo &PrInfo = MBBInfoMap[&Pre];
3502 if (!MO0.isUndef() && PrInfo.reachable &&
3503 !PrInfo.isLiveOut(MO0.getReg()))
3504 report("PHI operand is not live-out from predecessor", &MO0, I);
3505 }
3506 }
3507
3508 // Did we see all predecessors?
3509 if (MInfo.reachable) {
3510 for (MachineBasicBlock *Pred : MBB.predecessors()) {
3511 if (!seen.count(Pred)) {
3512 report("Missing PHI operand", &Phi);
3513 OS << printMBBReference(*Pred)
3514 << " is a predecessor according to the CFG.\n";
3515 }
3516 }
3517 }
3518 }
3519}
3520
3521static void
3523 std::function<void(const Twine &Message)> FailureCB,
3524 raw_ostream &OS) {
3526 CV.initialize(&OS, FailureCB, MF);
3527
3528 for (const auto &MBB : MF) {
3529 CV.visit(MBB);
3530 for (const auto &MI : MBB.instrs())
3531 CV.visit(MI);
3532 }
3533
3534 if (CV.sawTokens()) {
3535 DT.recalculate(const_cast<MachineFunction &>(MF));
3536 CV.verify(DT);
3537 }
3538}
3539
3540void MachineVerifier::visitMachineFunctionAfter() {
3541 auto FailureCB = [this](const Twine &Message) {
3542 report(Message.str().c_str(), MF);
3543 };
3544 verifyConvergenceControl(*MF, DT, FailureCB, OS);
3545
3546 calcRegsPassed();
3547
3548 for (const MachineBasicBlock &MBB : *MF)
3549 checkPHIOps(MBB);
3550
3551 // Now check liveness info if available
3552 calcRegsRequired();
3553
3554 // Check for killed virtual registers that should be live out.
3555 for (const auto &MBB : *MF) {
3556 BBInfo &MInfo = MBBInfoMap[&MBB];
3557 for (Register VReg : MInfo.vregsRequired)
3558 if (MInfo.regsKilled.count(VReg)) {
3559 report("Virtual register killed in block, but needed live out.", &MBB);
3560 OS << "Virtual register " << printReg(VReg)
3561 << " is used after the block.\n";
3562 }
3563 }
3564
3565 if (!MF->empty()) {
3566 BBInfo &MInfo = MBBInfoMap[&MF->front()];
3567 for (Register VReg : MInfo.vregsRequired) {
3568 report("Virtual register defs don't dominate all uses.", MF);
3569 report_context_vreg(VReg);
3570 }
3571 }
3572
3573 if (LiveInts)
3574 verifyLiveIntervals();
3575
3576 // Check live-in list of each MBB. If a register is live into MBB, check
3577 // that the register is in regsLiveOut of each predecessor block. Since
3578 // this must come from a definition in the predecessor or its live-in
3579 // list, this will catch a live-through case where the predecessor does not
3580 // have the register in its live-in list. This currently only checks
3581 // registers that have no aliases, are not allocatable and are not
3582 // reserved, which could mean a condition code register for instance.
3583 if (MRI->tracksLiveness())
3584 for (const auto &MBB : *MF)
3586 MCRegister LiveInReg = P.PhysReg;
3587 bool hasAliases = MCRegAliasIterator(LiveInReg, TRI, false).isValid();
3588 if (hasAliases || isAllocatable(LiveInReg) || isReserved(LiveInReg))
3589 continue;
3590 for (const MachineBasicBlock *Pred : MBB.predecessors()) {
3591 BBInfo &PInfo = MBBInfoMap[Pred];
3592 if (!PInfo.regsLiveOut.count(LiveInReg)) {
3593 report("Live in register not found to be live out from predecessor.",
3594 &MBB);
3595 OS << TRI->getName(LiveInReg) << " not found to be live out from "
3596 << printMBBReference(*Pred) << '\n';
3597 }
3598 }
3599 }
3600
3601 for (auto CSInfo : MF->getCallSitesInfo())
3602 if (!CSInfo.first->isCall())
3603 report("Call site info referencing instruction that is not call", MF);
3604
3605 // If there's debug-info, check that we don't have any duplicate value
3606 // tracking numbers.
3607 if (MF->getFunction().getSubprogram()) {
3608 DenseSet<unsigned> SeenNumbers;
3609 for (const auto &MBB : *MF) {
3610 for (const auto &MI : MBB) {
3611 if (auto Num = MI.peekDebugInstrNum()) {
3612 auto Result = SeenNumbers.insert((unsigned)Num);
3613 if (!Result.second)
3614 report("Instruction has a duplicated value tracking number", &MI);
3615 }
3616 }
3617 }
3618 }
3619}
3620
3621void MachineVerifier::verifyLiveIntervals() {
3622 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
3623 for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
3625
3626 // Spilling and splitting may leave unused registers around. Skip them.
3627 if (MRI->reg_nodbg_empty(Reg))
3628 continue;
3629
3630 if (!LiveInts->hasInterval(Reg)) {
3631 report("Missing live interval for virtual register", MF);
3632 OS << printReg(Reg, TRI) << " still has defs or uses\n";
3633 continue;
3634 }
3635
3636 const LiveInterval &LI = LiveInts->getInterval(Reg);
3637 assert(Reg == LI.reg() && "Invalid reg to interval mapping");
3638 verifyLiveInterval(LI);
3639 }
3640
3641 // Verify all the cached regunit intervals.
3642 for (MCRegUnit Unit : TRI->regunits())
3643 if (const LiveRange *LR = LiveInts->getCachedRegUnit(Unit))
3644 verifyLiveRange(*LR, VirtRegOrUnit(Unit));
3645}
3646
3647void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
3648 const VNInfo *VNI,
3649 VirtRegOrUnit VRegOrUnit,
3650 LaneBitmask LaneMask) {
3651 if (VNI->isUnused())
3652 return;
3653
3654 const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
3655
3656 if (!DefVNI) {
3657 report("Value not live at VNInfo def and not marked unused", MF);
3658 report_context(LR, VRegOrUnit, LaneMask);
3659 report_context(*VNI);
3660 return;
3661 }
3662
3663 if (DefVNI != VNI) {
3664 report("Live segment at def has different VNInfo", MF);
3665 report_context(LR, VRegOrUnit, LaneMask);
3666 report_context(*VNI);
3667 return;
3668 }
3669
3670 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
3671 if (!MBB) {
3672 report("Invalid VNInfo definition index", MF);
3673 report_context(LR, VRegOrUnit, LaneMask);
3674 report_context(*VNI);
3675 return;
3676 }
3677
3678 if (VNI->isPHIDef()) {
3679 if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
3680 report("PHIDef VNInfo is not defined at MBB start", MBB);
3681 report_context(LR, VRegOrUnit, LaneMask);
3682 report_context(*VNI);
3683 }
3684 return;
3685 }
3686
3687 // Non-PHI def.
3688 const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
3689 if (!MI) {
3690 report("No instruction at VNInfo def index", MBB);
3691 report_context(LR, VRegOrUnit, LaneMask);
3692 report_context(*VNI);
3693 return;
3694 }
3695
3696 bool hasDef = false;
3697 bool isEarlyClobber = false;
3698 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
3699 if (!MOI->isReg() || !MOI->isDef())
3700 continue;
3701 if (VRegOrUnit.isVirtualReg()) {
3702 if (MOI->getReg() != VRegOrUnit.asVirtualReg())
3703 continue;
3704 } else {
3705 if (!MOI->getReg().isPhysical() ||
3706 !TRI->hasRegUnit(MOI->getReg(), VRegOrUnit.asMCRegUnit()))
3707 continue;
3708 }
3709 if (LaneMask.any() &&
3710 (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none())
3711 continue;
3712 hasDef = true;
3713 if (MOI->isEarlyClobber())
3714 isEarlyClobber = true;
3715 }
3716
3717 if (!hasDef) {
3718 report("Defining instruction does not modify register", MI);
3719 report_context(LR, VRegOrUnit, LaneMask);
3720 report_context(*VNI);
3721 }
3722
3723 // Early clobber defs begin at USE slots, but other defs must begin at
3724 // DEF slots.
3725 if (isEarlyClobber) {
3726 if (!VNI->def.isEarlyClobber()) {
3727 report("Early clobber def must be at an early-clobber slot", MBB);
3728 report_context(LR, VRegOrUnit, LaneMask);
3729 report_context(*VNI);
3730 }
3731 } else if (!VNI->def.isRegister()) {
3732 report("Non-PHI, non-early clobber def must be at a register slot", MBB);
3733 report_context(LR, VRegOrUnit, LaneMask);
3734 report_context(*VNI);
3735 }
3736}
3737
3738void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
3740 VirtRegOrUnit VRegOrUnit,
3741 LaneBitmask LaneMask) {
3742 const LiveRange::Segment &S = *I;
3743 const VNInfo *VNI = S.valno;
3744 assert(VNI && "Live segment has no valno");
3745
3746 if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
3747 report("Foreign valno in live segment", MF);
3748 report_context(LR, VRegOrUnit, LaneMask);
3749 report_context(S);
3750 report_context(*VNI);
3751 }
3752
3753 if (VNI->isUnused()) {
3754 report("Live segment valno is marked unused", MF);
3755 report_context(LR, VRegOrUnit, LaneMask);
3756 report_context(S);
3757 }
3758
3759 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
3760 if (!MBB) {
3761 report("Bad start of live segment, no basic block", MF);
3762 report_context(LR, VRegOrUnit, LaneMask);
3763 report_context(S);
3764 return;
3765 }
3766 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
3767 if (S.start != MBBStartIdx && S.start != VNI->def) {
3768 report("Live segment must begin at MBB entry or valno def", MBB);
3769 report_context(LR, VRegOrUnit, LaneMask);
3770 report_context(S);
3771 }
3772
3773 const MachineBasicBlock *EndMBB =
3774 LiveInts->getMBBFromIndex(S.end.getPrevSlot());
3775 if (!EndMBB) {
3776 report("Bad end of live segment, no basic block", MF);
3777 report_context(LR, VRegOrUnit, LaneMask);
3778 report_context(S);
3779 return;
3780 }
3781
3782 // Checks for non-live-out segments.
3783 if (S.end != LiveInts->getMBBEndIdx(EndMBB)) {
3784 // RegUnit intervals are allowed dead phis.
3785 if (!VRegOrUnit.isVirtualReg() && VNI->isPHIDef() && S.start == VNI->def &&
3786 S.end == VNI->def.getDeadSlot())
3787 return;
3788
3789 // The live segment is ending inside EndMBB
3790 const MachineInstr *MI =
3791 LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
3792 if (!MI) {
3793 report("Live segment doesn't end at a valid instruction", EndMBB);
3794 report_context(LR, VRegOrUnit, LaneMask);
3795 report_context(S);
3796 return;
3797 }
3798
3799 // The block slot must refer to a basic block boundary.
3800 if (S.end.isBlock()) {
3801 report("Live segment ends at B slot of an instruction", EndMBB);
3802 report_context(LR, VRegOrUnit, LaneMask);
3803 report_context(S);
3804 }
3805
3806 if (S.end.isDead()) {
3807 // Segment ends on the dead slot.
3808 // That means there must be a dead def.
3809 if (!SlotIndex::isSameInstr(S.start, S.end)) {
3810 report("Live segment ending at dead slot spans instructions", EndMBB);
3811 report_context(LR, VRegOrUnit, LaneMask);
3812 report_context(S);
3813 }
3814 }
3815
3816 // After tied operands are rewritten, a live segment can only end at an
3817 // early-clobber slot if it is being redefined by an early-clobber def.
3818 // TODO: Before tied operands are rewritten, a live segment can only end at
3819 // an early-clobber slot if the last use is tied to an early-clobber def.
3820 if (MF->getProperties().hasTiedOpsRewritten() && S.end.isEarlyClobber()) {
3821 if (I + 1 == LR.end() || (I + 1)->start != S.end) {
3822 report("Live segment ending at early clobber slot must be "
3823 "redefined by an EC def in the same instruction",
3824 EndMBB);
3825 report_context(LR, VRegOrUnit, LaneMask);
3826 report_context(S);
3827 }
3828 }
3829
3830 // The following checks only apply to virtual registers. Physreg liveness
3831 // is too weird to check.
3832 if (VRegOrUnit.isVirtualReg()) {
3833 // A live segment can end with either a redefinition, a kill flag on a
3834 // use, or a dead flag on a def.
3835 bool hasRead = false;
3836 bool hasSubRegDef = false;
3837 bool hasDeadDef = false;
3838 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
3839 if (!MOI->isReg() || MOI->getReg() != VRegOrUnit.asVirtualReg())
3840 continue;
3841 unsigned Sub = MOI->getSubReg();
3842 LaneBitmask SLM =
3843 Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub) : LaneBitmask::getAll();
3844 if (MOI->isDef()) {
3845 if (Sub != 0) {
3846 hasSubRegDef = true;
3847 // An operand %0:sub0 reads %0:sub1..n. Invert the lane
3848 // mask for subregister defs. Read-undef defs will be handled by
3849 // readsReg below.
3850 SLM = ~SLM;
3851 }
3852 if (MOI->isDead())
3853 hasDeadDef = true;
3854 }
3855 if (LaneMask.any() && (LaneMask & SLM).none())
3856 continue;
3857 if (MOI->readsReg())
3858 hasRead = true;
3859 }
3860 if (S.end.isDead()) {
3861 // Make sure that the corresponding machine operand for a "dead" live
3862 // range has the dead flag. We cannot perform this check for subregister
3863 // liveranges as partially dead values are allowed.
3864 if (LaneMask.none() && !hasDeadDef) {
3865 report(
3866 "Instruction ending live segment on dead slot has no dead flag",
3867 MI);
3868 report_context(LR, VRegOrUnit, LaneMask);
3869 report_context(S);
3870 }
3871 } else {
3872 if (!hasRead) {
3873 // When tracking subregister liveness, the main range must start new
3874 // values on partial register writes, even if there is no read.
3875 if (!MRI->shouldTrackSubRegLiveness(VRegOrUnit.asVirtualReg()) ||
3876 LaneMask.any() || !hasSubRegDef) {
3877 report("Instruction ending live segment doesn't read the register",
3878 MI);
3879 report_context(LR, VRegOrUnit, LaneMask);
3880 report_context(S);
3881 }
3882 }
3883 }
3884 }
3885 }
3886
3887 // Now check all the basic blocks in this live segment.
3889 // Is this live segment the beginning of a non-PHIDef VN?
3890 if (S.start == VNI->def && !VNI->isPHIDef()) {
3891 // Not live-in to any blocks.
3892 if (MBB == EndMBB)
3893 return;
3894 // Skip this block.
3895 ++MFI;
3896 }
3897
3899 if (LaneMask.any()) {
3900 LiveInterval &OwnerLI = LiveInts->getInterval(VRegOrUnit.asVirtualReg());
3901 OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
3902 }
3903
3904 while (true) {
3905 assert(LiveInts->isLiveInToMBB(LR, &*MFI));
3906 // We don't know how to track physregs into a landing pad.
3907 if (!VRegOrUnit.isVirtualReg() && MFI->isEHPad()) {
3908 if (&*MFI == EndMBB)
3909 break;
3910 ++MFI;
3911 continue;
3912 }
3913
3914 // Is VNI a PHI-def in the current block?
3915 bool IsPHI = VNI->isPHIDef() &&
3916 VNI->def == LiveInts->getMBBStartIdx(&*MFI);
3917
3918 // Check that VNI is live-out of all predecessors.
3919 for (const MachineBasicBlock *Pred : MFI->predecessors()) {
3920 SlotIndex PEnd = LiveInts->getMBBEndIdx(Pred);
3921 // Predecessor of landing pad live-out on last call.
3922 if (MFI->isEHPad()) {
3923 for (const MachineInstr &MI : llvm::reverse(*Pred)) {
3924 if (MI.isCall()) {
3925 PEnd = Indexes->getInstructionIndex(MI).getBoundaryIndex();
3926 break;
3927 }
3928 }
3929 }
3930 const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
3931
3932 // All predecessors must have a live-out value. However for a phi
3933 // instruction with subregister intervals
3934 // only one of the subregisters (not necessarily the current one) needs to
3935 // be defined.
3936 if (!PVNI && (LaneMask.none() || !IsPHI)) {
3937 if (LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes))
3938 continue;
3939 report("Register not marked live out of predecessor", Pred);
3940 report_context(LR, VRegOrUnit, LaneMask);
3941 report_context(*VNI);
3942 OS << " live into " << printMBBReference(*MFI) << '@'
3943 << LiveInts->getMBBStartIdx(&*MFI) << ", not live before " << PEnd
3944 << '\n';
3945 continue;
3946 }
3947
3948 // Only PHI-defs can take different predecessor values.
3949 if (!IsPHI && PVNI != VNI) {
3950 report("Different value live out of predecessor", Pred);
3951 report_context(LR, VRegOrUnit, LaneMask);
3952 OS << "Valno #" << PVNI->id << " live out of "
3953 << printMBBReference(*Pred) << '@' << PEnd << "\nValno #" << VNI->id
3954 << " live into " << printMBBReference(*MFI) << '@'
3955 << LiveInts->getMBBStartIdx(&*MFI) << '\n';
3956 }
3957 }
3958 if (&*MFI == EndMBB)
3959 break;
3960 ++MFI;
3961 }
3962}
3963
3964void MachineVerifier::verifyLiveRange(const LiveRange &LR,
3965 VirtRegOrUnit VRegOrUnit,
3966 LaneBitmask LaneMask) {
3967 for (const VNInfo *VNI : LR.valnos)
3968 verifyLiveRangeValue(LR, VNI, VRegOrUnit, LaneMask);
3969
3970 for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
3971 verifyLiveRangeSegment(LR, I, VRegOrUnit, LaneMask);
3972}
3973
3974void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
3975 Register Reg = LI.reg();
3976 assert(Reg.isVirtual());
3977 verifyLiveRange(LI, VirtRegOrUnit(Reg));
3978
3979 if (LI.hasSubRanges()) {
3982 for (const LiveInterval::SubRange &SR : LI.subranges()) {
3983 if ((Mask & SR.LaneMask).any()) {
3984 report("Lane masks of sub ranges overlap in live interval", MF);
3985 report_context(LI);
3986 }
3987 if ((SR.LaneMask & ~MaxMask).any()) {
3988 report("Subrange lanemask is invalid", MF);
3989 report_context(LI);
3990 }
3991 if (SR.empty()) {
3992 report("Subrange must not be empty", MF);
3993 report_context(SR, VirtRegOrUnit(LI.reg()), SR.LaneMask);
3994 }
3995 Mask |= SR.LaneMask;
3996 verifyLiveRange(SR, VirtRegOrUnit(LI.reg()), SR.LaneMask);
3997 if (!LI.covers(SR)) {
3998 report("A Subrange is not covered by the main range", MF);
3999 report_context(LI);
4000 }
4001 }
4002 }
4003
4004 // Check the LI only has one connected component.
4005 ConnectedVNInfoEqClasses ConEQ(*LiveInts);
4006 unsigned NumComp = ConEQ.Classify(LI);
4007 if (NumComp > 1) {
4008 report("Multiple connected components in live interval", MF);
4009 report_context(LI);
4010 for (unsigned comp = 0; comp != NumComp; ++comp) {
4011 OS << comp << ": valnos";
4012 for (const VNInfo *I : LI.valnos)
4013 if (comp == ConEQ.getEqClass(I))
4014 OS << ' ' << I->id;
4015 OS << '\n';
4016 }
4017 }
4018}
4019
4020namespace {
4021
4022 // FrameSetup and FrameDestroy can have zero adjustment, so using a single
4023 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
4024 // value is zero.
4025 // We use a bool plus an integer to capture the stack state.
4026struct StackStateOfBB {
4027 StackStateOfBB() = default;
4028 StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup)
4029 : EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
4030 ExitIsSetup(ExitSetup) {}
4031
4032 // Can be negative, which means we are setting up a frame.
4033 int EntryValue = 0;
4034 int ExitValue = 0;
4035 bool EntryIsSetup = false;
4036 bool ExitIsSetup = false;
4037};
4038
4039} // end anonymous namespace
4040
4041/// Make sure on every path through the CFG, a FrameSetup <n> is always followed
4042/// by a FrameDestroy <n>, stack adjustments are identical on all
4043/// CFG edges to a merge point, and frame is destroyed at end of a return block.
4044void MachineVerifier::verifyStackFrame() {
4045 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
4046 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
4047 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
4048 return;
4049
4051 SPState.resize(MF->getNumBlockIDs());
4053
4054 // Visit the MBBs in DFS order.
4055 for (df_ext_iterator<const MachineFunction *,
4057 DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
4058 DFI != DFE; ++DFI) {
4059 const MachineBasicBlock *MBB = *DFI;
4060
4061 StackStateOfBB BBState;
4062 // Check the exit state of the DFS stack predecessor.
4063 if (DFI.getPathLength() >= 2) {
4064 const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
4065 assert(Reachable.count(StackPred) &&
4066 "DFS stack predecessor is already visited.\n");
4067 BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
4068 BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
4069 BBState.ExitValue = BBState.EntryValue;
4070 BBState.ExitIsSetup = BBState.EntryIsSetup;
4071 }
4072
4073 if ((int)MBB->getCallFrameSize() != -BBState.EntryValue) {
4074 report("Call frame size on entry does not match value computed from "
4075 "predecessor",
4076 MBB);
4077 OS << "Call frame size on entry " << MBB->getCallFrameSize()
4078 << " does not match value computed from predecessor "
4079 << -BBState.EntryValue << '\n';
4080 }
4081
4082 // Update stack state by checking contents of MBB.
4083 for (const auto &I : *MBB) {
4084 if (I.getOpcode() == FrameSetupOpcode) {
4085 if (BBState.ExitIsSetup)
4086 report("FrameSetup is after another FrameSetup", &I);
4087 if (!MRI->isSSA() && !MF->getFrameInfo().adjustsStack())
4088 report("AdjustsStack not set in presence of a frame pseudo "
4089 "instruction.", &I);
4090 BBState.ExitValue -= TII->getFrameTotalSize(I);
4091 BBState.ExitIsSetup = true;
4092 }
4093
4094 if (I.getOpcode() == FrameDestroyOpcode) {
4095 int Size = TII->getFrameTotalSize(I);
4096 if (!BBState.ExitIsSetup)
4097 report("FrameDestroy is not after a FrameSetup", &I);
4098 int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
4099 BBState.ExitValue;
4100 if (BBState.ExitIsSetup && AbsSPAdj != Size) {
4101 report("FrameDestroy <n> is after FrameSetup <m>", &I);
4102 OS << "FrameDestroy <" << Size << "> is after FrameSetup <"
4103 << AbsSPAdj << ">.\n";
4104 }
4105 if (!MRI->isSSA() && !MF->getFrameInfo().adjustsStack())
4106 report("AdjustsStack not set in presence of a frame pseudo "
4107 "instruction.", &I);
4108 BBState.ExitValue += Size;
4109 BBState.ExitIsSetup = false;
4110 }
4111 }
4112 SPState[MBB->getNumber()] = BBState;
4113
4114 // Make sure the exit state of any predecessor is consistent with the entry
4115 // state.
4116 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
4117 if (Reachable.count(Pred) &&
4118 (SPState[Pred->getNumber()].ExitValue != BBState.EntryValue ||
4119 SPState[Pred->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
4120 report("The exit stack state of a predecessor is inconsistent.", MBB);
4121 OS << "Predecessor " << printMBBReference(*Pred) << " has exit state ("
4122 << SPState[Pred->getNumber()].ExitValue << ", "
4123 << SPState[Pred->getNumber()].ExitIsSetup << "), while "
4124 << printMBBReference(*MBB) << " has entry state ("
4125 << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
4126 }
4127 }
4128
4129 // Make sure the entry state of any successor is consistent with the exit
4130 // state.
4131 for (const MachineBasicBlock *Succ : MBB->successors()) {
4132 if (Reachable.count(Succ) &&
4133 (SPState[Succ->getNumber()].EntryValue != BBState.ExitValue ||
4134 SPState[Succ->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
4135 report("The entry stack state of a successor is inconsistent.", MBB);
4136 OS << "Successor " << printMBBReference(*Succ) << " has entry state ("
4137 << SPState[Succ->getNumber()].EntryValue << ", "
4138 << SPState[Succ->getNumber()].EntryIsSetup << "), while "
4139 << printMBBReference(*MBB) << " has exit state ("
4140 << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
4141 }
4142 }
4143
4144 // Make sure a basic block with return ends with zero stack adjustment.
4145 if (!MBB->empty() && MBB->back().isReturn()) {
4146 if (BBState.ExitIsSetup)
4147 report("A return block ends with a FrameSetup.", MBB);
4148 if (BBState.ExitValue)
4149 report("A return block ends with a nonzero stack adjustment.", MBB);
4150 }
4151 }
4152}
4153
4154void MachineVerifier::verifyStackProtector() {
4155 const MachineFrameInfo &MFI = MF->getFrameInfo();
4156 if (!MFI.hasStackProtectorIndex())
4157 return;
4158 // Only applicable when the offsets of frame objects have been determined,
4159 // which is indicated by a non-zero stack size.
4160 if (!MFI.getStackSize())
4161 return;
4162 const TargetFrameLowering &TFI = *MF->getSubtarget().getFrameLowering();
4163 bool StackGrowsDown =
4165 unsigned FI = MFI.getStackProtectorIndex();
4166 int64_t SPStart = MFI.getObjectOffset(FI);
4167 int64_t SPEnd = SPStart + MFI.getObjectSize(FI);
4168 for (unsigned I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
4169 if (I == FI)
4170 continue;
4171 if (MFI.isDeadObjectIndex(I))
4172 continue;
4173 // FIXME: Skip non-default stack objects, as some targets may place them
4174 // above the stack protector. This is a workaround for the fact that
4175 // backends such as AArch64 may place SVE stack objects *above* the stack
4176 // protector.
4178 continue;
4179 // Skip variable-sized objects because they do not have a fixed offset.
4181 continue;
4182 // FIXME: Skip spill slots which may be allocated above the stack protector.
4183 // Ideally this would only skip callee-saved registers, but we don't have
4184 // that information here. For example, spill-slots used for scavenging are
4185 // not described in CalleeSavedInfo.
4186 if (MFI.isSpillSlotObjectIndex(I))
4187 continue;
4188 int64_t ObjStart = MFI.getObjectOffset(I);
4189 int64_t ObjEnd = ObjStart + MFI.getObjectSize(I);
4190 if (SPStart < ObjEnd && ObjStart < SPEnd) {
4191 report("Stack protector overlaps with another stack object", MF);
4192 break;
4193 }
4194 if ((StackGrowsDown && SPStart <= ObjStart) ||
4195 (!StackGrowsDown && SPStart >= ObjStart)) {
4196 report("Stack protector is not the top-most object on the stack", MF);
4197 break;
4198 }
4199 }
4200}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
uint64_t Imm
static bool isLoad(int Opcode)
static bool isStore(int Opcode)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file implements the BitVector class.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
A common definition of LaneBitmask for use in TableGen and CodeGen.
Implement a low-level type suitable for MachineInstr level instruction selection.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:629
This file declares the MIR specialization of the GenericConvergenceVerifier template.
Register Reg
Register const TargetRegisterInfo * TRI
static void verifyConvergenceControl(const MachineFunction &MF, MachineDominatorTree &DT, std::function< void(const Twine &Message)> FailureCB, raw_ostream &OS)
static bool hasPHIs(const MachineFunction &MF)
Promote Memory to Register
Definition Mem2Reg.cpp:110
modulo schedule Modulo Schedule test pass
#define P(N)
ppc ctr loops verify
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
SmallVector< MachineOperand, 4 > Cond
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg)
SI Optimize VGPR LiveRange
const char * Msg
SmallPtrSet< BasicBlock *, 0 > BlockSet
This file contains some templates that are useful if you are working with the STL at all.
This file defines generic set operations that may be used on set's of different types,...
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file describes how to lower LLVM code to machine code.
static unsigned getSize(unsigned Kind)
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
Definition APFloat.cpp:398
const fltSemantics & getSemantics() const
Definition APFloat.h:1591
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:406
LLVM Basic Block Representation.
Definition BasicBlock.h:62
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:666
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
void clear()
Removes all bits from the bitvector.
Definition BitVector.h:349
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:159
ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a LiveInterval into equivalence cl...
ConstMIBundleOperands - Iterate over all operands in a const bundle of machine instructions.
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
This is the shared class of boolean and integer constants.
Definition Constants.h:87
IntegerType * getIntegerType() const
Variant of the getType() method to always return an IntegerType, which reduces the amount of casting ...
Definition Constants.h:198
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
Register getReg() const
Base class for user error types.
Definition Error.h:354
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
const Function & getFunction() const
Definition Function.h:167
void initialize(raw_ostream *OS, function_ref< void(const Twine &Message)> FailureCB, const FunctionT &F)
bool isPredicated(const MachineInstr &MI) const override
Returns true if the instruction is already predicated.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
constexpr bool isScalableVector() const
Returns true if the LLT is a scalable vector.
constexpr unsigned getScalarSizeInBits() const
constexpr bool isFloatOrFloatVector() const
constexpr bool isScalar() const
constexpr Kind getKind() const
LLT getScalarType() const
constexpr bool isPointerVector() const
constexpr FpSemantics getFpSemantics() const
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr bool isValid() const
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
constexpr bool isVector() const
constexpr bool isScalable() const
Returns true if the LLT is a scalable vector.
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
constexpr bool isPointer() const
constexpr ElementCount getElementCount() const
constexpr unsigned getAddressSpace() const
constexpr bool isPointerOrPointerVector() const
constexpr bool isFixedVector() const
Returns true if the LLT is a fixed vector.
constexpr TypeSize getSizeInBytes() const
Returns the total size of the type in bytes, i.e.
LLT getElementType() const
Returns the vector's element type. Only valid for vector types.
A live range for subregisters.
LiveInterval - This class represents the liveness of a register, or stack slot.
Register reg() const
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
LLVM_ABI void computeSubRangeUndefs(SmallVectorImpl< SlotIndex > &Undefs, LaneBitmask LaneMask, const MachineRegisterInfo &MRI, const SlotIndexes &Indexes) const
For a given lane mask LaneMask, compute indexes at which the lane is marked undefined by subregister ...
void print(raw_ostream &O, const Module *=nullptr) const override
Implement the dump method.
Result of a LiveRange query.
bool isDeadDef() const
Return true if this instruction has a dead def.
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
VNInfo * valueOut() const
Return the value leaving the instruction, if any.
bool isKill() const
Return true if the live-in value is killed by this instruction.
static LLVM_ABI bool isJointlyDominated(const MachineBasicBlock *MBB, ArrayRef< SlotIndex > Defs, const SlotIndexes &Indexes)
A diagnostic function to check if the end of the block MBB is jointly dominated by the blocks corresp...
This class represents the liveness of a register, stack slot, etc.
VNInfo * getValNumInfo(unsigned ValNo)
getValNumInfo - Returns pointer to the specified val#.
Segments::const_iterator const_iterator
bool liveAt(SlotIndex index) const
LLVM_ABI bool covers(const LiveRange &Other) const
Returns true if all segments of the Other live range are completely covered by this live range.
bool empty() const
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarily including Idx,...
bool verify() const
Walk the range and assert if any invariants fail to hold.
unsigned getNumValNums() const
iterator begin()
VNInfoList valnos
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
TypeSize getValue() const
Describe properties that are true of each instruction in the target description file.
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition MCInstrDesc.h:88
MCRegAliasIterator enumerates all registers aliasing Reg.
bool hasSuperClassEq(const MCRegisterClass *RC) const
Returns true if RC is a super-class of or equal to this class.
LaneBitmask getLaneMask() const
Returns the combination of all lane masks of register in this class.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
bool isValid() const
isValid - Returns true until all the operands have been visited.
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
bool isEHPad() const
Returns true if the block is a landing pad.
iterator_range< livein_iterator > liveins() const
iterator_range< iterator > phis()
Returns a range that iterates over the phis in the basic block.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
bool isIRBlockAddressTaken() const
Test whether this block is the target of an IR BlockAddress.
BasicBlock * getAddressTakenIRBlock() const
Retrieves the BasicBlock which corresponds to this MachineBasicBlock.
LLVM_ABI bool isPredecessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a predecessor of this block.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
unsigned getCallFrameSize() const
Return the call frame size on entry to this basic block.
iterator_range< succ_iterator > successors()
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
iterator_range< pred_iterator > predecessors()
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
int getStackProtectorIndex() const
Return the index for the stack protector object.
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
LLVM_ABI BitVector getPristineRegs(const MachineFunction &MF) const
Return a set of physical registers that are pristine.
bool isVariableSizedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a variable sized object.
int getObjectIndexEnd() const
Return one past the maximum frame object index.
bool hasStackProtectorIndex() const
uint8_t getStackID(int ObjectIdx) const
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, raw_ostream *OS=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineBasicBlock & front() const
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
BasicBlockListType::const_iterator const_iterator
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool isReturn(QueryType Type=AnyInBundle) const
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
bool isBarrier(QueryType Type=AnyInBundle) const
Returns true if the specified instruction stops control flow from executing the instruction immediate...
A description of a memory reference used in the backend.
LocationSize getSize() const
Return the size in bytes of the memory reference.
const PseudoSourceValue * getPseudoValue() const
LLT getMemoryType() const
Return the memory type of the memory reference.
const MDNode * getRanges() const
Return the range tag for the memory reference.
AtomicOrdering getSuccessOrdering() const
Return the atomic ordering requirements for this memory operation.
LocationSize getSizeInBits() const
Return the size in bits of the memory reference.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
int64_t getImm() const
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
bool isIntrinsicID() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
ArrayRef< int > getShuffleMask() const
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isValidExcessOperand() const
Return true if this operand can validly be appended to an arbitrary operand list.
bool isShuffleMask() const
LLVM_ABI void print(raw_ostream &os, const TargetRegisterInfo *TRI=nullptr) const
Print the MachineOperand to os.
LaneBitmask getLaneMask() const
unsigned getCFIIndex() const
LLVM_ABI bool isRenamable() const
isRenamable - Returns true if this register may be renamed, i.e.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
bool isInternalRead() const
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
@ MO_CFIIndex
MCCFIInstruction index.
@ MO_RegisterMask
Mask of preserved registers.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_FrameIndex
Abstract Stack Frame Index.
@ MO_Register
Register operand.
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
use_nodbg_iterator use_nodbg_begin(Register RegNo) const
LLVM_ABI void verifyUseLists() const
Verify the use list of all registers.
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
static use_nodbg_iterator use_nodbg_end()
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
const BitVector & getReservedRegs() const
getReservedRegs - Returns a reference to the frozen set of reserved registers.
LLT getType(Register Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register.
bool reservedRegsFrozen() const
reservedRegsFrozen - Returns true after freezeReservedRegs() was called to ensure the set of reserved...
bool def_empty(Register RegNo) const
def_empty - Return true if there are no instructions defining the specified register (it may be live-...
bool reg_nodbg_empty(Register RegNo) const
reg_nodbg_empty - Return true if the only instructions using or defining Reg are Debug instructions.
const RegisterBank * getRegBankOrNull(Register Reg) const
Return the register bank of Reg, or null if Reg has not been assigned a register bank or has been ass...
bool shouldTrackSubRegLiveness(const TargetRegisterClass &RC) const
Returns true if liveness for register class RC should be tracked at the subregister level.
bool hasOneDef(Register RegNo) const
Return true if there is exactly one operand defining the specified register.
LLVM_ABI bool isReservedRegUnit(MCRegUnit Unit) const
Returns true when the given register unit is considered reserved.
const TargetRegisterClass * getRegClassOrNull(Register Reg) const
Return the register class of Reg, or null if Reg has not been assigned a register class yet.
LLVM_ABI LaneBitmask getMaxLaneMaskForVReg(Register Reg) const
Returns a mask covering all bits that can appear in lane masks of subregisters of the virtual registe...
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:97
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition Pass.cpp:142
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Holds all the information related to register banks.
const RegisterBank & getRegBank(unsigned ID)
Get the register bank identified by ID.
unsigned getMaximumSize(unsigned RegBankID) const
Get the maximum size in bits that fits in the given register bank.
This class implements the register bank concept.
const char * getName() const
Get a user friendly name of this register bank.
unsigned getID() const
Get the identifier of this register bank.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
unsigned virtRegIndex() const
Convert a virtual register number to a 0-based index.
Definition Register.h:87
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr unsigned id() const
Definition Register.h:100
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
bool isBlock() const
isBlock - Returns true if this is a block boundary slot.
SlotIndex getDeadSlot() const
Returns the dead def kill slot for the current instruction.
bool isEarlyClobber() const
isEarlyClobber - Returns true if this is an early-clobber slot.
bool isRegister() const
isRegister - Returns true if this is a normal register use/def slot.
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
bool isDead() const
isDead - Returns true if this is a dead def kill slot.
SlotIndexes pass.
MBBIndexIterator MBBIndexBegin() const
Returns an iterator for the begin of the idx2MBBMap.
MBBIndexIterator MBBIndexEnd() const
Return an iterator for the end of the idx2MBBMap.
SmallVectorImpl< IdxMBBPair >::const_iterator MBBIndexIterator
Iterator over the idx2MBBMap (sorted pairs of slot index of basic block begin and basic block)
size_type size() const
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Register getReg() const
MI-level Statepoint operands.
Definition StackMaps.h:159
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Information about stack frame layout on the target.
StackDirection getStackGrowthDirection() const
getStackGrowthDirection - Return the direction the stack grows
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const RegisterBankInfo * getRegBankInfo() const
If the information for the register banks is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getZero()
Definition TypeSize.h:358
Value * getOperand(unsigned i) const
Definition User.h:207
VNInfo - Value Number Information.
bool isUnused() const
Returns true if this value is unused.
unsigned id
The ID number of this value.
SlotIndex def
The index of the defining instruction.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
LLVM Value Representation.
Definition Value.h:75
Wrapper class representing a virtual register or register unit.
Definition Register.h:175
constexpr bool isVirtualReg() const
Definition Register.h:191
constexpr MCRegUnit asMCRegUnit() const
Definition Register.h:195
constexpr Register asVirtualReg() const
Definition Register.h:200
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
constexpr bool isNonZero() const
Definition TypeSize.h:156
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:217
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:224
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:238
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
LLVM_ABI AttributeSet getFnAttributes(LLVMContext &C, ID id)
Return the function attributes for an intrinsic.
@ OPERAND_IMMEDIATE
Definition MCInstrDesc.h:61
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
iterator end() const
Definition BasicBlock.h:89
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
bool isPreISelGenericOpcode(unsigned Opcode)
Check whether the given Opcode is a generic opcode that is not supposed to appear after ISel.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
void set_subtract(S1Ty &S1, const S2Ty &S2)
set_subtract(A, B) - Compute A := A - B
Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
Definition LaneBitmask.h:92
LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
bool isPreISelGenericOptimizationHint(unsigned Opcode)
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
LLVM_ABI FunctionPass * createMachineVerifierPass(const std::string &Banner)
createMachineVerifierPass - This pass verifies cenerated machine code instructions for correctness.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI void verifyMachineFunction(const std::string &Banner, const MachineFunction &MF)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
detail::ValueMatchesPoly< M > HasValue(M Matcher)
Definition Error.h:221
df_ext_iterator< T, SetTy > df_ext_begin(const T &G, SetTy &S)
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
GenericConvergenceVerifier< MachineSSAContext > MachineConvergenceVerifier
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
LLVM_ABI raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Other
Any other memory.
Definition ModRef.h:68
@ Sub
Subtraction of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
df_ext_iterator< T, SetTy > df_ext_end(const T &G, SetTy &S)
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82
constexpr bool none() const
Definition LaneBitmask.h:52
constexpr bool any() const
Definition LaneBitmask.h:53
static constexpr LaneBitmask getNone()
Definition LaneBitmask.h:81
This represents a simple continuous liveness interval for a value.
Pair of physical register and lane mask.