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