LLVM 24.0.0git
MIParser.cpp
Go to the documentation of this file.
1//===- MIParser.cpp - Machine instructions parser implementation ----------===//
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// This file implements the parsing of machine instructions.
10//
11//===----------------------------------------------------------------------===//
12
14#include "MILexer.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/APSInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/ADT/StringRef.h"
23#include "llvm/ADT/Twine.h"
43#include "llvm/IR/BasicBlock.h"
44#include "llvm/IR/Constants.h"
45#include "llvm/IR/DataLayout.h"
47#include "llvm/IR/DebugLoc.h"
48#include "llvm/IR/Function.h"
49#include "llvm/IR/InlineAsm.h"
50#include "llvm/IR/InstrTypes.h"
52#include "llvm/IR/Intrinsics.h"
53#include "llvm/IR/Metadata.h"
54#include "llvm/IR/Module.h"
56#include "llvm/IR/Type.h"
57#include "llvm/IR/Value.h"
59#include "llvm/MC/LaneBitmask.h"
60#include "llvm/MC/MCContext.h"
61#include "llvm/MC/MCDwarf.h"
62#include "llvm/MC/MCInstrDesc.h"
68#include "llvm/Support/SMLoc.h"
71#include <cassert>
72#include <cctype>
73#include <cstddef>
74#include <cstdint>
75#include <limits>
76#include <string>
77#include <utility>
78
79using namespace llvm;
80
82 const TargetSubtargetInfo &NewSubtarget) {
83
84 // If the subtarget changed, over conservatively assume everything is invalid.
85 if (&Subtarget == &NewSubtarget)
86 return;
87
88 Names2InstrOpCodes.clear();
89 Names2Regs.clear();
90 Names2RegMasks.clear();
91 Names2SubRegIndices.clear();
92 Names2TargetIndices.clear();
93 Names2DirectTargetFlags.clear();
94 Names2BitmaskTargetFlags.clear();
95 Names2MMOTargetFlags.clear();
96
97 initNames2RegClasses();
98 initNames2RegBanks();
99}
100
101void PerTargetMIParsingState::initNames2Regs() {
102 if (!Names2Regs.empty())
103 return;
104
105 // The '%noreg' register is the register 0.
106 Names2Regs.insert(std::make_pair("noreg", 0));
107 const auto *TRI = Subtarget.getRegisterInfo();
108 assert(TRI && "Expected target register info");
109
110 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
111 bool WasInserted =
112 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
113 .second;
114 (void)WasInserted;
115 assert(WasInserted && "Expected registers to be unique case-insensitively");
116 }
117}
118
120 Register &Reg) {
121 initNames2Regs();
122 auto RegInfo = Names2Regs.find(RegName);
123 if (RegInfo == Names2Regs.end())
124 return true;
125 Reg = RegInfo->getValue();
126 return false;
127}
128
130 uint8_t &FlagValue) const {
131 const auto *TRI = Subtarget.getRegisterInfo();
132 std::optional<uint8_t> FV = TRI->getVRegFlagValue(FlagName);
133 if (!FV)
134 return true;
135 FlagValue = *FV;
136 return false;
137}
138
139void PerTargetMIParsingState::initNames2InstrOpCodes() {
140 if (!Names2InstrOpCodes.empty())
141 return;
142 const auto *TII = Subtarget.getInstrInfo();
143 assert(TII && "Expected target instruction info");
144 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
145 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
146}
147
149 unsigned &OpCode) {
150 initNames2InstrOpCodes();
151 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
152 if (InstrInfo == Names2InstrOpCodes.end())
153 return true;
154 OpCode = InstrInfo->getValue();
155 return false;
156}
157
158void PerTargetMIParsingState::initNames2RegMasks() {
159 if (!Names2RegMasks.empty())
160 return;
161 const auto *TRI = Subtarget.getRegisterInfo();
162 assert(TRI && "Expected target register info");
163 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
164 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
165 assert(RegMasks.size() == RegMaskNames.size());
166 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
167 Names2RegMasks.insert(
168 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
169}
170
172 initNames2RegMasks();
173 auto RegMaskInfo = Names2RegMasks.find(Identifier);
174 if (RegMaskInfo == Names2RegMasks.end())
175 return nullptr;
176 return RegMaskInfo->getValue();
177}
178
179void PerTargetMIParsingState::initNames2SubRegIndices() {
180 if (!Names2SubRegIndices.empty())
181 return;
182 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
183 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
184 Names2SubRegIndices.insert(
185 std::make_pair(TRI->getSubRegIndexName(I), I));
186}
187
189 initNames2SubRegIndices();
190 auto SubRegInfo = Names2SubRegIndices.find(Name);
191 if (SubRegInfo == Names2SubRegIndices.end())
192 return 0;
193 return SubRegInfo->getValue();
194}
195
196void PerTargetMIParsingState::initNames2TargetIndices() {
197 if (!Names2TargetIndices.empty())
198 return;
199 const auto *TII = Subtarget.getInstrInfo();
200 assert(TII && "Expected target instruction info");
201 auto Indices = TII->getSerializableTargetIndices();
202 for (const auto &I : Indices)
203 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
204}
205
207 initNames2TargetIndices();
208 auto IndexInfo = Names2TargetIndices.find(Name);
209 if (IndexInfo == Names2TargetIndices.end())
210 return true;
211 Index = IndexInfo->second;
212 return false;
213}
214
215void PerTargetMIParsingState::initNames2DirectTargetFlags() {
216 if (!Names2DirectTargetFlags.empty())
217 return;
218
219 const auto *TII = Subtarget.getInstrInfo();
220 assert(TII && "Expected target instruction info");
221 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
222 for (const auto &I : Flags)
223 Names2DirectTargetFlags.insert(
224 std::make_pair(StringRef(I.second), I.first));
225}
226
228 unsigned &Flag) {
229 initNames2DirectTargetFlags();
230 auto FlagInfo = Names2DirectTargetFlags.find(Name);
231 if (FlagInfo == Names2DirectTargetFlags.end())
232 return true;
233 Flag = FlagInfo->second;
234 return false;
235}
236
237void PerTargetMIParsingState::initNames2BitmaskTargetFlags() {
238 if (!Names2BitmaskTargetFlags.empty())
239 return;
240
241 const auto *TII = Subtarget.getInstrInfo();
242 assert(TII && "Expected target instruction info");
243 auto Flags = TII->getSerializableBitmaskMachineOperandTargetFlags();
244 for (const auto &I : Flags)
245 Names2BitmaskTargetFlags.insert(
246 std::make_pair(StringRef(I.second), I.first));
247}
248
250 unsigned &Flag) {
251 initNames2BitmaskTargetFlags();
252 auto FlagInfo = Names2BitmaskTargetFlags.find(Name);
253 if (FlagInfo == Names2BitmaskTargetFlags.end())
254 return true;
255 Flag = FlagInfo->second;
256 return false;
257}
258
259void PerTargetMIParsingState::initNames2MMOTargetFlags() {
260 if (!Names2MMOTargetFlags.empty())
261 return;
262
263 const auto *TII = Subtarget.getInstrInfo();
264 assert(TII && "Expected target instruction info");
265 auto Flags = TII->getSerializableMachineMemOperandTargetFlags();
266 for (const auto &I : Flags)
267 Names2MMOTargetFlags.insert(std::make_pair(StringRef(I.second), I.first));
268}
269
272 initNames2MMOTargetFlags();
273 auto FlagInfo = Names2MMOTargetFlags.find(Name);
274 if (FlagInfo == Names2MMOTargetFlags.end())
275 return true;
276 Flag = FlagInfo->second;
277 return false;
278}
279
280void PerTargetMIParsingState::initNames2RegClasses() {
281 if (!Names2RegClasses.empty())
282 return;
283
284 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
285 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
286 const auto *RC = TRI->getRegClass(I);
287 Names2RegClasses.insert(
288 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
289 }
290}
291
292void PerTargetMIParsingState::initNames2RegBanks() {
293 if (!Names2RegBanks.empty())
294 return;
295
296 const RegisterBankInfo *RBI = Subtarget.getRegBankInfo();
297 // If the target does not support GlobalISel, we may not have a
298 // register bank info.
299 if (!RBI)
300 return;
301
302 for (unsigned I = 0, E = RBI->getNumRegBanks(); I < E; ++I) {
303 const auto &RegBank = RBI->getRegBank(I);
304 Names2RegBanks.insert(
305 std::make_pair(StringRef(RegBank.getName()).lower(), &RegBank));
306 }
307}
308
311 auto RegClassInfo = Names2RegClasses.find(Name);
312 if (RegClassInfo == Names2RegClasses.end())
313 return nullptr;
314 return RegClassInfo->getValue();
315}
316
318 auto RegBankInfo = Names2RegBanks.find(Name);
319 if (RegBankInfo == Names2RegBanks.end())
320 return nullptr;
321 return RegBankInfo->getValue();
322}
323
328
330 auto I = VRegInfos.try_emplace(Num);
331 if (I.second) {
332 MachineRegisterInfo &MRI = MF.getRegInfo();
333 VRegInfo *Info = new (Allocator) VRegInfo;
334 Info->VReg = MRI.createIncompleteVirtualRegister();
335 I.first->second = Info;
336 }
337 return *I.first->second;
338}
339
341 assert(RegName != "" && "Expected named reg.");
342
343 auto I = VRegInfosNamed.try_emplace(RegName.str());
344 if (I.second) {
345 VRegInfo *Info = new (Allocator) VRegInfo;
346 Info->VReg = MF.getRegInfo().createIncompleteVirtualRegister(RegName);
347 I.first->second = Info;
348 }
349 return *I.first->second;
350}
351
352static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST,
353 DenseMap<unsigned, const Value *> &Slots2Values) {
354 int Slot = MST.getLocalSlot(V);
355 if (Slot == -1)
356 return;
357 Slots2Values.insert(std::make_pair(unsigned(Slot), V));
358}
359
360/// Creates the mapping from slot numbers to function's unnamed IR values.
361static void initSlots2Values(const Function &F,
362 DenseMap<unsigned, const Value *> &Slots2Values) {
363 ModuleSlotTracker MST(F.getParent());
365 for (const auto &Arg : F.args())
366 mapValueToSlot(&Arg, MST, Slots2Values);
367 for (const auto &BB : F) {
368 mapValueToSlot(&BB, MST, Slots2Values);
369 for (const auto &I : BB)
370 mapValueToSlot(&I, MST, Slots2Values);
371 }
372}
373
375 if (Slots2Values.empty())
376 initSlots2Values(MF.getFunction(), Slots2Values);
377 return Slots2Values.lookup(Slot);
378}
379
380namespace {
381
382/// A wrapper struct around the 'MachineOperand' struct that includes a source
383/// range and other attributes.
384struct ParsedMachineOperand {
385 MachineOperand Operand;
388 std::optional<unsigned> TiedDefIdx;
389
390 ParsedMachineOperand(const MachineOperand &Operand, StringRef::iterator Begin,
392 std::optional<unsigned> &TiedDefIdx)
393 : Operand(Operand), Begin(Begin), End(End), TiedDefIdx(TiedDefIdx) {
394 if (TiedDefIdx)
395 assert(Operand.isReg() && Operand.isUse() &&
396 "Only used register operands can be tied");
397 }
398};
399
400class MIParser {
401 MachineFunction &MF;
402 SMDiagnostic &Error;
403 StringRef Source, CurrentSource;
404 MIToken Token;
405 PerFunctionMIParsingState &PFS;
406 /// Maps from slot numbers to function's unnamed basic blocks.
407 DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks;
408
409public:
410 MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
411 StringRef Source);
412
413 /// \p SkipChar gives the number of characters to skip before looking
414 /// for the next token.
415 void lex(unsigned SkipChar = 0);
416
417 /// Report an error at the current location with the given message.
418 ///
419 /// This function always return true.
420 bool error(const Twine &Msg);
421
422 /// Report an error at the given location with the given message.
423 ///
424 /// This function always return true.
425 bool error(StringRef::iterator Loc, const Twine &Msg);
426
427 bool
428 parseBasicBlockDefinitions(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
429 bool parseBasicBlocks();
430 bool parse(MachineInstr *&MI);
431 bool parseStandaloneMBB(MachineBasicBlock *&MBB);
432 bool parseStandaloneNamedRegister(Register &Reg);
433 bool parseStandaloneVirtualRegister(VRegInfo *&Info);
434 bool parseStandaloneRegister(Register &Reg);
435 bool parseStandaloneStackObject(int &FI);
436 bool parseStandaloneMDNode(MDNode *&Node);
437
438 bool
439 parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
440 bool parseBasicBlock(MachineBasicBlock &MBB,
441 MachineBasicBlock *&AddFalthroughFrom);
442 bool parseBasicBlockLiveins(MachineBasicBlock &MBB);
443 bool parseBasicBlockSuccessors(MachineBasicBlock &MBB);
444
445 bool parseNamedRegister(Register &Reg);
446 bool parseVirtualRegister(VRegInfo *&Info);
447 bool parseNamedVirtualRegister(VRegInfo *&Info);
448 bool parseRegister(Register &Reg, VRegInfo *&VRegInfo);
449 bool parseRegisterFlag(RegState &Flags);
450 bool parseRegisterClassOrBank(VRegInfo &RegInfo);
451 bool parseSubRegisterIndex(unsigned &SubReg);
452 bool parseRegisterTiedDefIndex(unsigned &TiedDefIdx);
453 bool parseRegisterOperand(MachineOperand &Dest,
454 std::optional<unsigned> &TiedDefIdx,
455 bool IsDef = false);
456 bool parseImmediateOperand(MachineOperand &Dest);
457 bool parseSymbolicInlineAsmOperand(unsigned OpIdx, MachineOperand &Dest);
458 bool parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
459 const Constant *&C);
460 bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
461 bool parseLowLevelType(StringRef::iterator Loc, LLT &Ty);
462 bool parseTypedImmediateOperand(MachineOperand &Dest);
463 bool parseFPImmediateOperand(MachineOperand &Dest);
464 bool parseMBBReference(MachineBasicBlock *&MBB);
465 bool parseMBBOperand(MachineOperand &Dest);
466 bool parseStackFrameIndex(int &FI);
467 bool parseStackObjectOperand(MachineOperand &Dest);
468 bool parseFixedStackFrameIndex(int &FI);
469 bool parseFixedStackObjectOperand(MachineOperand &Dest);
470 bool parseGlobalValue(GlobalValue *&GV);
471 bool parseGlobalAddressOperand(MachineOperand &Dest);
472 bool parseConstantPoolIndexOperand(MachineOperand &Dest);
473 bool parseSubRegisterIndexOperand(MachineOperand &Dest);
474 bool parseJumpTableIndexOperand(MachineOperand &Dest);
475 bool parseExternalSymbolOperand(MachineOperand &Dest);
476 bool parseMCSymbolOperand(MachineOperand &Dest);
477 [[nodiscard]] bool parseMDNode(MDNode *&Node);
478 bool parseDIExpression(MDNode *&Expr);
479 bool parseDILocation(MDNode *&Expr);
480 bool parseMetadataOperand(MachineOperand &Dest);
481 bool parseCFIOffset(int64_t &Offset);
482 bool parseCFIUnsigned(unsigned &Value);
483 bool parseCFIRegister(unsigned &Reg);
484 bool parseCFIAddressSpace(unsigned &AddressSpace);
485 bool parseCFIEscapeValues(std::string& Values);
486 bool parseCFIOperand(MachineOperand &Dest);
487 bool parseIRBlock(BasicBlock *&BB, const Function &F);
488 bool parseBlockAddressOperand(MachineOperand &Dest);
489 bool parseIntrinsicOperand(MachineOperand &Dest);
490 bool parsePredicateOperand(MachineOperand &Dest);
491 bool parseShuffleMaskOperand(MachineOperand &Dest);
492 bool parseTargetIndexOperand(MachineOperand &Dest);
493 bool parseDbgInstrRefOperand(MachineOperand &Dest);
494 bool parseCustomRegisterMaskOperand(MachineOperand &Dest);
495 bool parseLaneMaskOperand(MachineOperand &Dest);
496 bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
497 bool parseMachineOperand(const unsigned OpCode, const unsigned OpIdx,
498 MachineOperand &Dest,
499 std::optional<unsigned> &TiedDefIdx);
500 bool parseMachineOperandAndTargetFlags(const unsigned OpCode,
501 const unsigned OpIdx,
502 MachineOperand &Dest,
503 std::optional<unsigned> &TiedDefIdx);
504 bool parseOffset(int64_t &Offset);
505 bool parseIRBlockAddressTaken(BasicBlock *&BB);
506 bool parseAlignment(uint64_t &Alignment);
507 bool parseAddrspace(unsigned &Addrspace);
508 bool parseSectionID(std::optional<MBBSectionID> &SID);
509 bool parseBBID(std::optional<UniqueBBID> &BBID);
510 bool parseCallFrameSize(unsigned &CallFrameSize);
511 bool parseMaxBytesForAlignment(unsigned &MaxBytesForAlignment);
512 bool parsePrefetchTarget(CallsiteID &Target);
513 bool parseOperandsOffset(MachineOperand &Op);
514 bool parseIRValue(const Value *&V);
515 bool parseMemoryOperandFlag(MachineMemOperand::Flags &Flags);
516 bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
517 bool parseMachinePointerInfo(MachinePointerInfo &Dest);
518 bool parseOptionalScope(LLVMContext &Context, SyncScope::ID &SSID);
519 bool parseOptionalAtomicOrdering(AtomicOrdering &Order);
520 bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
521 bool parsePreOrPostInstrSymbol(MCSymbol *&Symbol);
522 bool parseHeapAllocMarker(MDNode *&Node);
523 bool parsePCSections(MDNode *&Node);
524 bool parseMMRA(MDNode *&Node);
525
526 bool parseTargetImmMnemonic(const unsigned OpCode, const unsigned OpIdx,
527 MachineOperand &Dest, const MIRFormatter &MF);
528
529private:
530 /// Convert the integer literal in the current token into an unsigned integer.
531 ///
532 /// Return true if an error occurred.
533 bool getUnsigned(unsigned &Result);
534
535 /// Convert the integer literal in the current token into an uint64.
536 ///
537 /// Return true if an error occurred.
538 bool getUint64(uint64_t &Result);
539
540 /// Convert the hexadecimal literal in the current token into an unsigned
541 /// APInt with a minimum bitwidth required to represent the value.
542 ///
543 /// Return true if the literal does not represent an integer value.
544 bool getHexUint(APInt &Result);
545
546 /// If the current token is of the given kind, consume it and return false.
547 /// Otherwise report an error and return true.
548 bool expectAndConsume(MIToken::TokenKind TokenKind);
549
550 /// If the current token is of the given kind, consume it and return true.
551 /// Otherwise return false.
552 bool consumeIfPresent(MIToken::TokenKind TokenKind);
553
554 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
555
556 bool assignRegisterTies(MachineInstr &MI,
558
559 bool verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
560 const MCInstrDesc &MCID);
561
562 const BasicBlock *getIRBlock(unsigned Slot);
563 const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
564
565 /// Get or create an MCSymbol for a given name.
566 MCSymbol *getOrCreateMCSymbol(StringRef Name);
567
568 /// parseStringConstant
569 /// ::= StringConstant
570 bool parseStringConstant(std::string &Result);
571};
572
573} // end anonymous namespace
574
575MIParser::MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
576 StringRef Source)
577 : MF(PFS.MF), Error(Error), Source(Source), CurrentSource(Source), PFS(PFS)
578{}
579
580void MIParser::lex(unsigned SkipChar) {
581 CurrentSource = lexMIToken(
582 CurrentSource.substr(SkipChar), Token,
583 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
584}
585
586bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
587
588bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
589 const SourceMgr &SM = *PFS.SM;
590 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
591 const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
592 if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
593 // Create an ordinary diagnostic when the source manager's buffer is the
594 // source string.
596 return true;
597 }
598 // Create a diagnostic for a YAML string literal.
599 Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
600 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
601 Source, {}, {});
602 return true;
603}
604
605typedef function_ref<bool(StringRef::iterator Loc, const Twine &)>
607
608static const char *toString(MIToken::TokenKind TokenKind) {
609 switch (TokenKind) {
610 case MIToken::comma:
611 return "','";
612 case MIToken::equal:
613 return "'='";
614 case MIToken::colon:
615 return "':'";
616 case MIToken::lparen:
617 return "'('";
618 case MIToken::rparen:
619 return "')'";
620 default:
621 return "<unknown token>";
622 }
623}
624
625bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
626 if (Token.isNot(TokenKind))
627 return error(Twine("expected ") + toString(TokenKind));
628 lex();
629 return false;
630}
631
632bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
633 if (Token.isNot(TokenKind))
634 return false;
635 lex();
636 return true;
637}
638
639// Parse Machine Basic Block Section ID.
640bool MIParser::parseSectionID(std::optional<MBBSectionID> &SID) {
642 lex();
643 if (Token.is(MIToken::IntegerLiteral)) {
644 unsigned Value = 0;
645 if (getUnsigned(Value))
646 return error("Unknown Section ID");
647 SID = MBBSectionID{Value};
648 } else {
649 const StringRef &S = Token.stringValue();
650 if (S == "Exception")
652 else if (S == "Cold")
654 else
655 return error("Unknown Section ID");
656 }
657 lex();
658 return false;
659}
660
661// Parse Machine Basic Block ID.
662bool MIParser::parseBBID(std::optional<UniqueBBID> &BBID) {
663 if (Token.isNot(MIToken::kw_bb_id))
664 return error("expected 'bb_id'");
665 lex();
666 unsigned BaseID = 0;
667 unsigned CloneID = 0;
668 if (Token.is(MIToken::FloatingPointLiteral)) {
669 StringRef S = Token.range();
670 auto Parts = S.split('.');
671 if (Parts.first.getAsInteger(10, BaseID) ||
672 Parts.second.getAsInteger(10, CloneID))
673 return error("Unknown BB ID");
674 lex();
675 } else {
676 if (getUnsigned(BaseID))
677 return error("Unknown BB ID");
678 lex();
679 if (Token.is(MIToken::comma) || Token.is(MIToken::dot)) {
680 lex();
681 if (getUnsigned(CloneID))
682 return error("Unknown Clone ID");
683 lex();
684 } else if (Token.is(MIToken::IntegerLiteral)) {
685 if (getUnsigned(CloneID))
686 return error("Unknown Clone ID");
687 lex();
688 }
689 }
690 BBID = {BaseID, CloneID};
691 return false;
692}
693
694// Parse basic block call frame size.
695bool MIParser::parseCallFrameSize(unsigned &CallFrameSize) {
697 lex();
698 unsigned Value = 0;
699 if (getUnsigned(Value))
700 return error("Unknown call frame size");
701 CallFrameSize = Value;
702 lex();
703 return false;
704}
705
706// Parse the maximum number of bytes permitted for basic block alignment
707// padding.
708bool MIParser::parseMaxBytesForAlignment(unsigned &MaxBytesForAlignment) {
710 lex();
711 if (Token.isNot(MIToken::IntegerLiteral) && Token.isNot(MIToken::HexLiteral))
712 return error("expected an integer literal after 'max-bytes-for-alignment'");
713 unsigned Value = 0;
714 if (getUnsigned(Value))
715 return true;
716 MaxBytesForAlignment = Value;
717 lex();
718 return false;
719}
720
721bool MIParser::parsePrefetchTarget(CallsiteID &Target) {
722 lex();
723 std::optional<UniqueBBID> BBID;
724 if (parseBBID(BBID))
725 return true;
726 Target.BBID = *BBID;
727 if (expectAndConsume(MIToken::comma))
728 return true;
729 return getUnsigned(Target.CallsiteIndex);
730}
731
732bool MIParser::parseBasicBlockDefinition(
735 unsigned ID = 0;
736 if (getUnsigned(ID))
737 return true;
738 auto Loc = Token.location();
739 auto Name = Token.stringValue();
740 lex();
741 bool MachineBlockAddressTaken = false;
742 bool LabelMustBeEmitted = false;
743 BasicBlock *AddressTakenIRBlock = nullptr;
744 bool IsLandingPad = false;
745 bool IsInlineAsmBrIndirectTarget = false;
746 bool IsEHFuncletEntry = false;
747 bool IsEHScopeEntry = false;
748 bool IsCleanupFuncletEntry = false;
749 bool IsEHContTarget = false;
750 std::optional<MBBSectionID> SectionID;
752 unsigned MaxBytesForAlignment = 0;
753 std::optional<UniqueBBID> BBID;
754 unsigned CallFrameSize = 0;
755 BasicBlock *BB = nullptr;
756 if (consumeIfPresent(MIToken::lparen)) {
757 do {
758 // TODO: Report an error when multiple same attributes are specified.
759 switch (Token.kind()) {
761 MachineBlockAddressTaken = true;
762 lex();
763 break;
765 LabelMustBeEmitted = true;
766 lex();
767 break;
769 if (parseIRBlockAddressTaken(AddressTakenIRBlock))
770 return true;
771 break;
773 IsLandingPad = true;
774 lex();
775 break;
777 IsInlineAsmBrIndirectTarget = true;
778 lex();
779 break;
781 IsEHFuncletEntry = true;
782 lex();
783 break;
785 IsEHScopeEntry = true;
786 lex();
787 break;
789 IsCleanupFuncletEntry = true;
790 lex();
791 break;
793 IsEHContTarget = true;
794 lex();
795 break;
797 if (parseAlignment(Alignment))
798 return true;
799 break;
801 if (parseMaxBytesForAlignment(MaxBytesForAlignment))
802 return true;
803 break;
804 case MIToken::IRBlock:
806 // TODO: Report an error when both name and ir block are specified.
807 if (parseIRBlock(BB, MF.getFunction()))
808 return true;
809 lex();
810 break;
812 if (parseSectionID(SectionID))
813 return true;
814 break;
816 if (parseBBID(BBID))
817 return true;
818 break;
820 if (parseCallFrameSize(CallFrameSize))
821 return true;
822 break;
823 default:
824 break;
825 }
826 } while (consumeIfPresent(MIToken::comma));
827 if (expectAndConsume(MIToken::rparen))
828 return true;
829 }
830 if (expectAndConsume(MIToken::colon))
831 return true;
832
833 if (!Name.empty()) {
835 MF.getFunction().getValueSymbolTable()->lookup(Name));
836 if (!BB)
837 return error(Loc, Twine("basic block '") + Name +
838 "' is not defined in the function '" +
839 MF.getName() + "'");
840 }
841 auto *MBB = MF.CreateMachineBasicBlock(BB, BBID);
842 MF.insert(MF.end(), MBB);
843 bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
844 if (!WasInserted)
845 return error(Loc, Twine("redefinition of machine basic block with id #") +
846 Twine(ID));
847 if (Alignment)
848 MBB->setAlignment(Align(Alignment));
849 else if (MaxBytesForAlignment)
850 return error(Loc, "'max-bytes-for-alignment' requires 'align'");
851 MBB->setMaxBytesForAlignment(MaxBytesForAlignment);
852 if (MachineBlockAddressTaken)
854 if (LabelMustBeEmitted)
856 if (AddressTakenIRBlock)
857 MBB->setAddressTakenIRBlock(AddressTakenIRBlock);
858 MBB->setIsEHPad(IsLandingPad);
859 MBB->setIsInlineAsmBrIndirectTarget(IsInlineAsmBrIndirectTarget);
860 MBB->setIsEHFuncletEntry(IsEHFuncletEntry);
861 MBB->setIsEHScopeEntry(IsEHScopeEntry);
862 MBB->setIsCleanupFuncletEntry(IsCleanupFuncletEntry);
863 MBB->setIsEHContTarget(IsEHContTarget);
864 if (SectionID) {
865 MBB->setSectionID(*SectionID);
866 MF.setBBSectionsType(BasicBlockSection::List);
867 }
868 MBB->setCallFrameSize(CallFrameSize);
869 return false;
870}
871
872bool MIParser::parseBasicBlockDefinitions(
874 lex();
875 // Skip until the first machine basic block.
876 while (Token.is(MIToken::Newline))
877 lex();
878 if (Token.isErrorOrEOF())
879 return Token.isError();
880 if (Token.isNot(MIToken::MachineBasicBlockLabel))
881 return error("expected a basic block definition before instructions");
882 unsigned BraceDepth = 0;
883 do {
884 if (parseBasicBlockDefinition(MBBSlots))
885 return true;
886 bool IsAfterNewline = false;
887 // Skip until the next machine basic block.
888 while (true) {
889 if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
890 Token.isErrorOrEOF())
891 break;
892 else if (Token.is(MIToken::MachineBasicBlockLabel))
893 return error("basic block definition should be located at the start of "
894 "the line");
895 else if (consumeIfPresent(MIToken::Newline)) {
896 IsAfterNewline = true;
897 continue;
898 }
899 IsAfterNewline = false;
900 if (Token.is(MIToken::lbrace))
901 ++BraceDepth;
902 if (Token.is(MIToken::rbrace)) {
903 if (!BraceDepth)
904 return error("extraneous closing brace ('}')");
905 --BraceDepth;
906 }
907 lex();
908 }
909 // Verify that we closed all of the '{' at the end of a file or a block.
910 if (!Token.isError() && BraceDepth)
911 return error("expected '}'"); // FIXME: Report a note that shows '{'.
912 } while (!Token.isErrorOrEOF());
913 return Token.isError();
914}
915
916bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
917 assert(Token.is(MIToken::kw_liveins));
918 lex();
919 if (expectAndConsume(MIToken::colon))
920 return true;
921 if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
922 return false;
923 do {
924 if (Token.isNot(MIToken::NamedRegister))
925 return error("expected a named register");
927 if (parseNamedRegister(Reg))
928 return true;
929 lex();
931 if (consumeIfPresent(MIToken::colon)) {
932 // Parse lane mask.
933 if (Token.isNot(MIToken::IntegerLiteral) &&
934 Token.isNot(MIToken::HexLiteral))
935 return error("expected a lane mask");
936 static_assert(sizeof(LaneBitmask::Type) == sizeof(uint64_t),
937 "Use correct get-function for lane mask");
939 if (getUint64(V))
940 return error("invalid lane mask value");
941 Mask = LaneBitmask(V);
942 lex();
943 }
944 MBB.addLiveIn(Reg, Mask);
945 } while (consumeIfPresent(MIToken::comma));
946 return false;
947}
948
949bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
951 lex();
952 if (expectAndConsume(MIToken::colon))
953 return true;
954 if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
955 return false;
956 do {
957 if (Token.isNot(MIToken::MachineBasicBlock))
958 return error("expected a machine basic block reference");
959 MachineBasicBlock *SuccMBB = nullptr;
960 if (parseMBBReference(SuccMBB))
961 return true;
962 lex();
963 unsigned Weight = 0;
964 if (consumeIfPresent(MIToken::lparen)) {
965 if (Token.isNot(MIToken::IntegerLiteral) &&
966 Token.isNot(MIToken::HexLiteral))
967 return error("expected an integer literal after '('");
968 if (getUnsigned(Weight))
969 return true;
970 lex();
971 if (expectAndConsume(MIToken::rparen))
972 return true;
973 }
975 } while (consumeIfPresent(MIToken::comma));
977 return false;
978}
979
980bool MIParser::parseBasicBlock(MachineBasicBlock &MBB,
981 MachineBasicBlock *&AddFalthroughFrom) {
982 // Skip the definition.
984 lex();
985 if (consumeIfPresent(MIToken::lparen)) {
986 while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
987 lex();
988 consumeIfPresent(MIToken::rparen);
989 }
990 consumeIfPresent(MIToken::colon);
991
992 // Parse the liveins and successors.
993 // N.B: Multiple lists of successors and liveins are allowed and they're
994 // merged into one.
995 // Example:
996 // liveins: $edi
997 // liveins: $esi
998 //
999 // is equivalent to
1000 // liveins: $edi, $esi
1001 bool ExplicitSuccessors = false;
1002 while (true) {
1003 if (Token.is(MIToken::kw_successors)) {
1004 if (parseBasicBlockSuccessors(MBB))
1005 return true;
1006 ExplicitSuccessors = true;
1007 } else if (Token.is(MIToken::kw_liveins)) {
1008 if (parseBasicBlockLiveins(MBB))
1009 return true;
1010 } else if (consumeIfPresent(MIToken::Newline)) {
1011 continue;
1012 } else {
1013 break;
1014 }
1015 if (!Token.isNewlineOrEOF())
1016 return error("expected line break at the end of a list");
1017 lex();
1018 }
1019
1020 // Parse the instructions.
1021 bool IsInBundle = false;
1022 MachineInstr *PrevMI = nullptr;
1023 while (!Token.is(MIToken::MachineBasicBlockLabel) &&
1024 !Token.is(MIToken::Eof)) {
1025 if (consumeIfPresent(MIToken::Newline))
1026 continue;
1027 if (consumeIfPresent(MIToken::rbrace)) {
1028 // The first parsing pass should verify that all closing '}' have an
1029 // opening '{'.
1030 assert(IsInBundle);
1031 IsInBundle = false;
1032 continue;
1033 }
1034 MachineInstr *MI = nullptr;
1035 if (parse(MI))
1036 return true;
1037 MBB.insert(MBB.end(), MI);
1038 if (IsInBundle) {
1040 MI->setFlag(MachineInstr::BundledPred);
1041 }
1042 PrevMI = MI;
1043 if (Token.is(MIToken::lbrace)) {
1044 if (IsInBundle)
1045 return error("nested instruction bundles are not allowed");
1046 lex();
1047 // This instruction is the start of the bundle.
1048 MI->setFlag(MachineInstr::BundledSucc);
1049 IsInBundle = true;
1050 if (!Token.is(MIToken::Newline))
1051 // The next instruction can be on the same line.
1052 continue;
1053 }
1054 assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
1055 lex();
1056 }
1057
1058 // Construct successor list by searching for basic block machine operands.
1059 if (!ExplicitSuccessors) {
1061 bool IsFallthrough;
1062 guessSuccessors(MBB, Successors, IsFallthrough);
1063 for (MachineBasicBlock *Succ : Successors)
1064 MBB.addSuccessor(Succ);
1065
1066 if (IsFallthrough) {
1067 AddFalthroughFrom = &MBB;
1068 } else {
1070 }
1071 }
1072
1073 return false;
1074}
1075
1076bool MIParser::parseBasicBlocks() {
1077 lex();
1078 // Skip until the first machine basic block.
1079 while (Token.is(MIToken::Newline))
1080 lex();
1081 if (Token.isErrorOrEOF())
1082 return Token.isError();
1083 // The first parsing pass should have verified that this token is a MBB label
1084 // in the 'parseBasicBlockDefinitions' method.
1086 MachineBasicBlock *AddFalthroughFrom = nullptr;
1087 do {
1088 MachineBasicBlock *MBB = nullptr;
1090 return true;
1091 if (AddFalthroughFrom) {
1092 if (!AddFalthroughFrom->isSuccessor(MBB))
1093 AddFalthroughFrom->addSuccessor(MBB);
1094 AddFalthroughFrom->normalizeSuccProbs();
1095 AddFalthroughFrom = nullptr;
1096 }
1097 if (parseBasicBlock(*MBB, AddFalthroughFrom))
1098 return true;
1099 // The method 'parseBasicBlock' should parse the whole block until the next
1100 // block or the end of file.
1101 assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
1102 } while (Token.isNot(MIToken::Eof));
1103 return false;
1104}
1105
1106bool MIParser::parse(MachineInstr *&MI) {
1107 // Parse any register operands before '='
1110 while (Token.isRegister() || Token.isRegisterFlag()) {
1111 auto Loc = Token.location();
1112 std::optional<unsigned> TiedDefIdx;
1113 if (parseRegisterOperand(MO, TiedDefIdx, /*IsDef=*/true))
1114 return true;
1115 Operands.push_back(
1116 ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
1117 if (Token.isNot(MIToken::comma))
1118 break;
1119 lex();
1120 }
1121 if (!Operands.empty() && expectAndConsume(MIToken::equal))
1122 return true;
1123
1124 unsigned OpCode, Flags = 0;
1125 if (Token.isError() || parseInstruction(OpCode, Flags))
1126 return true;
1127
1128 // Parse the remaining machine operands.
1129 while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_pre_instr_symbol) &&
1130 Token.isNot(MIToken::kw_post_instr_symbol) &&
1131 Token.isNot(MIToken::kw_heap_alloc_marker) &&
1132 Token.isNot(MIToken::kw_pcsections) && Token.isNot(MIToken::kw_mmra) &&
1133 Token.isNot(MIToken::kw_cfi_type) &&
1134 Token.isNot(MIToken::kw_deactivation_symbol) &&
1135 Token.isNot(MIToken::kw_debug_location) &&
1136 Token.isNot(MIToken::kw_debug_instr_number) &&
1137 Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) {
1138 auto Loc = Token.location();
1139 std::optional<unsigned> TiedDefIdx;
1140 if (parseMachineOperandAndTargetFlags(OpCode, Operands.size(), MO, TiedDefIdx))
1141 return true;
1142 Operands.push_back(
1143 ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
1144 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
1145 Token.is(MIToken::lbrace))
1146 break;
1147 if (Token.isNot(MIToken::comma))
1148 return error("expected ',' before the next machine operand");
1149 lex();
1150 }
1151
1152 MCSymbol *PreInstrSymbol = nullptr;
1153 if (Token.is(MIToken::kw_pre_instr_symbol))
1154 if (parsePreOrPostInstrSymbol(PreInstrSymbol))
1155 return true;
1156 MCSymbol *PostInstrSymbol = nullptr;
1157 if (Token.is(MIToken::kw_post_instr_symbol))
1158 if (parsePreOrPostInstrSymbol(PostInstrSymbol))
1159 return true;
1160 MDNode *HeapAllocMarker = nullptr;
1161 if (Token.is(MIToken::kw_heap_alloc_marker))
1162 if (parseHeapAllocMarker(HeapAllocMarker))
1163 return true;
1164 MDNode *PCSections = nullptr;
1165 if (Token.is(MIToken::kw_pcsections))
1166 if (parsePCSections(PCSections))
1167 return true;
1168 MDNode *MMRA = nullptr;
1169 if (Token.is(MIToken::kw_mmra) && parseMMRA(MMRA))
1170 return true;
1171 unsigned CFIType = 0;
1172 if (Token.is(MIToken::kw_cfi_type)) {
1173 lex();
1174 if (Token.isNot(MIToken::IntegerLiteral))
1175 return error("expected an integer literal after 'cfi-type'");
1176 // getUnsigned is sufficient for 32-bit integers.
1177 if (getUnsigned(CFIType))
1178 return true;
1179 lex();
1180 // Lex past trailing comma if present.
1181 if (Token.is(MIToken::comma))
1182 lex();
1183 }
1184
1185 GlobalValue *DS = nullptr;
1186 if (Token.is(MIToken::kw_deactivation_symbol)) {
1187 lex();
1188 if (parseGlobalValue(DS))
1189 return true;
1190 lex();
1191 }
1192
1193 unsigned InstrNum = 0;
1194 if (Token.is(MIToken::kw_debug_instr_number)) {
1195 lex();
1196 if (Token.isNot(MIToken::IntegerLiteral))
1197 return error("expected an integer literal after 'debug-instr-number'");
1198 if (getUnsigned(InstrNum))
1199 return true;
1200 lex();
1201 // Lex past trailing comma if present.
1202 if (Token.is(MIToken::comma))
1203 lex();
1204 }
1205
1206 DebugLoc DebugLocation;
1207 if (Token.is(MIToken::kw_debug_location)) {
1208 lex();
1209 MDNode *Node = nullptr;
1210 if (Token.is(MIToken::exclaim)) {
1211 if (parseMDNode(Node))
1212 return true;
1213 } else if (Token.is(MIToken::md_dilocation)) {
1214 if (parseDILocation(Node))
1215 return true;
1216 } else {
1217 return error("expected a metadata node after 'debug-location'");
1218 }
1219 DebugLocation = DebugLoc(dyn_cast<DILocation>(Node));
1220 if (!DebugLocation)
1221 return error("referenced metadata is not a DILocation");
1222 }
1223
1224 // Parse the machine memory operands.
1226 if (Token.is(MIToken::coloncolon)) {
1227 lex();
1228 while (!Token.isNewlineOrEOF()) {
1229 MachineMemOperand *MemOp = nullptr;
1230 if (parseMachineMemoryOperand(MemOp))
1231 return true;
1232 MemOperands.push_back(MemOp);
1233 if (Token.isNewlineOrEOF())
1234 break;
1235 if (OpCode == TargetOpcode::BUNDLE && Token.is(MIToken::lbrace))
1236 break;
1237 if (Token.isNot(MIToken::comma))
1238 return error("expected ',' before the next machine memory operand");
1239 lex();
1240 }
1241 }
1242
1243 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
1244 if (!MCID.isVariadic()) {
1245 // FIXME: Move the implicit operand verification to the machine verifier.
1246 if (verifyImplicitOperands(Operands, MCID))
1247 return true;
1248 }
1249
1250 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
1251 MI->setFlags(Flags);
1252
1253 // Don't check the operands make sense, let the verifier catch any
1254 // improprieties.
1255 for (const auto &Operand : Operands)
1256 MI->addOperand(MF, Operand.Operand);
1257
1258 if (assignRegisterTies(*MI, Operands))
1259 return true;
1260 if (PreInstrSymbol)
1261 MI->setPreInstrSymbol(MF, PreInstrSymbol);
1262 if (PostInstrSymbol)
1263 MI->setPostInstrSymbol(MF, PostInstrSymbol);
1264 if (HeapAllocMarker)
1265 MI->setHeapAllocMarker(MF, HeapAllocMarker);
1266 if (PCSections)
1267 MI->setPCSections(MF, PCSections);
1268 if (MMRA)
1269 MI->setMMRAMetadata(MF, MMRA);
1270 if (CFIType)
1271 MI->setCFIType(MF, CFIType);
1272 if (DS)
1273 MI->setDeactivationSymbol(MF, DS);
1274 if (!MemOperands.empty())
1275 MI->setMemRefs(MF, MemOperands);
1276 if (InstrNum)
1277 MI->setDebugInstrNum(InstrNum);
1278 return false;
1279}
1280
1281bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
1282 lex();
1283 if (Token.isNot(MIToken::MachineBasicBlock))
1284 return error("expected a machine basic block reference");
1286 return true;
1287 lex();
1288 if (Token.isNot(MIToken::Eof))
1289 return error(
1290 "expected end of string after the machine basic block reference");
1291 return false;
1292}
1293
1294bool MIParser::parseStandaloneNamedRegister(Register &Reg) {
1295 lex();
1296 if (Token.isNot(MIToken::NamedRegister))
1297 return error("expected a named register");
1298 if (parseNamedRegister(Reg))
1299 return true;
1300 lex();
1301 if (Token.isNot(MIToken::Eof))
1302 return error("expected end of string after the register reference");
1303 return false;
1304}
1305
1306bool MIParser::parseStandaloneVirtualRegister(VRegInfo *&Info) {
1307 lex();
1308 if (Token.isNot(MIToken::VirtualRegister))
1309 return error("expected a virtual register");
1310 if (parseVirtualRegister(Info))
1311 return true;
1312 lex();
1313 if (Token.isNot(MIToken::Eof))
1314 return error("expected end of string after the register reference");
1315 return false;
1316}
1317
1318bool MIParser::parseStandaloneRegister(Register &Reg) {
1319 lex();
1320 if (Token.isNot(MIToken::NamedRegister) &&
1321 Token.isNot(MIToken::VirtualRegister))
1322 return error("expected either a named or virtual register");
1323
1324 VRegInfo *Info;
1325 if (parseRegister(Reg, Info))
1326 return true;
1327
1328 lex();
1329 if (Token.isNot(MIToken::Eof))
1330 return error("expected end of string after the register reference");
1331 return false;
1332}
1333
1334bool MIParser::parseStandaloneStackObject(int &FI) {
1335 lex();
1336 if (Token.isNot(MIToken::StackObject))
1337 return error("expected a stack object");
1338 if (parseStackFrameIndex(FI))
1339 return true;
1340 if (Token.isNot(MIToken::Eof))
1341 return error("expected end of string after the stack object reference");
1342 return false;
1343}
1344
1345bool MIParser::parseStandaloneMDNode(MDNode *&Node) {
1346 lex();
1347 if (Token.is(MIToken::exclaim)) {
1348 if (parseMDNode(Node))
1349 return true;
1350 } else if (Token.is(MIToken::md_diexpr)) {
1351 if (parseDIExpression(Node))
1352 return true;
1353 } else if (Token.is(MIToken::md_dilocation)) {
1354 if (parseDILocation(Node))
1355 return true;
1356 } else {
1357 return error("expected a metadata node");
1358 }
1359 if (Token.isNot(MIToken::Eof))
1360 return error("expected end of string after the metadata node");
1361 return false;
1362}
1363
1364static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
1365 assert(MO.isImplicit());
1366 return MO.isDef() ? "implicit-def" : "implicit";
1367}
1368
1369static std::string getRegisterName(const TargetRegisterInfo *TRI,
1370 Register Reg) {
1371 assert(Reg.isPhysical() && "expected phys reg");
1372 return StringRef(TRI->getName(Reg)).lower();
1373}
1374
1375/// Return true if the parsed machine operands contain a given machine operand.
1376static bool isImplicitOperandIn(const MachineOperand &ImplicitOperand,
1378 for (const auto &I : Operands) {
1379 if (ImplicitOperand.isIdenticalTo(I.Operand))
1380 return true;
1381 }
1382 return false;
1383}
1384
1385bool MIParser::verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
1386 const MCInstrDesc &MCID) {
1387 if (MCID.isCall())
1388 // We can't verify call instructions as they can contain arbitrary implicit
1389 // register and register mask operands.
1390 return false;
1391
1392 // Gather all the expected implicit operands.
1393 SmallVector<MachineOperand, 4> ImplicitOperands;
1394 for (MCPhysReg ImpDef : MCID.implicit_defs())
1395 ImplicitOperands.push_back(MachineOperand::CreateReg(ImpDef, true, true));
1396 for (MCPhysReg ImpUse : MCID.implicit_uses())
1397 ImplicitOperands.push_back(MachineOperand::CreateReg(ImpUse, false, true));
1398
1399 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1400 assert(TRI && "Expected target register info");
1401 for (const auto &I : ImplicitOperands) {
1403 continue;
1404 return error(Operands.empty() ? Token.location() : Operands.back().End,
1405 Twine("missing implicit register operand '") +
1407 getRegisterName(TRI, I.getReg()) + "'");
1408 }
1409 return false;
1410}
1411
1412bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
1413 // Allow frame and fast math flags for OPCODE
1414 // clang-format off
1415 while (Token.is(MIToken::kw_frame_setup) ||
1416 Token.is(MIToken::kw_frame_destroy) ||
1417 Token.is(MIToken::kw_nnan) ||
1418 Token.is(MIToken::kw_ninf) ||
1419 Token.is(MIToken::kw_nsz) ||
1420 Token.is(MIToken::kw_arcp) ||
1421 Token.is(MIToken::kw_contract) ||
1422 Token.is(MIToken::kw_afn) ||
1423 Token.is(MIToken::kw_reassoc) ||
1424 Token.is(MIToken::kw_nuw) ||
1425 Token.is(MIToken::kw_nsw) ||
1426 Token.is(MIToken::kw_exact) ||
1427 Token.is(MIToken::kw_nofpexcept) ||
1428 Token.is(MIToken::kw_noconvergent) ||
1429 Token.is(MIToken::kw_unpredictable) ||
1430 Token.is(MIToken::kw_nneg) ||
1431 Token.is(MIToken::kw_disjoint) ||
1432 Token.is(MIToken::kw_nusw) ||
1433 Token.is(MIToken::kw_samesign) ||
1434 Token.is(MIToken::kw_inbounds) ||
1435 Token.is(MIToken::kw_nonnull) ||
1436 Token.is(MIToken::kw_lr_split)) {
1437 // clang-format on
1438 // Mine frame and fast math flags
1439 if (Token.is(MIToken::kw_frame_setup))
1441 if (Token.is(MIToken::kw_frame_destroy))
1443 if (Token.is(MIToken::kw_nnan))
1445 if (Token.is(MIToken::kw_ninf))
1447 if (Token.is(MIToken::kw_nsz))
1449 if (Token.is(MIToken::kw_arcp))
1451 if (Token.is(MIToken::kw_contract))
1453 if (Token.is(MIToken::kw_afn))
1455 if (Token.is(MIToken::kw_reassoc))
1457 if (Token.is(MIToken::kw_nuw))
1459 if (Token.is(MIToken::kw_nsw))
1461 if (Token.is(MIToken::kw_exact))
1463 if (Token.is(MIToken::kw_nofpexcept))
1465 if (Token.is(MIToken::kw_unpredictable))
1467 if (Token.is(MIToken::kw_noconvergent))
1469 if (Token.is(MIToken::kw_nneg))
1471 if (Token.is(MIToken::kw_disjoint))
1473 if (Token.is(MIToken::kw_nusw))
1475 if (Token.is(MIToken::kw_samesign))
1477 if (Token.is(MIToken::kw_inbounds))
1479 if (Token.is(MIToken::kw_nonnull))
1481 if (Token.is(MIToken::kw_lr_split))
1483
1484 lex();
1485 }
1486 if (Token.isNot(MIToken::Identifier))
1487 return error("expected a machine instruction");
1488 StringRef InstrName = Token.stringValue();
1489 if (PFS.Target.parseInstrName(InstrName, OpCode))
1490 return error(Twine("unknown machine instruction name '") + InstrName + "'");
1491 lex();
1492 return false;
1493}
1494
1495bool MIParser::parseNamedRegister(Register &Reg) {
1496 assert(Token.is(MIToken::NamedRegister) && "Needs NamedRegister token");
1497 StringRef Name = Token.stringValue();
1498 if (PFS.Target.getRegisterByName(Name, Reg))
1499 return error(Twine("unknown register name '") + Name + "'");
1500 return false;
1501}
1502
1503bool MIParser::parseNamedVirtualRegister(VRegInfo *&Info) {
1504 assert(Token.is(MIToken::NamedVirtualRegister) && "Expected NamedVReg token");
1505 StringRef Name = Token.stringValue();
1506 // TODO: Check that the VReg name is not the same as a physical register name.
1507 // If it is, then print a warning (when warnings are implemented).
1508 Info = &PFS.getVRegInfoNamed(Name);
1509 return false;
1510}
1511
1512bool MIParser::parseVirtualRegister(VRegInfo *&Info) {
1513 if (Token.is(MIToken::NamedVirtualRegister))
1514 return parseNamedVirtualRegister(Info);
1515 assert(Token.is(MIToken::VirtualRegister) && "Needs VirtualRegister token");
1516 unsigned ID;
1517 if (getUnsigned(ID))
1518 return true;
1519 Info = &PFS.getVRegInfo(ID);
1520 return false;
1521}
1522
1523bool MIParser::parseRegister(Register &Reg, VRegInfo *&Info) {
1524 switch (Token.kind()) {
1526 Reg = 0;
1527 return false;
1529 return parseNamedRegister(Reg);
1532 if (parseVirtualRegister(Info))
1533 return true;
1534 Reg = Info->VReg;
1535 return false;
1536 // TODO: Parse other register kinds.
1537 default:
1538 llvm_unreachable("The current token should be a register");
1539 }
1540}
1541
1542bool MIParser::parseRegisterClassOrBank(VRegInfo &RegInfo) {
1543 if (Token.isNot(MIToken::Identifier) && Token.isNot(MIToken::underscore))
1544 return error("expected '_', register class, or register bank name");
1545 StringRef::iterator Loc = Token.location();
1546 StringRef Name = Token.stringValue();
1547
1548 // Was it a register class?
1549 const TargetRegisterClass *RC = PFS.Target.getRegClass(Name);
1550 if (RC) {
1551 lex();
1552
1553 switch (RegInfo.Kind) {
1554 case VRegInfo::UNKNOWN:
1555 case VRegInfo::NORMAL:
1556 RegInfo.Kind = VRegInfo::NORMAL;
1557 if (RegInfo.Explicit && RegInfo.D.RC != RC) {
1558 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1559 return error(Loc, Twine("conflicting register classes, previously: ") +
1560 Twine(TRI.getRegClassName(RegInfo.D.RC)));
1561 }
1562 RegInfo.D.RC = RC;
1563 RegInfo.Explicit = true;
1564 return false;
1565
1566 case VRegInfo::GENERIC:
1567 case VRegInfo::REGBANK:
1568 return error(Loc, "register class specification on generic register");
1569 }
1570 llvm_unreachable("Unexpected register kind");
1571 }
1572
1573 // Should be a register bank or a generic register.
1574 const RegisterBank *RegBank = nullptr;
1575 if (Name != "_") {
1576 RegBank = PFS.Target.getRegBank(Name);
1577 if (!RegBank)
1578 return error(Loc, "expected '_', register class, or register bank name");
1579 }
1580
1581 lex();
1582
1583 switch (RegInfo.Kind) {
1584 case VRegInfo::UNKNOWN:
1585 case VRegInfo::GENERIC:
1586 case VRegInfo::REGBANK:
1587 RegInfo.Kind = RegBank ? VRegInfo::REGBANK : VRegInfo::GENERIC;
1588 if (RegInfo.Explicit && RegInfo.D.RegBank != RegBank)
1589 return error(Loc, "conflicting generic register banks");
1590 RegInfo.D.RegBank = RegBank;
1591 RegInfo.Explicit = true;
1592 return false;
1593
1594 case VRegInfo::NORMAL:
1595 return error(Loc, "register bank specification on normal register");
1596 }
1597 llvm_unreachable("Unexpected register kind");
1598}
1599
1600bool MIParser::parseRegisterFlag(RegState &Flags) {
1601 const RegState OldFlags = Flags;
1602 switch (Token.kind()) {
1605 break;
1608 break;
1609 case MIToken::kw_def:
1611 break;
1612 case MIToken::kw_dead:
1614 break;
1615 case MIToken::kw_killed:
1617 break;
1618 case MIToken::kw_undef:
1620 break;
1623 break;
1626 break;
1629 break;
1632 break;
1633 default:
1634 llvm_unreachable("The current token should be a register flag");
1635 }
1636 if (OldFlags == Flags)
1637 // We know that the same flag is specified more than once when the flags
1638 // weren't modified.
1639 return error("duplicate '" + Token.stringValue() + "' register flag");
1640 lex();
1641 return false;
1642}
1643
1644bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
1645 assert(Token.is(MIToken::dot));
1646 lex();
1647 if (Token.isNot(MIToken::Identifier))
1648 return error("expected a subregister index after '.'");
1649 auto Name = Token.stringValue();
1650 SubReg = PFS.Target.getSubRegIndex(Name);
1651 if (!SubReg)
1652 return error(Twine("use of unknown subregister index '") + Name + "'");
1653 lex();
1654 return false;
1655}
1656
1657bool MIParser::parseRegisterTiedDefIndex(unsigned &TiedDefIdx) {
1658 assert(Token.is(MIToken::kw_tied_def));
1659 lex();
1660 if (Token.isNot(MIToken::IntegerLiteral))
1661 return error("expected an integer literal after 'tied-def'");
1662 if (getUnsigned(TiedDefIdx))
1663 return true;
1664 lex();
1665 return expectAndConsume(MIToken::rparen);
1666}
1667
1668bool MIParser::assignRegisterTies(MachineInstr &MI,
1670 SmallVector<std::pair<unsigned, unsigned>, 4> TiedRegisterPairs;
1671 for (unsigned I = 0, E = Operands.size(); I != E; ++I) {
1672 if (!Operands[I].TiedDefIdx)
1673 continue;
1674 // The parser ensures that this operand is a register use, so we just have
1675 // to check the tied-def operand.
1676 unsigned DefIdx = *Operands[I].TiedDefIdx;
1677 if (DefIdx >= E)
1678 return error(Operands[I].Begin,
1679 Twine("use of invalid tied-def operand index '" +
1680 Twine(DefIdx) + "'; instruction has only ") +
1681 Twine(E) + " operands");
1682 const auto &DefOperand = Operands[DefIdx].Operand;
1683 if (!DefOperand.isReg() || !DefOperand.isDef())
1684 // FIXME: add note with the def operand.
1685 return error(Operands[I].Begin,
1686 Twine("use of invalid tied-def operand index '") +
1687 Twine(DefIdx) + "'; the operand #" + Twine(DefIdx) +
1688 " isn't a defined register");
1689 // Check that the tied-def operand wasn't tied elsewhere.
1690 for (const auto &TiedPair : TiedRegisterPairs) {
1691 if (TiedPair.first == DefIdx)
1692 return error(Operands[I].Begin,
1693 Twine("the tied-def operand #") + Twine(DefIdx) +
1694 " is already tied with another register operand");
1695 }
1696 TiedRegisterPairs.push_back(std::make_pair(DefIdx, I));
1697 }
1698 // FIXME: Verify that for non INLINEASM instructions, the def and use tied
1699 // indices must be less than tied max.
1700 for (const auto &TiedPair : TiedRegisterPairs)
1701 MI.tieOperands(TiedPair.first, TiedPair.second);
1702 return false;
1703}
1704
1705bool MIParser::parseRegisterOperand(MachineOperand &Dest,
1706 std::optional<unsigned> &TiedDefIdx,
1707 bool IsDef) {
1708 RegState Flags = getDefRegState(IsDef);
1709 while (Token.isRegisterFlag()) {
1710 if (parseRegisterFlag(Flags))
1711 return true;
1712 }
1713 // Update IsDef as we may have read a def flag.
1714 IsDef = hasRegState(Flags, RegState::Define);
1715 if (!Token.isRegister())
1716 return error("expected a register after register flags");
1717 Register Reg;
1718 VRegInfo *RegInfo;
1719 if (parseRegister(Reg, RegInfo))
1720 return true;
1721 lex();
1722 unsigned SubReg = 0;
1723 if (Token.is(MIToken::dot)) {
1724 if (parseSubRegisterIndex(SubReg))
1725 return true;
1726 if (!Reg.isVirtual())
1727 return error("subregister index expects a virtual register");
1728 }
1729 if (Token.is(MIToken::colon)) {
1730 if (!Reg.isVirtual())
1731 return error("register class specification expects a virtual register");
1732 lex();
1733 if (parseRegisterClassOrBank(*RegInfo))
1734 return true;
1735 }
1736
1737 if (consumeIfPresent(MIToken::lparen)) {
1738 // For a def, we only expect a type. For use we expect either a type or a
1739 // tied-def. Additionally, for physical registers, we don't expect a type.
1740 if (Token.is(MIToken::kw_tied_def)) {
1741 if (IsDef)
1742 return error("tied-def not supported for defs");
1743 unsigned Idx;
1744 if (parseRegisterTiedDefIndex(Idx))
1745 return true;
1746 TiedDefIdx = Idx;
1747 } else {
1748 if (!Reg.isVirtual())
1749 return error("unexpected type on physical register");
1750
1751 LLT Ty;
1752 // If type parsing fails, forwad the parse error for defs.
1753 if (parseLowLevelType(Token.location(), Ty))
1754 return IsDef ? true
1755 : error("expected tied-def or low-level type after '('");
1756
1757 if (expectAndConsume(MIToken::rparen))
1758 return true;
1759
1760 MachineRegisterInfo &MRI = MF.getRegInfo();
1761 if (MRI.getType(Reg).isValid() && MRI.getType(Reg) != Ty)
1762 return error("inconsistent type for generic virtual register");
1763
1764 MRI.setRegClassOrRegBank(Reg, static_cast<RegisterBank *>(nullptr));
1765 MRI.setType(Reg, Ty);
1767 }
1768 } else if (IsDef && Reg.isVirtual()) {
1769 // Generic virtual registers defs must have a type.
1770 if (RegInfo->Kind == VRegInfo::GENERIC ||
1771 RegInfo->Kind == VRegInfo::REGBANK)
1772 return error("generic virtual registers must have a type");
1773 }
1774
1775 if (IsDef) {
1776 if (hasRegState(Flags, RegState::Kill))
1777 return error("cannot have a killed def operand");
1778 } else {
1779 if (hasRegState(Flags, RegState::Dead))
1780 return error("cannot have a dead use operand");
1781 }
1782
1784 Reg, IsDef, hasRegState(Flags, RegState::Implicit),
1787 hasRegState(Flags, RegState::EarlyClobber), SubReg,
1791
1792 return false;
1793}
1794
1795bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
1797 const APSInt &Int = Token.integerValue();
1798 if (auto SImm = Int.trySExtValue(); Int.isSigned() && SImm.has_value())
1799 Dest = MachineOperand::CreateImm(*SImm);
1800 else if (auto UImm = Int.tryZExtValue(); !Int.isSigned() && UImm.has_value())
1801 Dest = MachineOperand::CreateImm(*UImm);
1802 else
1803 return error("integer literal is too large to be an immediate operand");
1804 lex();
1805 return false;
1806}
1807
1808bool MIParser::parseSymbolicInlineAsmOperand(unsigned OpIdx,
1809 MachineOperand &Dest) {
1811 assert(Token.is(MIToken::Identifier) &&
1812 "expected symbolic inline asm operand");
1813
1814 // Parse ExtraInfo flags.
1815 if (OpIdx == InlineAsm::MIOp_ExtraInfo) {
1816 unsigned ExtraInfo = 0;
1817 for (;;) {
1818 if (Token.isNot(MIToken::Identifier))
1819 break;
1820
1821 StringRef FlagName = Token.stringValue();
1822 unsigned Flag = StringSwitch<unsigned>(FlagName)
1824 .Case("mayload", InlineAsm::Extra_MayLoad)
1825 .Case("maystore", InlineAsm::Extra_MayStore)
1826 .Case("isconvergent", InlineAsm::Extra_IsConvergent)
1827 .Case("alignstack", InlineAsm::Extra_IsAlignStack)
1829 .Case("attdialect", 0)
1830 .Case("inteldialect", InlineAsm::Extra_AsmDialect)
1831 .Default(~0u);
1832 if (Flag == ~0u)
1833 return error("unknown inline asm extra info flag '" + FlagName + "'");
1834
1835 ExtraInfo |= Flag;
1836 lex();
1837 }
1838
1839 Dest = MachineOperand::CreateImm(ExtraInfo);
1840 return false;
1841 }
1842
1843 // Parse symbolic form: kind[:constraint].
1844 StringRef KindStr = Token.stringValue();
1845 constexpr auto InvalidKind = static_cast<InlineAsm::Kind>(0);
1848 .Case("regdef", InlineAsm::Kind::RegDef)
1849 .Case("reguse", InlineAsm::Kind::RegUse)
1851 .Case("clobber", InlineAsm::Kind::Clobber)
1852 .Case("imm", InlineAsm::Kind::Imm)
1853 .Case("mem", InlineAsm::Kind::Mem)
1854 .Default(InvalidKind);
1855 if (K == InvalidKind)
1856 return error("unknown inline asm operand kind '" + KindStr + "'");
1857
1858 lex();
1859
1860 // Create the flag with default of 1 operand.
1861 InlineAsm::Flag F(K, 1);
1862
1863 // Parse optional tiedto constraint: tiedto:$N.
1864 if (Token.is(MIToken::Identifier) && Token.stringValue() == "tiedto") {
1865 lex();
1866 if (Token.isNot(MIToken::colon))
1867 return error("expected ':' after 'tiedto'");
1868 lex();
1869 if (Token.isNot(MIToken::NamedRegister))
1870 return error("expected '$N' operand number after 'tiedto:'");
1871 unsigned OperandNo;
1872 if (Token.stringValue().getAsInteger(10, OperandNo))
1873 return error("invalid operand number in tiedto constraint");
1874 lex();
1875
1876 F.setMatchingOp(OperandNo);
1877
1879 return false;
1880 }
1881
1882 // Parse an optional constraint after ':'.
1883 if (Token.is(MIToken::colon)) {
1884 lex();
1885
1886 if (Token.isNot(MIToken::Identifier))
1887 return error(
1888 "expected register class or memory constraint name after ':'");
1889
1890 StringRef ConstraintStr = Token.stringValue();
1891 if (F.isMemKind()) {
1924 return error("unknown memory constraint '" + ConstraintStr + "'");
1925 F.setMemConstraint(CC);
1926 } else if (F.isRegDefKind() || F.isRegUseKind() ||
1927 F.isRegDefEarlyClobberKind()) {
1928 const TargetRegisterClass *RC =
1929 PFS.Target.getRegClass(ConstraintStr.lower());
1930 if (!RC)
1931 return error("unknown register class '" + ConstraintStr + "'");
1932 F.setRegClass(RC->getID());
1933 }
1934
1935 lex();
1936 }
1937
1938 // Parse an optional 'foldable' marker: the register allocator may fold the
1939 // operand's register to a stack slot (see
1940 // InlineAsm::Flag::setRegMayBeFolded()).
1941 if (Token.is(MIToken::Identifier) && Token.stringValue() == "foldable") {
1942 if (!F.isRegDefKind() && !F.isRegUseKind() && !F.isRegDefEarlyClobberKind())
1943 return error("only a register operand can be 'foldable'");
1944
1945 F.setRegMayBeFolded(true);
1946 lex();
1947 }
1948
1950 return false;
1951}
1952
1953bool MIParser::parseTargetImmMnemonic(const unsigned OpCode,
1954 const unsigned OpIdx,
1955 MachineOperand &Dest,
1956 const MIRFormatter &MF) {
1957 assert(Token.is(MIToken::dot));
1958 auto Loc = Token.location(); // record start position
1959 size_t Len = 1; // for "."
1960 lex();
1961
1962 // Handle the case that mnemonic starts with number.
1963 if (Token.is(MIToken::IntegerLiteral)) {
1964 Len += Token.range().size();
1965 lex();
1966 }
1967
1968 StringRef Src;
1969 if (Token.is(MIToken::comma))
1970 Src = StringRef(Loc, Len);
1971 else {
1972 assert(Token.is(MIToken::Identifier));
1973 Src = StringRef(Loc, Len + Token.stringValue().size());
1974 }
1975 int64_t Val;
1976 if (MF.parseImmMnemonic(OpCode, OpIdx, Src, Val,
1977 [this](StringRef::iterator Loc, const Twine &Msg)
1978 -> bool { return error(Loc, Msg); }))
1979 return true;
1980
1981 Dest = MachineOperand::CreateImm(Val);
1982 if (!Token.is(MIToken::comma))
1983 lex();
1984 return false;
1985}
1986
1988 PerFunctionMIParsingState &PFS, const Constant *&C,
1989 ErrorCallbackType ErrCB) {
1990 auto Source = StringValue.str(); // The source has to be null terminated.
1991 SMDiagnostic Err;
1992 C = parseConstantValue(Source, Err, *PFS.MF.getFunction().getParent(),
1993 &PFS.IRSlots);
1994 if (!C)
1995 return ErrCB(Loc + Err.getColumnNo(), Err.getMessage());
1996 return false;
1997}
1998
1999bool MIParser::parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
2000 const Constant *&C) {
2001 return ::parseIRConstant(
2002 Loc, StringValue, PFS, C,
2003 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2004 return error(Loc, Msg);
2005 });
2006}
2007
2008bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
2009 if (parseIRConstant(Loc, StringRef(Loc, Token.range().end() - Loc), C))
2010 return true;
2011 lex();
2012 return false;
2013}
2014
2015// See LLT implementation for bit size limits.
2017 return Size != 0 && isUInt<16>(Size);
2018}
2019
2020static bool verifyVectorElementCount(uint64_t NumElts, bool HasVScale) {
2021 // A fixed-length vector needs at least two elements.
2022 return NumElts != 0 && (HasVScale || NumElts != 1) && isUInt<16>(NumElts);
2023}
2024
2025static bool verifyAddrSpace(uint64_t AddrSpace) {
2026 return isUInt<24>(AddrSpace);
2027}
2028
2029bool MIParser::parseLowLevelType(StringRef::iterator Loc, LLT &Ty) {
2030 StringRef TypeDigits = Token.range();
2031 if (TypeDigits.consume_front("s") || TypeDigits.consume_front("i") ||
2032 TypeDigits.consume_front("f") || TypeDigits.consume_front("p") ||
2033 TypeDigits.consume_front("bf")) {
2034 if (TypeDigits.empty() || !llvm::all_of(TypeDigits, isdigit))
2035 return error(
2036 "expected integers after 's'/'i'/'f'/'bf'/'p' type identifier");
2037 }
2038
2039 bool Scalar = Token.range().starts_with("s");
2040 if (Scalar || Token.range().starts_with("i")) {
2041 auto ScalarSize = APSInt(TypeDigits).getZExtValue();
2042 if (!ScalarSize) {
2043 Ty = LLT::token();
2044 lex();
2045 return false;
2046 }
2047
2048 if (!verifyScalarSize(ScalarSize))
2049 return error("invalid size for scalar type");
2050
2051 Ty = Scalar ? LLT::scalar(ScalarSize) : LLT::integer(ScalarSize);
2052 lex();
2053 return false;
2054 }
2055
2056 if (Token.range().starts_with("p")) {
2057 const DataLayout &DL = MF.getDataLayout();
2058 uint64_t AS = APSInt(TypeDigits).getZExtValue();
2059 if (!verifyAddrSpace(AS))
2060 return error("invalid address space number");
2061
2062 Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
2063 lex();
2064 return false;
2065 }
2066
2067 if (Token.range().starts_with("f") || Token.range().starts_with("bf")) {
2068 auto ScalarSize = APSInt(TypeDigits).getZExtValue();
2069 if (!ScalarSize || !verifyScalarSize(ScalarSize))
2070 return error("invalid size for scalar type");
2071
2072 if (Token.range().starts_with("bf") && ScalarSize != 16)
2073 return error("invalid size for bfloat");
2074
2075 Ty = Token.range().starts_with("bf") ? LLT::bfloat16()
2076 : LLT::floatIEEE(ScalarSize);
2077 lex();
2078 return false;
2079 }
2080
2081 // Now we're looking for a vector.
2082 if (Token.isNot(MIToken::less))
2083 return error(Loc, "expected tN, pA, <M x tN>, <M x pA>, <vscale x M x tN>, "
2084 "or <vscale x M x pA> for GlobalISel type, "
2085 "where t = {'s', 'i', 'f', 'bf'}");
2086 lex();
2087
2088 bool HasVScale =
2089 Token.is(MIToken::Identifier) && Token.stringValue() == "vscale";
2090 if (HasVScale) {
2091 lex();
2092 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
2093 return error(
2094 "expected <vscale x M x tN>, where t = {'s', 'i', 'f', 'bf', 'p'}");
2095 lex();
2096 }
2097
2098 auto GetError = [this, &HasVScale, Loc]() {
2099 if (HasVScale)
2100 return error(Loc, "expected <vscale x M x tN> for vector type, where t = "
2101 "{'s', 'i', 'f', 'bf', 'p'}");
2102 return error(Loc, "expected <M x tN> for vector type, where t = {'s', 'i', "
2103 "'f', 'bf', 'p'}");
2104 };
2105
2106 if (Token.isNot(MIToken::IntegerLiteral))
2107 return GetError();
2108 uint64_t NumElements = Token.integerValue().getZExtValue();
2109 if (!verifyVectorElementCount(NumElements, HasVScale))
2110 return error("invalid number of vector elements");
2111
2112 lex();
2113
2114 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
2115 return GetError();
2116 lex();
2117
2118 StringRef VectorTyDigits = Token.range();
2119 if (!VectorTyDigits.consume_front("s") &&
2120 !VectorTyDigits.consume_front("i") &&
2121 !VectorTyDigits.consume_front("f") &&
2122 !VectorTyDigits.consume_front("p") && !VectorTyDigits.consume_front("bf"))
2123 return GetError();
2124
2125 if (VectorTyDigits.empty() || !llvm::all_of(VectorTyDigits, isdigit))
2126 return error(
2127 "expected integers after 's'/'i'/'f'/'bf'/'p' type identifier");
2128
2129 Scalar = Token.range().starts_with("s");
2130 if (Scalar || Token.range().starts_with("i")) {
2131 auto ScalarSize = APSInt(VectorTyDigits).getZExtValue();
2132 if (!verifyScalarSize(ScalarSize))
2133 return error("invalid size for scalar element in vector");
2134 Ty = Scalar ? LLT::scalar(ScalarSize) : LLT::integer(ScalarSize);
2135 } else if (Token.range().starts_with("p")) {
2136 const DataLayout &DL = MF.getDataLayout();
2137 uint64_t AS = APSInt(VectorTyDigits).getZExtValue();
2138 if (!verifyAddrSpace(AS))
2139 return error("invalid address space number");
2140
2141 Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
2142 } else if (Token.range().starts_with("f")) {
2143 auto ScalarSize = APSInt(VectorTyDigits).getZExtValue();
2144 if (!verifyScalarSize(ScalarSize))
2145 return error("invalid size for float element in vector");
2146 Ty = LLT::floatIEEE(ScalarSize);
2147 } else if (Token.range().starts_with("bf")) {
2148 auto ScalarSize = APSInt(VectorTyDigits).getZExtValue();
2149 if (!verifyScalarSize(ScalarSize))
2150 return error("invalid size for bfloat element in vector");
2151 Ty = LLT::bfloat16();
2152 } else {
2153 return GetError();
2154 }
2155 lex();
2156
2157 if (Token.isNot(MIToken::greater))
2158 return GetError();
2159
2160 lex();
2161
2162 Ty = LLT::vector(ElementCount::get(NumElements, HasVScale), Ty);
2163 return false;
2164}
2165
2166bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
2167 assert(Token.is(MIToken::Identifier));
2168 StringRef TypeDigits = Token.range();
2169 if (!TypeDigits.consume_front("i") && !TypeDigits.consume_front("s") &&
2170 !TypeDigits.consume_front("p") && !TypeDigits.consume_front("f") &&
2171 !TypeDigits.consume_front("bf"))
2172 return error("a typed immediate operand should start with one of 'i', "
2173 "'s', 'f', 'bf', or 'p'");
2174 if (TypeDigits.empty() || !llvm::all_of(TypeDigits, isdigit))
2175 return error(
2176 "expected integers after 'i'/'s'/'f'/'bf'/'p' type identifier");
2177
2178 auto Loc = Token.location();
2179 lex();
2180 if (Token.isNot(MIToken::IntegerLiteral)) {
2181 if (Token.isNot(MIToken::Identifier) ||
2182 !(Token.range() == "true" || Token.range() == "false"))
2183 return error("expected an integer literal");
2184 }
2185 const Constant *C = nullptr;
2186 if (parseIRConstant(Loc, C))
2187 return true;
2189 return false;
2190}
2191
2192bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
2193 auto Loc = Token.location();
2194 lex();
2195 if (Token.isNot(MIToken::FloatingPointLiteral) &&
2196 Token.isNot(MIToken::HexLiteral))
2197 return error("expected a floating point literal");
2198 const Constant *C = nullptr;
2199 if (parseIRConstant(Loc, C))
2200 return true;
2202 return false;
2203}
2204
2205static bool getHexUint(const MIToken &Token, APInt &Result) {
2207 StringRef S = Token.range();
2208 assert(S[0] == '0' && tolower(S[1]) == 'x');
2209 // This could be a floating point literal with a special prefix.
2210 if (!isxdigit(S[2]))
2211 return true;
2212 StringRef V = S.substr(2);
2213 APInt A(V.size()*4, V, 16);
2214
2215 // If A is 0, then A.getActiveBits() is 0. This isn't a valid bitwidth. Make
2216 // sure it isn't the case before constructing result.
2217 unsigned NumBits = (A == 0) ? 32 : A.getActiveBits();
2218 Result = APInt(NumBits, ArrayRef<uint64_t>(A.getRawData(), A.getNumWords()));
2219 return false;
2220}
2221
2222static bool getUnsigned(const MIToken &Token, unsigned &Result,
2223 ErrorCallbackType ErrCB) {
2224 if (Token.hasIntegerValue()) {
2225 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
2226 const APSInt &SInt = Token.integerValue();
2227 if (SInt.isNegative())
2228 return ErrCB(Token.location(), "expected unsigned integer");
2229 uint64_t Val64 = SInt.getLimitedValue(Limit);
2230 if (Val64 == Limit)
2231 return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2232 Result = Val64;
2233 return false;
2234 }
2235 if (Token.is(MIToken::HexLiteral)) {
2236 APInt A;
2237 if (getHexUint(Token, A))
2238 return true;
2239 if (A.getBitWidth() > 32)
2240 return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2241 Result = A.getZExtValue();
2242 return false;
2243 }
2244 return true;
2245}
2246
2247bool MIParser::getUnsigned(unsigned &Result) {
2248 return ::getUnsigned(
2249 Token, Result, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2250 return error(Loc, Msg);
2251 });
2252}
2253
2254bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
2257 unsigned Number;
2258 if (getUnsigned(Number))
2259 return true;
2260 auto MBBInfo = PFS.MBBSlots.find(Number);
2261 if (MBBInfo == PFS.MBBSlots.end())
2262 return error(Twine("use of undefined machine basic block #") +
2263 Twine(Number));
2264 MBB = MBBInfo->second;
2265 // TODO: Only parse the name if it's a MachineBasicBlockLabel. Deprecate once
2266 // we drop the <irname> from the bb.<id>.<irname> format.
2267 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
2268 return error(Twine("the name of machine basic block #") + Twine(Number) +
2269 " isn't '" + Token.stringValue() + "'");
2270 return false;
2271}
2272
2273bool MIParser::parseMBBOperand(MachineOperand &Dest) {
2276 return true;
2278 lex();
2279 return false;
2280}
2281
2282bool MIParser::parseStackFrameIndex(int &FI) {
2283 assert(Token.is(MIToken::StackObject));
2284 unsigned ID;
2285 if (getUnsigned(ID))
2286 return true;
2287 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
2288 if (ObjectInfo == PFS.StackObjectSlots.end())
2289 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
2290 "'");
2292 if (const auto *Alloca =
2293 MF.getFrameInfo().getObjectAllocation(ObjectInfo->second))
2294 Name = Alloca->getName();
2295 if (!Token.stringValue().empty() && Token.stringValue() != Name)
2296 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
2297 "' isn't '" + Token.stringValue() + "'");
2298 lex();
2299 FI = ObjectInfo->second;
2300 return false;
2301}
2302
2303bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
2304 int FI;
2305 if (parseStackFrameIndex(FI))
2306 return true;
2307 Dest = MachineOperand::CreateFI(FI);
2308 return false;
2309}
2310
2311bool MIParser::parseFixedStackFrameIndex(int &FI) {
2313 unsigned ID;
2314 if (getUnsigned(ID))
2315 return true;
2316 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
2317 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
2318 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
2319 Twine(ID) + "'");
2320 lex();
2321 FI = ObjectInfo->second;
2322 return false;
2323}
2324
2325bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
2326 int FI;
2327 if (parseFixedStackFrameIndex(FI))
2328 return true;
2329 Dest = MachineOperand::CreateFI(FI);
2330 return false;
2331}
2332
2333static bool parseGlobalValue(const MIToken &Token,
2335 ErrorCallbackType ErrCB) {
2336 switch (Token.kind()) {
2338 const Module *M = PFS.MF.getFunction().getParent();
2339 GV = M->getNamedValue(Token.stringValue());
2340 if (!GV)
2341 return ErrCB(Token.location(), Twine("use of undefined global value '") +
2342 Token.range() + "'");
2343 break;
2344 }
2345 case MIToken::GlobalValue: {
2346 unsigned GVIdx;
2347 if (getUnsigned(Token, GVIdx, ErrCB))
2348 return true;
2349 GV = PFS.IRSlots.GlobalValues.get(GVIdx);
2350 if (!GV)
2351 return ErrCB(Token.location(), Twine("use of undefined global value '@") +
2352 Twine(GVIdx) + "'");
2353 break;
2354 }
2355 default:
2356 llvm_unreachable("The current token should be a global value");
2357 }
2358 return false;
2359}
2360
2361bool MIParser::parseGlobalValue(GlobalValue *&GV) {
2362 return ::parseGlobalValue(
2363 Token, PFS, GV,
2364 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2365 return error(Loc, Msg);
2366 });
2367}
2368
2369bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
2370 GlobalValue *GV = nullptr;
2371 if (parseGlobalValue(GV))
2372 return true;
2373 lex();
2374 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
2375 if (parseOperandsOffset(Dest))
2376 return true;
2377 return false;
2378}
2379
2380bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
2382 unsigned ID;
2383 if (getUnsigned(ID))
2384 return true;
2385 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
2386 if (ConstantInfo == PFS.ConstantPoolSlots.end())
2387 return error("use of undefined constant '%const." + Twine(ID) + "'");
2388 lex();
2389 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
2390 if (parseOperandsOffset(Dest))
2391 return true;
2392 return false;
2393}
2394
2395bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
2397 unsigned ID;
2398 if (getUnsigned(ID))
2399 return true;
2400 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
2401 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
2402 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
2403 lex();
2404 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
2405 return false;
2406}
2407
2408bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
2410 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
2411 lex();
2412 Dest = MachineOperand::CreateES(Symbol);
2413 if (parseOperandsOffset(Dest))
2414 return true;
2415 return false;
2416}
2417
2418bool MIParser::parseMCSymbolOperand(MachineOperand &Dest) {
2419 assert(Token.is(MIToken::MCSymbol));
2420 MCSymbol *Symbol = getOrCreateMCSymbol(Token.stringValue());
2421 lex();
2422 Dest = MachineOperand::CreateMCSymbol(Symbol);
2423 if (parseOperandsOffset(Dest))
2424 return true;
2425 return false;
2426}
2427
2428bool MIParser::parseSubRegisterIndexOperand(MachineOperand &Dest) {
2430 StringRef Name = Token.stringValue();
2431 unsigned SubRegIndex = PFS.Target.getSubRegIndex(Token.stringValue());
2432 if (SubRegIndex == 0)
2433 return error(Twine("unknown subregister index '") + Name + "'");
2434 lex();
2435 Dest = MachineOperand::CreateImm(SubRegIndex);
2436 return false;
2437}
2438
2439bool MIParser::parseMDNode(MDNode *&Node) {
2440 assert(Token.is(MIToken::exclaim));
2441
2442 auto Loc = Token.location();
2443 lex();
2444 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
2445 return error("expected metadata id after '!'");
2446 unsigned ID;
2447 if (getUnsigned(ID))
2448 return true;
2449 auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID);
2450 if (NodeInfo == PFS.IRSlots.MetadataNodes.end()) {
2451 NodeInfo = PFS.MachineMetadataNodes.find(ID);
2452 if (NodeInfo == PFS.MachineMetadataNodes.end())
2453 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
2454 }
2455 lex();
2456 Node = NodeInfo->second.get();
2457 return false;
2458}
2459
2460bool MIParser::parseDIExpression(MDNode *&Expr) {
2461 unsigned Read;
2463 CurrentSource, Read, Error, *PFS.MF.getFunction().getParent(),
2464 &PFS.IRSlots);
2465 CurrentSource = CurrentSource.substr(Read);
2466 lex();
2467 if (!Expr)
2468 return error(Error.getMessage());
2469 return false;
2470}
2471
2472bool MIParser::parseDILocation(MDNode *&Loc) {
2473 assert(Token.is(MIToken::md_dilocation));
2474 lex();
2475
2476 bool HaveLine = false;
2477 unsigned Line = 0;
2478 unsigned Column = 0;
2479 MDNode *Scope = nullptr;
2480 MDNode *InlinedAt = nullptr;
2481 bool ImplicitCode = false;
2482 uint64_t AtomGroup = 0;
2483 uint64_t AtomRank = 0;
2484 MDNode *IRLayers = nullptr;
2485
2486 if (expectAndConsume(MIToken::lparen))
2487 return true;
2488
2489 if (Token.isNot(MIToken::rparen)) {
2490 do {
2491 if (Token.is(MIToken::Identifier)) {
2492 if (Token.stringValue() == "line") {
2493 lex();
2494 if (expectAndConsume(MIToken::colon))
2495 return true;
2496 if (Token.isNot(MIToken::IntegerLiteral) ||
2497 Token.integerValue().isSigned())
2498 return error("expected unsigned integer");
2499 Line = Token.integerValue().getZExtValue();
2500 HaveLine = true;
2501 lex();
2502 continue;
2503 }
2504 if (Token.stringValue() == "column") {
2505 lex();
2506 if (expectAndConsume(MIToken::colon))
2507 return true;
2508 if (Token.isNot(MIToken::IntegerLiteral) ||
2509 Token.integerValue().isSigned())
2510 return error("expected unsigned integer");
2511 Column = Token.integerValue().getZExtValue();
2512 lex();
2513 continue;
2514 }
2515 if (Token.stringValue() == "scope") {
2516 lex();
2517 if (expectAndConsume(MIToken::colon))
2518 return true;
2519 if (parseMDNode(Scope))
2520 return error("expected metadata node");
2521 if (!isa<DIScope>(Scope))
2522 return error("expected DIScope node");
2523 continue;
2524 }
2525 if (Token.stringValue() == "inlinedAt") {
2526 lex();
2527 if (expectAndConsume(MIToken::colon))
2528 return true;
2529 if (Token.is(MIToken::exclaim)) {
2530 if (parseMDNode(InlinedAt))
2531 return true;
2532 } else if (Token.is(MIToken::md_dilocation)) {
2533 if (parseDILocation(InlinedAt))
2534 return true;
2535 } else {
2536 return error("expected metadata node");
2537 }
2538 if (!isa<DILocation>(InlinedAt))
2539 return error("expected DILocation node");
2540 continue;
2541 }
2542 if (Token.stringValue() == "isImplicitCode") {
2543 lex();
2544 if (expectAndConsume(MIToken::colon))
2545 return true;
2546 if (!Token.is(MIToken::Identifier))
2547 return error("expected true/false");
2548 // As far as I can see, we don't have any existing need for parsing
2549 // true/false in MIR yet. Do it ad-hoc until there's something else
2550 // that needs it.
2551 if (Token.stringValue() == "true")
2552 ImplicitCode = true;
2553 else if (Token.stringValue() == "false")
2554 ImplicitCode = false;
2555 else
2556 return error("expected true/false");
2557 lex();
2558 continue;
2559 }
2560 if (Token.stringValue() == "atomGroup") {
2561 lex();
2562 if (expectAndConsume(MIToken::colon))
2563 return true;
2564 if (Token.isNot(MIToken::IntegerLiteral) ||
2565 Token.integerValue().isSigned())
2566 return error("expected unsigned integer");
2567 AtomGroup = Token.integerValue().getZExtValue();
2568 lex();
2569 continue;
2570 }
2571 if (Token.stringValue() == "atomRank") {
2572 lex();
2573 if (expectAndConsume(MIToken::colon))
2574 return true;
2575 if (Token.isNot(MIToken::IntegerLiteral) ||
2576 Token.integerValue().isSigned())
2577 return error("expected unsigned integer");
2578 AtomRank = Token.integerValue().getZExtValue();
2579 lex();
2580 continue;
2581 }
2582 if (Token.stringValue() == "irlayers") {
2583 lex();
2584 if (expectAndConsume(MIToken::colon))
2585 return true;
2586 if (parseMDNode(IRLayers))
2587 return error("expected metadata node");
2588 if (!isa<DILayerLocList>(IRLayers))
2589 return error("expected DILayerLocList node");
2590 continue;
2591 }
2592 }
2593 return error(Twine("invalid DILocation argument '") +
2594 Token.stringValue() + "'");
2595 } while (consumeIfPresent(MIToken::comma));
2596 }
2597
2598 if (expectAndConsume(MIToken::rparen))
2599 return true;
2600
2601 if (!HaveLine)
2602 return error("DILocation requires line number");
2603 if (!Scope)
2604 return error("DILocation requires a scope");
2605
2606 Loc = DILocation::get(MF.getFunction().getContext(), Line, Column, Scope,
2607 InlinedAt, ImplicitCode, AtomGroup, AtomRank, IRLayers);
2608 return false;
2609}
2610
2611bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
2612 MDNode *Node = nullptr;
2613 if (Token.is(MIToken::exclaim)) {
2614 if (parseMDNode(Node))
2615 return true;
2616 } else if (Token.is(MIToken::md_diexpr)) {
2617 if (parseDIExpression(Node))
2618 return true;
2619 }
2620 Dest = MachineOperand::CreateMetadata(Node);
2621 return false;
2622}
2623
2624bool MIParser::parseCFIOffset(int64_t &Offset) {
2625 if (Token.isNot(MIToken::IntegerLiteral))
2626 return error("expected a cfi offset");
2627 if (!Token.integerValue().isRepresentableByInt64())
2628 return error("expected a 64 bit integer (the cfi offset is too large)");
2629 Offset = Token.integerValue().getExtValue();
2630 lex();
2631 return false;
2632}
2633
2634bool MIParser::parseCFIUnsigned(unsigned &Value) {
2635 if (getUnsigned(Value))
2636 return true;
2637 lex();
2638 return false;
2639}
2640
2641bool MIParser::parseCFIRegister(unsigned &Reg) {
2642 if (Token.isNot(MIToken::NamedRegister))
2643 return error("expected a cfi register");
2644 Register LLVMReg;
2645 if (parseNamedRegister(LLVMReg))
2646 return true;
2647 const auto *TRI = MF.getSubtarget().getRegisterInfo();
2648 assert(TRI && "Expected target register info");
2649 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
2650 if (DwarfReg < 0)
2651 return error("invalid DWARF register");
2652 Reg = (unsigned)DwarfReg;
2653 lex();
2654 return false;
2655}
2656
2657bool MIParser::parseCFIAddressSpace(unsigned &AddressSpace) {
2658 if (Token.isNot(MIToken::IntegerLiteral))
2659 return error("expected a cfi address space literal");
2660 return parseCFIUnsigned(AddressSpace);
2661}
2662
2663bool MIParser::parseCFIEscapeValues(std::string &Values) {
2664 do {
2665 if (Token.isNot(MIToken::HexLiteral))
2666 return error("expected a hexadecimal literal");
2667 unsigned Value;
2668 if (getUnsigned(Value))
2669 return true;
2670 if (Value > UINT8_MAX)
2671 return error("expected a 8-bit integer (too large)");
2672 Values.push_back(static_cast<uint8_t>(Value));
2673 lex();
2674 } while (consumeIfPresent(MIToken::comma));
2675 return false;
2676}
2677
2678bool MIParser::parseCFIOperand(MachineOperand &Dest) {
2679 auto Kind = Token.kind();
2680 lex();
2681 int64_t Offset;
2682 unsigned Reg;
2683 unsigned AddressSpace;
2684 unsigned CFIIndex;
2685 switch (Kind) {
2687 if (parseCFIRegister(Reg))
2688 return true;
2689 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
2690 break;
2692 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2693 parseCFIOffset(Offset))
2694 return true;
2695 CFIIndex =
2696 MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
2697 break;
2699 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2700 parseCFIOffset(Offset))
2701 return true;
2702 CFIIndex = MF.addFrameInst(
2704 break;
2706 if (parseCFIRegister(Reg))
2707 return true;
2708 CFIIndex =
2709 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
2710 break;
2712 if (parseCFIOffset(Offset))
2713 return true;
2714 CFIIndex =
2715 MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, Offset));
2716 break;
2718 if (parseCFIOffset(Offset))
2719 return true;
2720 CFIIndex = MF.addFrameInst(
2722 break;
2724 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2725 parseCFIOffset(Offset))
2726 return true;
2727 CFIIndex =
2728 MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, Offset));
2729 break;
2731 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2732 parseCFIOffset(Offset) || expectAndConsume(MIToken::comma) ||
2733 parseCFIAddressSpace(AddressSpace))
2734 return true;
2735 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMDefAspaceCfa(
2736 nullptr, Reg, Offset, AddressSpace, SMLoc()));
2737 break;
2739 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRememberState(nullptr));
2740 break;
2742 if (parseCFIRegister(Reg))
2743 return true;
2744 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, Reg));
2745 break;
2747 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestoreState(nullptr));
2748 break;
2750 if (parseCFIRegister(Reg))
2751 return true;
2752 CFIIndex = MF.addFrameInst(MCCFIInstruction::createUndefined(nullptr, Reg));
2753 break;
2755 unsigned Reg2;
2756 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2757 parseCFIRegister(Reg2))
2758 return true;
2759
2760 CFIIndex =
2761 MF.addFrameInst(MCCFIInstruction::createRegister(nullptr, Reg, Reg2));
2762 break;
2763 }
2765 CFIIndex = MF.addFrameInst(MCCFIInstruction::createWindowSave(nullptr));
2766 break;
2768 CFIIndex = MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
2769 break;
2771 CFIIndex =
2772 MF.addFrameInst(MCCFIInstruction::createNegateRAStateWithPC(nullptr));
2773 break;
2775 unsigned State;
2776 MCSymbol *PACSym = nullptr;
2777 if (parseCFIUnsigned(State) || expectAndConsume(MIToken::comma))
2778 return true;
2779 if (Token.is(MIToken::MCSymbol)) {
2780 PACSym = getOrCreateMCSymbol(Token.stringValue());
2781 lex();
2782 CFIIndex = MF.addFrameInst(
2783 MCCFIInstruction::createSetRAState(nullptr, State, PACSym));
2784 } else if (Token.is(MIToken::IntegerLiteral)) {
2785 int64_t Offset;
2786 if (parseCFIOffset(Offset))
2787 return true;
2788 CFIIndex = MF.addFrameInst(
2790 } else {
2791 return error("expected '<mcsymbol ...>' or integer offset for "
2792 "cfi_set_ra_state");
2793 }
2794 break;
2795 }
2797 unsigned Reg, R1, R2;
2798 unsigned R1Size, R2Size;
2799 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2800 parseCFIRegister(R1) || expectAndConsume(MIToken::comma) ||
2801 parseCFIUnsigned(R1Size) || expectAndConsume(MIToken::comma) ||
2802 parseCFIRegister(R2) || expectAndConsume(MIToken::comma) ||
2803 parseCFIUnsigned(R2Size))
2804 return true;
2805
2806 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMRegisterPair(
2807 nullptr, Reg, R1, R1Size, R2, R2Size));
2808 break;
2809 }
2811 std::vector<MCCFIInstruction::VectorRegisterWithLane> VectorRegisters;
2812 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma))
2813 return true;
2814 do {
2815 unsigned VR;
2816 unsigned Lane, Size;
2817 if (parseCFIRegister(VR) || expectAndConsume(MIToken::comma) ||
2818 parseCFIUnsigned(Lane) || expectAndConsume(MIToken::comma) ||
2819 parseCFIUnsigned(Size))
2820 return true;
2821 VectorRegisters.push_back({VR, Lane, Size});
2822 } while (consumeIfPresent(MIToken::comma));
2823
2824 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMVectorRegisters(
2825 nullptr, Reg, std::move(VectorRegisters)));
2826 break;
2827 }
2829 unsigned Reg, MaskReg;
2830 unsigned RegSize, MaskRegSize;
2831 int64_t Offset = 0;
2832
2833 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2834 parseCFIUnsigned(RegSize) || expectAndConsume(MIToken::comma) ||
2835 parseCFIRegister(MaskReg) || expectAndConsume(MIToken::comma) ||
2836 parseCFIUnsigned(MaskRegSize) || expectAndConsume(MIToken::comma) ||
2837 parseCFIOffset(Offset))
2838 return true;
2839
2840 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMVectorOffset(
2841 nullptr, Reg, RegSize, MaskReg, MaskRegSize, Offset));
2842 break;
2843 }
2845 unsigned Reg, SpillReg, MaskReg;
2846 unsigned SpillRegLaneSize, MaskRegSize;
2847
2848 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2849 parseCFIRegister(SpillReg) || expectAndConsume(MIToken::comma) ||
2850 parseCFIUnsigned(SpillRegLaneSize) ||
2851 expectAndConsume(MIToken::comma) || parseCFIRegister(MaskReg) ||
2852 expectAndConsume(MIToken::comma) || parseCFIUnsigned(MaskRegSize))
2853 return true;
2854
2855 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMVectorRegisterMask(
2856 nullptr, Reg, SpillReg, SpillRegLaneSize, MaskReg, MaskRegSize));
2857 break;
2858 }
2860 std::string Values;
2861 if (parseCFIEscapeValues(Values))
2862 return true;
2863 CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(nullptr, Values));
2864 break;
2865 }
2866 default:
2867 // TODO: Parse the other CFI operands.
2868 llvm_unreachable("The current token should be a cfi operand");
2869 }
2870 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
2871 return false;
2872}
2873
2874bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
2875 switch (Token.kind()) {
2876 case MIToken::NamedIRBlock: {
2878 F.getValueSymbolTable()->lookup(Token.stringValue()));
2879 if (!BB)
2880 return error(Twine("use of undefined IR block '") + Token.range() + "'");
2881 break;
2882 }
2883 case MIToken::IRBlock: {
2884 unsigned SlotNumber = 0;
2885 if (getUnsigned(SlotNumber))
2886 return true;
2887 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
2888 if (!BB)
2889 return error(Twine("use of undefined IR block '%ir-block.") +
2890 Twine(SlotNumber) + "'");
2891 break;
2892 }
2893 default:
2894 llvm_unreachable("The current token should be an IR block reference");
2895 }
2896 return false;
2897}
2898
2899bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
2901 lex();
2902 if (expectAndConsume(MIToken::lparen))
2903 return true;
2904 if (Token.isNot(MIToken::GlobalValue) &&
2905 Token.isNot(MIToken::NamedGlobalValue))
2906 return error("expected a global value");
2907 GlobalValue *GV = nullptr;
2908 if (parseGlobalValue(GV))
2909 return true;
2910 auto *F = dyn_cast<Function>(GV);
2911 if (!F)
2912 return error("expected an IR function reference");
2913 lex();
2914 if (expectAndConsume(MIToken::comma))
2915 return true;
2916 BasicBlock *BB = nullptr;
2917 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
2918 return error("expected an IR block reference");
2919 if (parseIRBlock(BB, *F))
2920 return true;
2921 lex();
2922 if (expectAndConsume(MIToken::rparen))
2923 return true;
2924 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
2925 if (parseOperandsOffset(Dest))
2926 return true;
2927 return false;
2928}
2929
2930bool MIParser::parseIntrinsicOperand(MachineOperand &Dest) {
2931 assert(Token.is(MIToken::kw_intrinsic));
2932 lex();
2933 if (expectAndConsume(MIToken::lparen))
2934 return error("expected syntax intrinsic(@llvm.whatever)");
2935
2936 if (Token.isNot(MIToken::NamedGlobalValue))
2937 return error("expected syntax intrinsic(@llvm.whatever)");
2938
2939 std::string Name = std::string(Token.stringValue());
2940 lex();
2941
2942 if (expectAndConsume(MIToken::rparen))
2943 return error("expected ')' to terminate intrinsic name");
2944
2945 // Find out what intrinsic we're dealing with.
2947 if (ID == Intrinsic::not_intrinsic)
2948 return error("unknown intrinsic name");
2950
2951 return false;
2952}
2953
2954bool MIParser::parsePredicateOperand(MachineOperand &Dest) {
2955 assert(Token.is(MIToken::kw_intpred) || Token.is(MIToken::kw_floatpred));
2956 bool IsFloat = Token.is(MIToken::kw_floatpred);
2957 lex();
2958
2959 if (expectAndConsume(MIToken::lparen))
2960 return error("expected syntax intpred(whatever) or floatpred(whatever");
2961
2962 if (Token.isNot(MIToken::Identifier))
2963 return error("whatever");
2964
2966 if (IsFloat) {
2967 Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2968 .Case("false", CmpInst::FCMP_FALSE)
2969 .Case("oeq", CmpInst::FCMP_OEQ)
2970 .Case("ogt", CmpInst::FCMP_OGT)
2971 .Case("oge", CmpInst::FCMP_OGE)
2972 .Case("olt", CmpInst::FCMP_OLT)
2973 .Case("ole", CmpInst::FCMP_OLE)
2974 .Case("one", CmpInst::FCMP_ONE)
2975 .Case("ord", CmpInst::FCMP_ORD)
2976 .Case("uno", CmpInst::FCMP_UNO)
2977 .Case("ueq", CmpInst::FCMP_UEQ)
2978 .Case("ugt", CmpInst::FCMP_UGT)
2979 .Case("uge", CmpInst::FCMP_UGE)
2980 .Case("ult", CmpInst::FCMP_ULT)
2981 .Case("ule", CmpInst::FCMP_ULE)
2982 .Case("une", CmpInst::FCMP_UNE)
2983 .Case("true", CmpInst::FCMP_TRUE)
2986 return error("invalid floating-point predicate");
2987 } else {
2988 Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2989 .Case("eq", CmpInst::ICMP_EQ)
2990 .Case("ne", CmpInst::ICMP_NE)
2991 .Case("sgt", CmpInst::ICMP_SGT)
2992 .Case("sge", CmpInst::ICMP_SGE)
2993 .Case("slt", CmpInst::ICMP_SLT)
2994 .Case("sle", CmpInst::ICMP_SLE)
2995 .Case("ugt", CmpInst::ICMP_UGT)
2996 .Case("uge", CmpInst::ICMP_UGE)
2997 .Case("ult", CmpInst::ICMP_ULT)
2998 .Case("ule", CmpInst::ICMP_ULE)
3001 return error("invalid integer predicate");
3002 }
3003
3004 lex();
3006 if (expectAndConsume(MIToken::rparen))
3007 return error("predicate should be terminated by ')'.");
3008
3009 return false;
3010}
3011
3012bool MIParser::parseShuffleMaskOperand(MachineOperand &Dest) {
3014
3015 lex();
3016 if (expectAndConsume(MIToken::lparen))
3017 return error("expected syntax shufflemask(<integer or undef>, ...)");
3018
3019 SmallVector<int, 32> ShufMask;
3020 do {
3021 if (Token.is(MIToken::kw_undef)) {
3022 ShufMask.push_back(-1);
3023 } else if (Token.is(MIToken::IntegerLiteral)) {
3024 const APSInt &Int = Token.integerValue();
3025 ShufMask.push_back(Int.getExtValue());
3026 } else {
3027 return error("expected integer constant");
3028 }
3029
3030 lex();
3031 } while (consumeIfPresent(MIToken::comma));
3032
3033 if (expectAndConsume(MIToken::rparen))
3034 return error("shufflemask should be terminated by ')'.");
3035
3036 if (ShufMask.size() < 2)
3037 return error("shufflemask should have > 1 element");
3038
3039 ArrayRef<int> MaskAlloc = MF.allocateShuffleMask(ShufMask);
3040 Dest = MachineOperand::CreateShuffleMask(MaskAlloc);
3041 return false;
3042}
3043
3044bool MIParser::parseDbgInstrRefOperand(MachineOperand &Dest) {
3046
3047 lex();
3048 if (expectAndConsume(MIToken::lparen))
3049 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
3050
3051 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
3052 return error("expected unsigned integer for instruction index");
3053 uint64_t InstrIdx = Token.integerValue().getZExtValue();
3054 assert(InstrIdx <= std::numeric_limits<unsigned>::max() &&
3055 "Instruction reference's instruction index is too large");
3056 lex();
3057
3058 if (expectAndConsume(MIToken::comma))
3059 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
3060
3061 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
3062 return error("expected unsigned integer for operand index");
3063 uint64_t OpIdx = Token.integerValue().getZExtValue();
3064 assert(OpIdx <= std::numeric_limits<unsigned>::max() &&
3065 "Instruction reference's operand index is too large");
3066 lex();
3067
3068 if (expectAndConsume(MIToken::rparen))
3069 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
3070
3071 Dest = MachineOperand::CreateDbgInstrRef(InstrIdx, OpIdx);
3072 return false;
3073}
3074
3075bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
3077 lex();
3078 if (expectAndConsume(MIToken::lparen))
3079 return true;
3080 if (Token.isNot(MIToken::Identifier))
3081 return error("expected the name of the target index");
3082 int Index = 0;
3083 if (PFS.Target.getTargetIndex(Token.stringValue(), Index))
3084 return error("use of undefined target index '" + Token.stringValue() + "'");
3085 lex();
3086 if (expectAndConsume(MIToken::rparen))
3087 return true;
3088 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
3089 if (parseOperandsOffset(Dest))
3090 return true;
3091 return false;
3092}
3093
3094bool MIParser::parseCustomRegisterMaskOperand(MachineOperand &Dest) {
3095 assert(Token.stringValue() == "CustomRegMask" && "Expected a custom RegMask");
3096 lex();
3097 if (expectAndConsume(MIToken::lparen))
3098 return true;
3099
3100 uint32_t *Mask = MF.allocateRegMask();
3101 do {
3102 if (Token.isNot(MIToken::rparen)) {
3103 if (Token.isNot(MIToken::NamedRegister))
3104 return error("expected a named register");
3105 Register Reg;
3106 if (parseNamedRegister(Reg))
3107 return true;
3108 lex();
3109 Mask[Reg.id() / 32] |= 1U << (Reg.id() % 32);
3110 }
3111
3112 // TODO: Report an error if the same register is used more than once.
3113 } while (consumeIfPresent(MIToken::comma));
3114
3115 if (expectAndConsume(MIToken::rparen))
3116 return true;
3117 Dest = MachineOperand::CreateRegMask(Mask);
3118 return false;
3119}
3120
3121bool MIParser::parseLaneMaskOperand(MachineOperand &Dest) {
3122 assert(Token.is(MIToken::kw_lanemask));
3123
3124 lex();
3125 if (expectAndConsume(MIToken::lparen))
3126 return true;
3127
3128 // Parse lanemask.
3129 if (Token.isNot(MIToken::IntegerLiteral) && Token.isNot(MIToken::HexLiteral))
3130 return error("expected a valid lane mask value");
3131 static_assert(sizeof(LaneBitmask::Type) == sizeof(uint64_t),
3132 "Use correct get-function for lane mask.");
3134 if (getUint64(V))
3135 return true;
3136 LaneBitmask LaneMask(V);
3137 lex();
3138
3139 if (expectAndConsume(MIToken::rparen))
3140 return true;
3141
3142 Dest = MachineOperand::CreateLaneMask(LaneMask);
3143 return false;
3144}
3145
3146bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
3147 assert(Token.is(MIToken::kw_liveout));
3148 uint32_t *Mask = MF.allocateRegMask();
3149 lex();
3150 if (expectAndConsume(MIToken::lparen))
3151 return true;
3152 while (true) {
3153 if (Token.isNot(MIToken::NamedRegister))
3154 return error("expected a named register");
3155 Register Reg;
3156 if (parseNamedRegister(Reg))
3157 return true;
3158 lex();
3159 Mask[Reg.id() / 32] |= 1U << (Reg.id() % 32);
3160 // TODO: Report an error if the same register is used more than once.
3161 if (Token.isNot(MIToken::comma))
3162 break;
3163 lex();
3164 }
3165 if (expectAndConsume(MIToken::rparen))
3166 return true;
3168 return false;
3169}
3170
3171bool MIParser::parseMachineOperand(const unsigned OpCode, const unsigned OpIdx,
3172 MachineOperand &Dest,
3173 std::optional<unsigned> &TiedDefIdx) {
3174 switch (Token.kind()) {
3177 case MIToken::kw_def:
3178 case MIToken::kw_dead:
3179 case MIToken::kw_killed:
3180 case MIToken::kw_undef:
3189 return parseRegisterOperand(Dest, TiedDefIdx);
3191 // TODO: Forbid numeric operands for INLINEASM once the transition to the
3192 // symbolic form is over.
3193 return parseImmediateOperand(Dest);
3194 case MIToken::kw_half:
3195 case MIToken::kw_bfloat:
3196 case MIToken::kw_float:
3197 case MIToken::kw_double:
3199 case MIToken::kw_fp128:
3201 return parseFPImmediateOperand(Dest);
3203 return parseMBBOperand(Dest);
3205 return parseStackObjectOperand(Dest);
3207 return parseFixedStackObjectOperand(Dest);
3210 return parseGlobalAddressOperand(Dest);
3212 return parseConstantPoolIndexOperand(Dest);
3214 return parseJumpTableIndexOperand(Dest);
3216 return parseExternalSymbolOperand(Dest);
3217 case MIToken::MCSymbol:
3218 return parseMCSymbolOperand(Dest);
3220 return parseSubRegisterIndexOperand(Dest);
3221 case MIToken::md_diexpr:
3222 case MIToken::exclaim:
3223 return parseMetadataOperand(Dest);
3246 return parseCFIOperand(Dest);
3248 return parseBlockAddressOperand(Dest);
3250 return parseIntrinsicOperand(Dest);
3252 return parseTargetIndexOperand(Dest);
3254 return parseLaneMaskOperand(Dest);
3256 return parseLiveoutRegisterMaskOperand(Dest);
3259 return parsePredicateOperand(Dest);
3261 return parseShuffleMaskOperand(Dest);
3263 return parseDbgInstrRefOperand(Dest);
3264 case MIToken::Error:
3265 return true;
3266 case MIToken::Identifier: {
3267 bool IsInlineAsm = OpCode == TargetOpcode::INLINEASM ||
3268 OpCode == TargetOpcode::INLINEASM_BR;
3269 if (IsInlineAsm)
3270 return parseSymbolicInlineAsmOperand(OpIdx, Dest);
3271
3272 StringRef Id = Token.stringValue();
3273 if (const auto *RegMask = PFS.Target.getRegMask(Id)) {
3274 Dest = MachineOperand::CreateRegMask(RegMask);
3275 lex();
3276 break;
3277 } else if (Id == "CustomRegMask") {
3278 return parseCustomRegisterMaskOperand(Dest);
3279 } else {
3280 return parseTypedImmediateOperand(Dest);
3281 }
3282 }
3283 case MIToken::dot: {
3284 const auto *TII = MF.getSubtarget().getInstrInfo();
3285 if (const auto *Formatter = TII->getMIRFormatter()) {
3286 return parseTargetImmMnemonic(OpCode, OpIdx, Dest, *Formatter);
3287 }
3288 [[fallthrough]];
3289 }
3290 default:
3291 // FIXME: Parse the MCSymbol machine operand.
3292 return error("expected a machine operand");
3293 }
3294 return false;
3295}
3296
3297bool MIParser::parseMachineOperandAndTargetFlags(
3298 const unsigned OpCode, const unsigned OpIdx, MachineOperand &Dest,
3299 std::optional<unsigned> &TiedDefIdx) {
3300 unsigned TF = 0;
3301 bool HasTargetFlags = false;
3302 if (Token.is(MIToken::kw_target_flags)) {
3303 HasTargetFlags = true;
3304 lex();
3305 if (expectAndConsume(MIToken::lparen))
3306 return true;
3307 if (Token.isNot(MIToken::Identifier))
3308 return error("expected the name of the target flag");
3309 if (PFS.Target.getDirectTargetFlag(Token.stringValue(), TF)) {
3310 if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), TF))
3311 return error("use of undefined target flag '" + Token.stringValue() +
3312 "'");
3313 }
3314 lex();
3315 while (Token.is(MIToken::comma)) {
3316 lex();
3317 if (Token.isNot(MIToken::Identifier))
3318 return error("expected the name of the target flag");
3319 unsigned BitFlag = 0;
3320 if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), BitFlag))
3321 return error("use of undefined target flag '" + Token.stringValue() +
3322 "'");
3323 // TODO: Report an error when using a duplicate bit target flag.
3324 TF |= BitFlag;
3325 lex();
3326 }
3327 if (expectAndConsume(MIToken::rparen))
3328 return true;
3329 }
3330 auto Loc = Token.location();
3331 if (parseMachineOperand(OpCode, OpIdx, Dest, TiedDefIdx))
3332 return true;
3333 if (!HasTargetFlags)
3334 return false;
3335 if (Dest.isReg())
3336 return error(Loc, "register operands can't have target flags");
3337 Dest.setTargetFlags(TF);
3338 return false;
3339}
3340
3341bool MIParser::parseOffset(int64_t &Offset) {
3342 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
3343 return false;
3344 StringRef Sign = Token.range();
3345 bool IsNegative = Token.is(MIToken::minus);
3346 lex();
3347 if (Token.isNot(MIToken::IntegerLiteral))
3348 return error("expected an integer literal after '" + Sign + "'");
3349 if (Token.integerValue().getSignificantBits() > 64)
3350 return error("expected 64-bit integer (too large)");
3351 Offset = Token.integerValue().getExtValue();
3352 if (IsNegative)
3353 Offset = -Offset;
3354 lex();
3355 return false;
3356}
3357
3358bool MIParser::parseIRBlockAddressTaken(BasicBlock *&BB) {
3360 lex();
3361 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
3362 return error("expected basic block after 'ir_block_address_taken'");
3363
3364 if (parseIRBlock(BB, MF.getFunction()))
3365 return true;
3366
3367 lex();
3368 return false;
3369}
3370
3371bool MIParser::parseAlignment(uint64_t &Alignment) {
3372 assert(Token.is(MIToken::kw_align) || Token.is(MIToken::kw_basealign));
3373 lex();
3374 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3375 return error("expected an integer literal after 'align'");
3376 if (getUint64(Alignment))
3377 return true;
3378 lex();
3379
3380 if (!isPowerOf2_64(Alignment))
3381 return error("expected a power-of-2 literal after 'align'");
3382
3383 return false;
3384}
3385
3386bool MIParser::parseAddrspace(unsigned &Addrspace) {
3387 assert(Token.is(MIToken::kw_addrspace));
3388 lex();
3389 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3390 return error("expected an integer literal after 'addrspace'");
3391 if (getUnsigned(Addrspace))
3392 return true;
3393 lex();
3394 return false;
3395}
3396
3397bool MIParser::parseOperandsOffset(MachineOperand &Op) {
3398 int64_t Offset = 0;
3399 if (parseOffset(Offset))
3400 return true;
3401 Op.setOffset(Offset);
3402 return false;
3403}
3404
3405static bool parseIRValue(const MIToken &Token, PerFunctionMIParsingState &PFS,
3406 const Value *&V, ErrorCallbackType ErrCB) {
3407 switch (Token.kind()) {
3408 case MIToken::NamedIRValue: {
3410 break;
3411 }
3412 case MIToken::IRValue: {
3413 unsigned SlotNumber = 0;
3414 if (getUnsigned(Token, SlotNumber, ErrCB))
3415 return true;
3416 V = PFS.getIRValue(SlotNumber);
3417 break;
3418 }
3420 case MIToken::GlobalValue: {
3421 GlobalValue *GV = nullptr;
3422 if (parseGlobalValue(Token, PFS, GV, ErrCB))
3423 return true;
3424 V = GV;
3425 break;
3426 }
3428 const Constant *C = nullptr;
3429 if (parseIRConstant(Token.location(), Token.stringValue(), PFS, C, ErrCB))
3430 return true;
3431 V = C;
3432 break;
3433 }
3435 V = nullptr;
3436 return false;
3437 default:
3438 llvm_unreachable("The current token should be an IR block reference");
3439 }
3440 if (!V)
3441 return ErrCB(Token.location(), Twine("use of undefined IR value '") + Token.range() + "'");
3442 return false;
3443}
3444
3445bool MIParser::parseIRValue(const Value *&V) {
3446 return ::parseIRValue(
3447 Token, PFS, V, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3448 return error(Loc, Msg);
3449 });
3450}
3451
3452bool MIParser::getUint64(uint64_t &Result) {
3453 if (Token.hasIntegerValue()) {
3454 if (Token.integerValue().getActiveBits() > 64)
3455 return error("expected 64-bit integer (too large)");
3456 Result = Token.integerValue().getZExtValue();
3457 return false;
3458 }
3459 if (Token.is(MIToken::HexLiteral)) {
3460 APInt A;
3461 if (getHexUint(A))
3462 return true;
3463 if (A.getBitWidth() > 64)
3464 return error("expected 64-bit integer (too large)");
3465 Result = A.getZExtValue();
3466 return false;
3467 }
3468 return true;
3469}
3470
3471bool MIParser::getHexUint(APInt &Result) {
3472 return ::getHexUint(Token, Result);
3473}
3474
3475bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags &Flags) {
3476 const auto OldFlags = Flags;
3477 switch (Token.kind()) {
3480 break;
3483 break;
3486 break;
3489 break;
3492 if (PFS.Target.getMMOTargetFlag(Token.stringValue(), TF))
3493 return error("use of undefined target MMO flag '" + Token.stringValue() +
3494 "'");
3495 Flags |= TF;
3496 break;
3497 }
3498 default:
3499 llvm_unreachable("The current token should be a memory operand flag");
3500 }
3501 if (OldFlags == Flags)
3502 // We know that the same flag is specified more than once when the flags
3503 // weren't modified.
3504 return error("duplicate '" + Token.stringValue() + "' memory operand flag");
3505 lex();
3506 return false;
3507}
3508
3509bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
3510 switch (Token.kind()) {
3511 case MIToken::kw_stack:
3512 PSV = MF.getPSVManager().getStack();
3513 break;
3514 case MIToken::kw_got:
3515 PSV = MF.getPSVManager().getGOT();
3516 break;
3518 PSV = MF.getPSVManager().getJumpTable();
3519 break;
3521 PSV = MF.getPSVManager().getConstantPool();
3522 break;
3524 int FI;
3525 if (parseFixedStackFrameIndex(FI))
3526 return true;
3527 PSV = MF.getPSVManager().getFixedStack(FI);
3528 // The token was already consumed, so use return here instead of break.
3529 return false;
3530 }
3531 case MIToken::StackObject: {
3532 int FI;
3533 if (parseStackFrameIndex(FI))
3534 return true;
3535 PSV = MF.getPSVManager().getFixedStack(FI);
3536 // The token was already consumed, so use return here instead of break.
3537 return false;
3538 }
3540 lex();
3541 switch (Token.kind()) {
3544 GlobalValue *GV = nullptr;
3545 if (parseGlobalValue(GV))
3546 return true;
3547 PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
3548 break;
3549 }
3551 PSV = MF.getPSVManager().getExternalSymbolCallEntry(
3552 MF.createExternalSymbolName(Token.stringValue()));
3553 break;
3554 default:
3555 return error(
3556 "expected a global value or an external symbol after 'call-entry'");
3557 }
3558 break;
3559 case MIToken::kw_custom: {
3560 lex();
3561 const auto *TII = MF.getSubtarget().getInstrInfo();
3562 if (const auto *Formatter = TII->getMIRFormatter()) {
3563 if (Formatter->parseCustomPseudoSourceValue(
3564 Token.stringValue(), MF, PFS, PSV,
3565 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3566 return error(Loc, Msg);
3567 }))
3568 return true;
3569 } else {
3570 return error("unable to parse target custom pseudo source value");
3571 }
3572 break;
3573 }
3574 default:
3575 llvm_unreachable("The current token should be pseudo source value");
3576 }
3577 lex();
3578 return false;
3579}
3580
3581bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
3582 if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
3583 Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
3584 Token.is(MIToken::FixedStackObject) || Token.is(MIToken::StackObject) ||
3585 Token.is(MIToken::kw_call_entry) || Token.is(MIToken::kw_custom)) {
3586 const PseudoSourceValue *PSV = nullptr;
3587 if (parseMemoryPseudoSourceValue(PSV))
3588 return true;
3589 int64_t Offset = 0;
3590 if (parseOffset(Offset))
3591 return true;
3592 Dest = MachinePointerInfo(PSV, Offset);
3593 return false;
3594 }
3595 if (Token.isNot(MIToken::NamedIRValue) && Token.isNot(MIToken::IRValue) &&
3596 Token.isNot(MIToken::GlobalValue) &&
3597 Token.isNot(MIToken::NamedGlobalValue) &&
3598 Token.isNot(MIToken::QuotedIRValue) &&
3599 Token.isNot(MIToken::kw_unknown_address))
3600 return error("expected an IR value reference");
3601 const Value *V = nullptr;
3602 if (parseIRValue(V))
3603 return true;
3604 if (V && !V->getType()->isPointerTy())
3605 return error("expected a pointer IR value");
3606 lex();
3607 int64_t Offset = 0;
3608 if (parseOffset(Offset))
3609 return true;
3610 Dest = MachinePointerInfo(V, Offset);
3611 return false;
3612}
3613
3614bool MIParser::parseOptionalScope(LLVMContext &Context,
3615 SyncScope::ID &SSID) {
3616 SSID = SyncScope::System;
3617 if (Token.is(MIToken::Identifier) && Token.stringValue() == "syncscope") {
3618 lex();
3619 if (expectAndConsume(MIToken::lparen))
3620 return error("expected '(' in syncscope");
3621
3622 std::string SSN;
3623 if (parseStringConstant(SSN))
3624 return true;
3625
3626 SSID = Context.getOrInsertSyncScopeID(SSN);
3627 if (expectAndConsume(MIToken::rparen))
3628 return error("expected ')' in syncscope");
3629 }
3630
3631 return false;
3632}
3633
3634bool MIParser::parseOptionalAtomicOrdering(AtomicOrdering &Order) {
3636 if (Token.isNot(MIToken::Identifier))
3637 return false;
3638
3639 Order = StringSwitch<AtomicOrdering>(Token.stringValue())
3640 .Case("unordered", AtomicOrdering::Unordered)
3641 .Case("monotonic", AtomicOrdering::Monotonic)
3642 .Case("acquire", AtomicOrdering::Acquire)
3643 .Case("release", AtomicOrdering::Release)
3647
3648 if (Order != AtomicOrdering::NotAtomic) {
3649 lex();
3650 return false;
3651 }
3652
3653 return error("expected an atomic scope, ordering or a size specification");
3654}
3655
3656bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
3657 if (expectAndConsume(MIToken::lparen))
3658 return true;
3660 while (Token.isMemoryOperandFlag()) {
3661 if (parseMemoryOperandFlag(Flags))
3662 return true;
3663 }
3664 if (Token.isNot(MIToken::Identifier) ||
3665 (Token.stringValue() != "load" && Token.stringValue() != "store"))
3666 return error("expected 'load' or 'store' memory operation");
3667 if (Token.stringValue() == "load")
3669 else
3671 lex();
3672
3673 // Optional 'store' for operands that both load and store.
3674 if (Token.is(MIToken::Identifier) && Token.stringValue() == "store") {
3676 lex();
3677 }
3678
3679 // Optional synchronization scope.
3680 SyncScope::ID SSID;
3681 if (parseOptionalScope(MF.getFunction().getContext(), SSID))
3682 return true;
3683
3684 // Up to two atomic orderings (cmpxchg provides guarantees on failure).
3685 AtomicOrdering Order, FailureOrder;
3686 if (parseOptionalAtomicOrdering(Order))
3687 return true;
3688
3689 if (parseOptionalAtomicOrdering(FailureOrder))
3690 return true;
3691
3692 if (Token.isNot(MIToken::IntegerLiteral) &&
3693 Token.isNot(MIToken::kw_unknown_size) &&
3694 Token.isNot(MIToken::lparen))
3695 return error("expected memory LLT, the size integer literal or 'unknown-size' after "
3696 "memory operation");
3697
3699 if (Token.is(MIToken::IntegerLiteral)) {
3700 uint64_t Size;
3701 if (getUint64(Size))
3702 return true;
3703
3704 // Convert from bytes to bits for storage.
3706 lex();
3707 } else if (Token.is(MIToken::kw_unknown_size)) {
3708 lex();
3709 } else {
3710 if (expectAndConsume(MIToken::lparen))
3711 return true;
3712 if (parseLowLevelType(Token.location(), MemoryType))
3713 return true;
3714 if (expectAndConsume(MIToken::rparen))
3715 return true;
3716 }
3717
3719 if (Token.is(MIToken::Identifier)) {
3720 const char *Word =
3723 ? "on"
3724 : Flags & MachineMemOperand::MOLoad ? "from" : "into";
3725 if (Token.stringValue() != Word)
3726 return error(Twine("expected '") + Word + "'");
3727 lex();
3728
3729 if (parseMachinePointerInfo(Ptr))
3730 return true;
3731 }
3732 uint64_t BaseAlignment =
3733 MemoryType.isValid()
3734 ? PowerOf2Ceil(MemoryType.getSizeInBytes().getKnownMinValue())
3735 : 1;
3736 AAMDNodes AAInfo;
3737 MDNode *Range = nullptr;
3738 MDNode *MemCacheHint = nullptr;
3739 while (consumeIfPresent(MIToken::comma)) {
3740 switch (Token.kind()) {
3741 case MIToken::kw_align: {
3742 // align is printed if it is different than size.
3744 if (parseAlignment(Alignment))
3745 return true;
3746 if (Ptr.Offset & (Alignment - 1)) {
3747 // MachineMemOperand::getAlign never returns a value greater than the
3748 // alignment of offset, so this just guards against hand-written MIR
3749 // that specifies a large "align" value when it should probably use
3750 // "basealign" instead.
3751 return error("specified alignment is more aligned than offset");
3752 }
3753 BaseAlignment = Alignment;
3754 break;
3755 }
3757 // basealign is printed if it is different than align.
3758 if (parseAlignment(BaseAlignment))
3759 return true;
3760 break;
3762 if (parseAddrspace(Ptr.AddrSpace))
3763 return true;
3764 break;
3765 case MIToken::md_tbaa:
3766 lex();
3767 if (parseMDNode(AAInfo.TBAA))
3768 return true;
3769 break;
3771 lex();
3772 if (parseMDNode(AAInfo.Scope))
3773 return true;
3774 break;
3776 lex();
3777 if (parseMDNode(AAInfo.NoAlias))
3778 return true;
3779 break;
3781 lex();
3782 if (parseMDNode(AAInfo.NoAliasAddrSpace))
3783 return true;
3784 break;
3785 case MIToken::md_range:
3786 lex();
3787 if (parseMDNode(Range))
3788 return true;
3789 break;
3791 lex();
3792 if (parseMDNode(MemCacheHint))
3793 return true;
3794 break;
3795 // TODO: Report an error on duplicate metadata nodes.
3796 default:
3797 return error("expected 'align' or '!tbaa' or '!alias.scope' or "
3798 "'!noalias' or '!range' or '!mem.cache_hint' or "
3799 "'!noalias.addrspace'");
3800 }
3801 }
3802 if (expectAndConsume(MIToken::rparen))
3803 return true;
3804 Dest = MF.getMachineMemOperand(Ptr, Flags, MemoryType, Align(BaseAlignment),
3805 MMOMetadata(AAInfo, Range, MemCacheHint), SSID,
3806 Order, FailureOrder);
3807 return false;
3808}
3809
3810bool MIParser::parsePreOrPostInstrSymbol(MCSymbol *&Symbol) {
3812 Token.is(MIToken::kw_post_instr_symbol)) &&
3813 "Invalid token for a pre- post-instruction symbol!");
3814 lex();
3815 if (Token.isNot(MIToken::MCSymbol))
3816 return error("expected a symbol after 'pre-instr-symbol'");
3817 Symbol = getOrCreateMCSymbol(Token.stringValue());
3818 lex();
3819 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3820 Token.is(MIToken::lbrace))
3821 return false;
3822 if (Token.isNot(MIToken::comma))
3823 return error("expected ',' before the next machine operand");
3824 lex();
3825 return false;
3826}
3827
3828bool MIParser::parseHeapAllocMarker(MDNode *&Node) {
3830 "Invalid token for a heap alloc marker!");
3831 lex();
3832 if (parseMDNode(Node))
3833 return true;
3834 if (!Node)
3835 return error("expected a MDNode after 'heap-alloc-marker'");
3836 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3837 Token.is(MIToken::lbrace))
3838 return false;
3839 if (Token.isNot(MIToken::comma))
3840 return error("expected ',' before the next machine operand");
3841 lex();
3842 return false;
3843}
3844
3845bool MIParser::parsePCSections(MDNode *&Node) {
3846 assert(Token.is(MIToken::kw_pcsections) &&
3847 "Invalid token for a PC sections!");
3848 lex();
3849 if (parseMDNode(Node))
3850 return true;
3851 if (!Node)
3852 return error("expected a MDNode after 'pcsections'");
3853 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3854 Token.is(MIToken::lbrace))
3855 return false;
3856 if (Token.isNot(MIToken::comma))
3857 return error("expected ',' before the next machine operand");
3858 lex();
3859 return false;
3860}
3861
3862bool MIParser::parseMMRA(MDNode *&Node) {
3863 assert(Token.is(MIToken::kw_mmra) && "Invalid token for MMRA!");
3864 lex();
3865 if (parseMDNode(Node))
3866 return true;
3867 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3868 Token.is(MIToken::lbrace))
3869 return false;
3870 if (Token.isNot(MIToken::comma))
3871 return error("expected ',' before the next machine operand");
3872 lex();
3873 return false;
3874}
3875
3877 const Function &F,
3878 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3879 ModuleSlotTracker MST(F.getParent());
3881 for (const auto &BB : F) {
3882 if (BB.hasName())
3883 continue;
3884 int Slot = MST.getLocalSlot(&BB);
3885 if (Slot == -1)
3886 continue;
3887 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
3888 }
3889}
3890
3892 unsigned Slot,
3893 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3894 return Slots2BasicBlocks.lookup(Slot);
3895}
3896
3897const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
3898 if (Slots2BasicBlocks.empty())
3899 initSlots2BasicBlocks(MF.getFunction(), Slots2BasicBlocks);
3900 return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
3901}
3902
3903const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
3904 if (&F == &MF.getFunction())
3905 return getIRBlock(Slot);
3906 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
3907 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
3908 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
3909}
3910
3911MCSymbol *MIParser::getOrCreateMCSymbol(StringRef Name) {
3912 // FIXME: Currently we can't recognize temporary or local symbols and call all
3913 // of the appropriate forms to create them. However, this handles basic cases
3914 // well as most of the special aspects are recognized by a prefix on their
3915 // name, and the input names should already be unique. For test cases, keeping
3916 // the symbol name out of the symbol table isn't terribly important.
3917 return MF.getContext().getOrCreateSymbol(Name);
3918}
3919
3920bool MIParser::parseStringConstant(std::string &Result) {
3921 if (Token.isNot(MIToken::StringConstant))
3922 return error("expected string constant");
3923 Result = std::string(Token.stringValue());
3924 lex();
3925 return false;
3926}
3927
3929 StringRef Src,
3931 return MIParser(PFS, Error, Src).parseBasicBlockDefinitions(PFS.MBBSlots);
3932}
3933
3936 return MIParser(PFS, Error, Src).parseBasicBlocks();
3937}
3938
3942 return MIParser(PFS, Error, Src).parseStandaloneMBB(MBB);
3943}
3944
3946 Register &Reg, StringRef Src,
3948 return MIParser(PFS, Error, Src).parseStandaloneRegister(Reg);
3949}
3950
3952 Register &Reg, StringRef Src,
3954 return MIParser(PFS, Error, Src).parseStandaloneNamedRegister(Reg);
3955}
3956
3958 VRegInfo *&Info, StringRef Src,
3960 return MIParser(PFS, Error, Src).parseStandaloneVirtualRegister(Info);
3961}
3962
3965 return MIParser(PFS, Error, Src).parseStandaloneStackObject(FI);
3966}
3967
3971 return MIParser(PFS, Error, Src).parsePrefetchTarget(Target);
3972}
3975 return MIParser(PFS, Error, Src).parseStandaloneMDNode(Node);
3976}
3977
3979 PerFunctionMIParsingState &PFS, const Value *&V,
3980 ErrorCallbackType ErrorCallback) {
3981 MIToken Token;
3982 Src = lexMIToken(Src, Token, [&](StringRef::iterator Loc, const Twine &Msg) {
3983 ErrorCallback(Loc, Msg);
3984 });
3985 V = nullptr;
3986
3987 return ::parseIRValue(Token, PFS, V, ErrorCallback);
3988}
const AArch64Subtarget & Subtarget
SDValue Pred
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
uint64_t uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
bpf unwind lower
basic Basic Alias true
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Error parseAlignment(StringRef Str, Align &Alignment, StringRef Name, bool AllowZero=false)
Attempts to parse an alignment component of a specification.
This file defines the DenseMap class.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define RegName(no)
A common definition of LaneBitmask for use in TableGen and CodeGen.
static llvm::Error parse(GsymDataExtractor &Data, uint64_t BaseAddr, LineEntryCallback const &Callback)
Definition LineTable.cpp:54
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
static const char * printImplicitRegisterFlag(const MachineOperand &MO)
static bool verifyVectorElementCount(uint64_t NumElts, bool HasVScale)
static const BasicBlock * getIRBlockFromSlot(unsigned Slot, const DenseMap< unsigned, const BasicBlock * > &Slots2BasicBlocks)
static std::string getRegisterName(const TargetRegisterInfo *TRI, Register Reg)
static bool parseIRConstant(StringRef::iterator Loc, StringRef StringValue, PerFunctionMIParsingState &PFS, const Constant *&C, ErrorCallbackType ErrCB)
static void initSlots2Values(const Function &F, DenseMap< unsigned, const Value * > &Slots2Values)
Creates the mapping from slot numbers to function's unnamed IR values.
Definition MIParser.cpp:361
static bool parseIRValue(const MIToken &Token, PerFunctionMIParsingState &PFS, const Value *&V, ErrorCallbackType ErrCB)
static bool verifyScalarSize(uint64_t Size)
static bool getUnsigned(const MIToken &Token, unsigned &Result, ErrorCallbackType ErrCB)
static bool getHexUint(const MIToken &Token, APInt &Result)
static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST, DenseMap< unsigned, const Value * > &Slots2Values)
Definition MIParser.cpp:352
static void initSlots2BasicBlocks(const Function &F, DenseMap< unsigned, const BasicBlock * > &Slots2BasicBlocks)
function_ref< bool(StringRef::iterator Loc, const Twine &)> ErrorCallbackType
Definition MIParser.cpp:606
static bool isImplicitOperandIn(const MachineOperand &ImplicitOperand, ArrayRef< ParsedMachineOperand > Operands)
Return true if the parsed machine operands contain a given machine operand.
static bool parseGlobalValue(const MIToken &Token, PerFunctionMIParsingState &PFS, GlobalValue *&GV, ErrorCallbackType ErrCB)
static bool verifyAddrSpace(uint64_t AddrSpace)
Register Reg
Register const TargetRegisterInfo * TRI
#define R2(n)
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
SI Fold Operands
const char * Msg
This file defines the SmallVector class.
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
#define error(X)
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
bool isNegative() const
Determine sign of this APSInt.
Definition APSInt.h:50
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
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static constexpr BranchProbability getRaw(uint32_t N)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:312
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
ValueSymbolTable * getValueSymbolTable()
getSymbolTable() - Return the symbol table if any, otherwise nullptr.
Definition Function.h:802
Module * getParent()
Get the module that this global value is contained inside of...
static constexpr LLT vector(ElementCount EC, unsigned ScalarSizeInBits)
Get a low-level vector of some number of elements and element width.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr bool isValid() const
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
static constexpr LLT token()
Get a low-level token; just a scalar with zero bits (or no size).
static constexpr LLT bfloat16()
static LLT floatIEEE(unsigned SizeInBits)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
static MCCFIInstruction createDefCfaRegister(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_def_cfa_register modifies a rule for computing CFA.
Definition MCDwarf.h:635
static MCCFIInstruction createLLVMVectorOffset(MCSymbol *L, unsigned Register, unsigned RegisterSizeInBits, unsigned MaskRegister, unsigned MaskRegisterSizeInBits, int64_t Offset, SMLoc Loc={})
.cfi_llvm_vector_offset Previous value of Register is saved at Offset from CFA.
Definition MCDwarf.h:797
static MCCFIInstruction createUndefined(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_undefined From now on the previous value of Register can't be restored anymore.
Definition MCDwarf.h:732
static MCCFIInstruction createLLVMVectorRegisters(MCSymbol *L, unsigned Register, ArrayRef< VectorRegisterWithLane > VectorRegisters, SMLoc Loc={})
.cfi_llvm_vector_registers Previous value of Register is saved in lanes of vector registers.
Definition MCDwarf.h:787
static MCCFIInstruction createRestore(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_restore says that the rule for Register is now the same as it was at the beginning of the functi...
Definition MCDwarf.h:725
static MCCFIInstruction createSetRAState(MCSymbol *L, unsigned State, MCSymbol *PACSym=nullptr, SMLoc Loc={})
.cfi_set_ra_state AArch64 set RA sign state,
Definition MCDwarf.h:708
static MCCFIInstruction createLLVMDefAspaceCfa(MCSymbol *L, unsigned Register, int64_t Offset, unsigned AddressSpace, SMLoc Loc)
.cfi_llvm_def_aspace_cfa defines the rule for computing the CFA to be the result of evaluating the DW...
Definition MCDwarf.h:660
static MCCFIInstruction createLLVMVectorRegisterMask(MCSymbol *L, unsigned Register, unsigned SpillRegister, unsigned SpillRegisterLaneSizeInBits, unsigned MaskRegister, unsigned MaskRegisterSizeInBits, SMLoc Loc={})
.cfi_llvm_vector_register_mask Previous value of Register is saved in SpillRegister,...
Definition MCDwarf.h:808
static MCCFIInstruction createRegister(MCSymbol *L, unsigned Register1, unsigned Register2, SMLoc Loc={})
.cfi_register Previous value of Register1 is saved in register Register2.
Definition MCDwarf.h:685
static MCCFIInstruction cfiDefCfa(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it.
Definition MCDwarf.h:628
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition MCDwarf.h:670
static MCCFIInstruction createNegateRAStateWithPC(MCSymbol *L, SMLoc Loc={})
.cfi_negate_ra_state_with_pc AArch64 negate RA state with PC.
Definition MCDwarf.h:701
static MCCFIInstruction createNegateRAState(MCSymbol *L, SMLoc Loc={})
.cfi_negate_ra_state AArch64 negate RA state.
Definition MCDwarf.h:696
static MCCFIInstruction createRememberState(MCSymbol *L, SMLoc Loc={})
.cfi_remember_state Save all current rules for all registers.
Definition MCDwarf.h:745
static MCCFIInstruction createLLVMRegisterPair(MCSymbol *L, unsigned Register, unsigned R1, unsigned R1SizeInBits, unsigned R2, unsigned R2SizeInBits, SMLoc Loc={})
.cfi_llvm_register_pair Previous value of Register is saved in R1:R2.
Definition MCDwarf.h:777
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition MCDwarf.h:643
static MCCFIInstruction createEscape(MCSymbol *L, StringRef Vals, SMLoc Loc={}, StringRef Comment="")
.cfi_escape Allows the user to add arbitrary bytes to the unwind info.
Definition MCDwarf.h:756
static MCCFIInstruction createWindowSave(MCSymbol *L, SMLoc Loc={})
.cfi_window_save SPARC register window is saved.
Definition MCDwarf.h:691
static MCCFIInstruction createAdjustCfaOffset(MCSymbol *L, int64_t Adjustment, SMLoc Loc={})
.cfi_adjust_cfa_offset Same as .cfi_def_cfa_offset, but Offset is a relative value that is added/subt...
Definition MCDwarf.h:651
static MCCFIInstruction createRestoreState(MCSymbol *L, SMLoc Loc={})
.cfi_restore_state Restore the previously saved state.
Definition MCDwarf.h:750
static MCCFIInstruction createSameValue(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_same_value Current value of Register is the same as in the previous frame.
Definition MCDwarf.h:739
static MCCFIInstruction createRelOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_rel_offset Previous value of Register is saved at offset Offset from the current CFA register.
Definition MCDwarf.h:678
Describe properties that are true of each instruction in the target description file.
unsigned getID() const
getID() - Return the register class ID number.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Metadata node.
Definition Metadata.h:1081
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
MIRFormater - Interface to format MIR operand based on target.
virtual bool parseImmMnemonic(const unsigned OpCode, const unsigned OpIdx, StringRef Src, int64_t &Imm, ErrorCallbackType ErrorCallback) const
Implement target specific parsing of immediate mnemonics.
function_ref< bool(StringRef::iterator Loc, const Twine &)> ErrorCallbackType
static LLVM_ABI bool parseIRValue(StringRef Src, MachineFunction &MF, PerFunctionMIParsingState &PFS, const Value *&V, ErrorCallbackType ErrorCallback)
Helper functions to parse IR value from MIR serialization format which will be useful for target spec...
void normalizeSuccProbs()
Normalize probabilities of all successors so that the sum of them becomes one.
void setAddressTakenIRBlock(BasicBlock *BB)
Set this block to reflect that it corresponds to an IR-level basic block with a BlockAddress.
void setIsCleanupFuncletEntry(bool V=true)
Indicates if this is the entry block of a cleanup funclet.
void setLabelMustBeEmitted()
Set this block to reflect that, regardless how we flow to it, we need its label be emitted.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
void setMaxBytesForAlignment(unsigned MaxBytes)
Set the maximum amount of padding allowed for aligning the basic block.
void setAlignment(Align A)
Set alignment of the basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void setSectionID(MBBSectionID V)
Sets the section ID for this basic block.
void setIsInlineAsmBrIndirectTarget(bool V=true)
Indicates if this is the indirect dest of an INLINEASM_BR.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
void setIsEHContTarget(bool V=true)
Indicates if this is a target of Windows EH Continuation Guard.
void setIsEHFuncletEntry(bool V=true)
Indicates if this is the entry block of an EH funclet.
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
void setIsEHScopeEntry(bool V=true)
Indicates if this is the entry block of an EH scope, i.e., the block that that used to have a catchpa...
void setMachineBlockAddressTaken()
Set this block to indicate that its address is used as something other than the target of a terminato...
void setIsEHPad(bool V=true)
Indicates the block is a landing pad.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
void setFlag(MIFlag Flag)
Set a MI flag.
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MONonTemporal
The memory access is non-temporal.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
static MachineOperand CreateMCSymbol(MCSymbol *Sym, unsigned TargetFlags=0)
static MachineOperand CreateES(const char *SymName, unsigned TargetFlags=0)
static MachineOperand CreateFPImm(const ConstantFP *CFP)
static MachineOperand CreateCFIIndex(unsigned CFIIndex)
static MachineOperand CreateRegMask(const uint32_t *Mask)
CreateRegMask - Creates a register mask operand referencing Mask.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
static MachineOperand CreateCImm(const ConstantInt *CI)
static MachineOperand CreateMetadata(const MDNode *Meta)
static MachineOperand CreatePredicate(unsigned Pred)
static MachineOperand CreateImm(int64_t Val)
static MachineOperand CreateShuffleMask(ArrayRef< int > Mask)
static MachineOperand CreateJTI(unsigned Idx, unsigned TargetFlags=0)
static MachineOperand CreateDbgInstrRef(unsigned InstrIdx, unsigned OpIdx)
static MachineOperand CreateRegLiveOut(const uint32_t *Mask)
static MachineOperand CreateGA(const GlobalValue *GV, int64_t Offset, unsigned TargetFlags=0)
static MachineOperand CreateBA(const BlockAddress *BA, int64_t Offset, unsigned TargetFlags=0)
void setTargetFlags(unsigned F)
static MachineOperand CreateLaneMask(LaneBitmask LaneMask)
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
static MachineOperand CreateCPI(unsigned Idx, int Offset, unsigned TargetFlags=0)
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
static MachineOperand CreateTargetIndex(unsigned Idx, int64_t Offset, unsigned TargetFlags=0)
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0)
static MachineOperand CreateIntrinsicID(Intrinsic::ID ID)
static MachineOperand CreateFI(int Idx)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
void setRegClassOrRegBank(Register Reg, const RegClassOrRegBank &RCOrRB)
LLT getType(Register Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register.
LLVM_ABI void setType(Register VReg, LLT Ty)
Set the low-level type of VReg to Ty.
void noteNewVirtualRegister(Register Reg)
This interface provides simple read-only access to a block of memory, and provides simple methods for...
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
const char * getBufferEnd() const
const char * getBufferStart() const
Manage lifetime of a slot tracker for printing IR.
int getLocalSlot(const Value *V)
Return the slot number of the specified local value.
void incorporateFunction(const Function &F)
Incorporate the given function.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Special value supplied for machine level alias analysis.
const RegisterBank & getRegBank(unsigned ID)
Get the register bank identified by ID.
unsigned getNumRegBanks() const
Get the total number of register banks.
This class implements the register bank concept.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
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
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:307
Represents a location in source code.
Definition SMLoc.h:22
static SMLoc getFromPointer(const char *Ptr)
Definition SMLoc.h:35
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition SourceMgr.h:34
unsigned getMainFileID() const
Definition SourceMgr.h:150
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition SourceMgr.h:141
LLVM_ABI SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges={}, ArrayRef< SMFixIt > FixIts={}) const
Return an SMDiagnostic at the specified location with the specified string.
bool empty() const
Definition StringMap.h:103
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition StringMap.h:311
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:736
const char * iterator
Definition StringRef.h:60
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
LLVM_ABI std::string lower() const
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:661
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
Value * lookup(StringRef Name) const
This method finds the value with the given Name in the the symbol table.
LLVM Value Representation.
Definition Value.h:75
bool hasName() const
Definition Value.h:263
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:66
support::ulittle32_t Word
Definition IRSymtab.h:53
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI bool parseStackObjectReference(PerFunctionMIParsingState &PFS, int &FI, StringRef Src, SMDiagnostic &Error)
LLVM_ABI bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node, StringRef Src, SMDiagnostic &Error)
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
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
RegState
Flags to represent properties of register accesses.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
@ Kill
The last use of a register.
@ InternalRead
Register reads a value that is defined inside the same instruction or bundle.
@ Undef
Value of the register doesn't matter.
@ EarlyClobber
Register definition happens before uses.
@ Define
Register definition.
@ Renamable
Register that may be renamed.
@ Debug
Register 'use' is for debugging purpose.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
StringRef lexMIToken(StringRef Source, MIToken &Token, function_ref< void(StringRef::iterator, const Twine &)> ErrorCallback)
Consume a single machine instruction token in the given source and return the remaining source string...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
LLVM_ABI bool parseMachineBasicBlockDefinitions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine basic block definitions, and skip the machine instructions.
LLVM_ABI bool parsePrefetchTarget(PerFunctionMIParsingState &PFS, CallsiteID &Target, StringRef Src, SMDiagnostic &Error)
LLVM_ABI void guessSuccessors(const MachineBasicBlock &MBB, SmallVectorImpl< MachineBasicBlock * > &Result, bool &IsFallthrough)
Determine a possible list of successors of a basic block based on the basic block machine operand bei...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool parseMBBReference(PerFunctionMIParsingState &PFS, MachineBasicBlock *&MBB, StringRef Src, SMDiagnostic &Error)
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI DIExpression * parseDIExpressionBodyAtBeginning(StringRef Asm, unsigned &Read, SMDiagnostic &Err, const Module &M, const SlotMapping *Slots)
Definition Parser.cpp:238
constexpr RegState getDefRegState(bool B)
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
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
constexpr bool hasRegState(RegState Value, RegState Test)
AtomicOrdering
Atomic ordering for LLVM's memory model.
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
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
LLVM_ABI bool parseMachineInstructions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine instructions.
LLVM_ABI bool parseRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
LLVM_ABI Constant * parseConstantValue(StringRef Asm, SMDiagnostic &Err, const Module &M, const SlotMapping *Slots=nullptr)
Parse a type and a constant value in the given string.
Definition Parser.cpp:197
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool parseVirtualRegisterReference(PerFunctionMIParsingState &PFS, VRegInfo *&Info, StringRef Src, SMDiagnostic &Error)
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:774
MDNode * NoAliasAddrSpace
The tag specifying the noalias address spaces.
Definition Metadata.h:803
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:797
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:791
MDNode * NoAlias
The tag specifying the noalias scope.
Definition Metadata.h:800
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82
LLVM_ABI static const MBBSectionID ExceptionSectionID
LLVM_ABI static const MBBSectionID ColdSectionID
A token produced by the machine instruction lexer.
Definition MILexer.h:26
TokenKind kind() const
Definition MILexer.h:222
bool hasIntegerValue() const
Definition MILexer.h:262
bool is(TokenKind K) const
Definition MILexer.h:249
StringRef stringValue() const
Return the token's string value.
Definition MILexer.h:258
@ kw_pre_instr_symbol
Definition MILexer.h:144
@ kw_deactivation_symbol
Definition MILexer.h:149
@ kw_call_frame_size
Definition MILexer.h:157
@ kw_cfi_aarch64_negate_ra_sign_state
Definition MILexer.h:101
@ kw_cfi_llvm_def_aspace_cfa
Definition MILexer.h:94
@ MachineBasicBlock
Definition MILexer.h:181
@ kw_dbg_instr_ref
Definition MILexer.h:85
@ NamedVirtualRegister
Definition MILexer.h:179
@ kw_early_clobber
Definition MILexer.h:59
@ kw_cleanup_funclet_entry
Definition MILexer.h:137
@ kw_unpredictable
Definition MILexer.h:77
@ FloatingPointLiteral
Definition MILexer.h:191
@ kw_cfi_window_save
Definition MILexer.h:100
@ kw_cfi_llvm_register_pair
Definition MILexer.h:104
@ kw_frame_destroy
Definition MILexer.h:64
@ kw_cfi_undefined
Definition MILexer.h:99
@ MachineBasicBlockLabel
Definition MILexer.h:180
@ kw_cfi_llvm_vector_offset
Definition MILexer.h:106
@ kw_cfi_register
Definition MILexer.h:95
@ kw_inlineasm_br_indirect_target
Definition MILexer.h:134
@ kw_cfi_rel_offset
Definition MILexer.h:88
@ kw_cfi_llvm_vector_registers
Definition MILexer.h:105
@ kw_ehfunclet_entry
Definition MILexer.h:136
@ kw_label_must_be_emitted
Definition MILexer.h:156
@ kw_cfi_llvm_vector_register_mask
Definition MILexer.h:107
@ kw_cfi_aarch64_negate_ra_sign_state_with_pc
Definition MILexer.h:102
@ kw_cfi_def_cfa_register
Definition MILexer.h:89
@ kw_cfi_same_value
Definition MILexer.h:86
@ kw_cfi_set_ra_state
Definition MILexer.h:103
@ kw_cfi_adjust_cfa_offset
Definition MILexer.h:91
@ kw_dereferenceable
Definition MILexer.h:55
@ kw_implicit_define
Definition MILexer.h:52
@ kw_max_bytes_for_alignment
Definition MILexer.h:158
@ kw_cfi_def_cfa_offset
Definition MILexer.h:90
@ md_mem_cache_hint
Definition MILexer.h:172
@ kw_machine_block_address_taken
Definition MILexer.h:155
@ kw_cfi_remember_state
Definition MILexer.h:96
@ kw_debug_instr_number
Definition MILexer.h:84
@ kw_post_instr_symbol
Definition MILexer.h:145
@ kw_cfi_restore_state
Definition MILexer.h:98
@ kw_ir_block_address_taken
Definition MILexer.h:154
@ kw_unknown_address
Definition MILexer.h:153
@ md_noalias_addrspace
Definition MILexer.h:170
@ kw_debug_location
Definition MILexer.h:83
@ kw_heap_alloc_marker
Definition MILexer.h:146
StringRef range() const
Definition MILexer.h:255
StringRef::iterator location() const
Definition MILexer.h:253
const APSInt & integerValue() const
Definition MILexer.h:260
LLVM IR metadata carried by a MachineMemOperand.
This class contains a discriminated union of information about pointers in memory operands,...
int64_t Offset
Offset - This is an offset from the base Value*.
LLVM_ABI VRegInfo & getVRegInfo(Register Num)
Definition MIParser.cpp:329
const SlotMapping & IRSlots
Definition MIParser.h:173
LLVM_ABI const Value * getIRValue(unsigned Slot)
Definition MIParser.cpp:374
DenseMap< unsigned, MachineBasicBlock * > MBBSlots
Definition MIParser.h:178
StringMap< VRegInfo * > VRegInfosNamed
Definition MIParser.h:180
DenseMap< unsigned, const Value * > Slots2Values
Maps from slot numbers to function's unnamed values.
Definition MIParser.h:187
LLVM_ABI PerFunctionMIParsingState(MachineFunction &MF, SourceMgr &SM, const SlotMapping &IRSlots, PerTargetMIParsingState &Target)
Definition MIParser.cpp:324
PerTargetMIParsingState & Target
Definition MIParser.h:174
DenseMap< Register, VRegInfo * > VRegInfos
Definition MIParser.h:179
LLVM_ABI VRegInfo & getVRegInfoNamed(StringRef RegName)
Definition MIParser.cpp:340
LLVM_ABI bool getVRegFlagValue(StringRef FlagName, uint8_t &FlagValue) const
Definition MIParser.cpp:129
LLVM_ABI bool getDirectTargetFlag(StringRef Name, unsigned &Flag)
Try to convert a name of a direct target flag to the corresponding target flag.
Definition MIParser.cpp:227
LLVM_ABI const RegisterBank * getRegBank(StringRef Name)
Check if the given identifier is a name of a register bank.
Definition MIParser.cpp:317
LLVM_ABI bool parseInstrName(StringRef InstrName, unsigned &OpCode)
Try to convert an instruction name to an opcode.
Definition MIParser.cpp:148
LLVM_ABI unsigned getSubRegIndex(StringRef Name)
Check if the given identifier is a name of a subregister index.
Definition MIParser.cpp:188
LLVM_ABI bool getTargetIndex(StringRef Name, int &Index)
Try to convert a name of target index to the corresponding target index.
Definition MIParser.cpp:206
LLVM_ABI void setTarget(const TargetSubtargetInfo &NewSubtarget)
Definition MIParser.cpp:81
LLVM_ABI bool getRegisterByName(StringRef RegName, Register &Reg)
Try to convert a register name to a register number.
Definition MIParser.cpp:119
LLVM_ABI bool getMMOTargetFlag(StringRef Name, MachineMemOperand::Flags &Flag)
Try to convert a name of a MachineMemOperand target flag to the corresponding target flag.
Definition MIParser.cpp:270
LLVM_ABI bool getBitmaskTargetFlag(StringRef Name, unsigned &Flag)
Try to convert a name of a bitmask target flag to the corresponding target flag.
Definition MIParser.cpp:249
LLVM_ABI const TargetRegisterClass * getRegClass(StringRef Name)
Check if the given identifier is a name of a register class.
Definition MIParser.cpp:310
LLVM_ABI const uint32_t * getRegMask(StringRef Identifier)
Check if the given identifier is a name of a register mask.
Definition MIParser.cpp:171
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:32
NumberedValues< GlobalValue * > GlobalValues
Definition SlotMapping.h:33
const RegisterBank * RegBank
Definition MIParser.h:46
union llvm::VRegInfo::@127225073067155374133234315364317264041071000132 D
const TargetRegisterClass * RC
Definition MIParser.h:45
enum llvm::VRegInfo::@374354327266250320012227113300214031244227062232 Kind
Register VReg
Definition MIParser.h:48
bool Explicit
VReg was explicitly specified in the .mir file.
Definition MIParser.h:43