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