LLVM 23.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;
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(), /*ShouldInitializeAllMetadata=*/false);
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 SMRange SourceRange;
405 MIToken Token;
406 PerFunctionMIParsingState &PFS;
407 /// Maps from slot numbers to function's unnamed basic blocks.
408 DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks;
409
410public:
411 MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
412 StringRef Source);
413 MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
414 StringRef Source, SMRange SourceRange);
415
416 /// \p SkipChar gives the number of characters to skip before looking
417 /// for the next token.
418 void lex(unsigned SkipChar = 0);
419
420 /// Report an error at the current location with the given message.
421 ///
422 /// This function always return true.
423 bool error(const Twine &Msg);
424
425 /// Report an error at the given location with the given message.
426 ///
427 /// This function always return true.
428 bool error(StringRef::iterator Loc, const Twine &Msg);
429
430 bool
431 parseBasicBlockDefinitions(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
432 bool parseBasicBlocks();
433 bool parse(MachineInstr *&MI);
434 bool parseStandaloneMBB(MachineBasicBlock *&MBB);
435 bool parseStandaloneNamedRegister(Register &Reg);
436 bool parseStandaloneVirtualRegister(VRegInfo *&Info);
437 bool parseStandaloneRegister(Register &Reg);
438 bool parseStandaloneStackObject(int &FI);
439 bool parseStandaloneMDNode(MDNode *&Node);
441 bool parseMDTuple(MDNode *&MD, bool IsDistinct);
442 bool parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts);
443 bool parseMetadata(Metadata *&MD);
444
445 bool
446 parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
447 bool parseBasicBlock(MachineBasicBlock &MBB,
448 MachineBasicBlock *&AddFalthroughFrom);
449 bool parseBasicBlockLiveins(MachineBasicBlock &MBB);
450 bool parseBasicBlockSuccessors(MachineBasicBlock &MBB);
451
452 bool parseNamedRegister(Register &Reg);
453 bool parseVirtualRegister(VRegInfo *&Info);
454 bool parseNamedVirtualRegister(VRegInfo *&Info);
455 bool parseRegister(Register &Reg, VRegInfo *&VRegInfo);
456 bool parseRegisterFlag(RegState &Flags);
457 bool parseRegisterClassOrBank(VRegInfo &RegInfo);
458 bool parseSubRegisterIndex(unsigned &SubReg);
459 bool parseRegisterTiedDefIndex(unsigned &TiedDefIdx);
460 bool parseRegisterOperand(MachineOperand &Dest,
461 std::optional<unsigned> &TiedDefIdx,
462 bool IsDef = false);
463 bool parseImmediateOperand(MachineOperand &Dest);
464 bool parseInlineAsmOperand(MachineOperand &Dest);
465 bool parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
466 const Constant *&C);
467 bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
468 bool parseLowLevelType(StringRef::iterator Loc, LLT &Ty);
469 bool parseTypedImmediateOperand(MachineOperand &Dest);
470 bool parseFPImmediateOperand(MachineOperand &Dest);
471 bool parseMBBReference(MachineBasicBlock *&MBB);
472 bool parseMBBOperand(MachineOperand &Dest);
473 bool parseStackFrameIndex(int &FI);
474 bool parseStackObjectOperand(MachineOperand &Dest);
475 bool parseFixedStackFrameIndex(int &FI);
476 bool parseFixedStackObjectOperand(MachineOperand &Dest);
477 bool parseGlobalValue(GlobalValue *&GV);
478 bool parseGlobalAddressOperand(MachineOperand &Dest);
479 bool parseConstantPoolIndexOperand(MachineOperand &Dest);
480 bool parseSubRegisterIndexOperand(MachineOperand &Dest);
481 bool parseJumpTableIndexOperand(MachineOperand &Dest);
482 bool parseExternalSymbolOperand(MachineOperand &Dest);
483 bool parseMCSymbolOperand(MachineOperand &Dest);
484 [[nodiscard]] bool parseMDNode(MDNode *&Node);
485 bool parseDIExpression(MDNode *&Expr);
486 bool parseDILocation(MDNode *&Expr);
487 bool parseMetadataOperand(MachineOperand &Dest);
488 bool parseCFIOffset(int &Offset);
489 bool parseCFIRegister(unsigned &Reg);
490 bool parseCFIAddressSpace(unsigned &AddressSpace);
491 bool parseCFIEscapeValues(std::string& Values);
492 bool parseCFIOperand(MachineOperand &Dest);
493 bool parseIRBlock(BasicBlock *&BB, const Function &F);
494 bool parseBlockAddressOperand(MachineOperand &Dest);
495 bool parseIntrinsicOperand(MachineOperand &Dest);
496 bool parsePredicateOperand(MachineOperand &Dest);
497 bool parseShuffleMaskOperand(MachineOperand &Dest);
498 bool parseTargetIndexOperand(MachineOperand &Dest);
499 bool parseDbgInstrRefOperand(MachineOperand &Dest);
500 bool parseCustomRegisterMaskOperand(MachineOperand &Dest);
501 bool parseLaneMaskOperand(MachineOperand &Dest);
502 bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
503 bool parseMachineOperand(const unsigned OpCode, const unsigned OpIdx,
504 MachineOperand &Dest,
505 std::optional<unsigned> &TiedDefIdx);
506 bool parseMachineOperandAndTargetFlags(const unsigned OpCode,
507 const unsigned OpIdx,
508 MachineOperand &Dest,
509 std::optional<unsigned> &TiedDefIdx);
510 bool parseOffset(int64_t &Offset);
511 bool parseIRBlockAddressTaken(BasicBlock *&BB);
512 bool parseAlignment(uint64_t &Alignment);
513 bool parseAddrspace(unsigned &Addrspace);
514 bool parseSectionID(std::optional<MBBSectionID> &SID);
515 bool parseBBID(std::optional<UniqueBBID> &BBID);
516 bool parseCallFrameSize(unsigned &CallFrameSize);
517 bool parsePrefetchTarget(CallsiteID &Target);
518 bool parseOperandsOffset(MachineOperand &Op);
519 bool parseIRValue(const Value *&V);
520 bool parseMemoryOperandFlag(MachineMemOperand::Flags &Flags);
521 bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
522 bool parseMachinePointerInfo(MachinePointerInfo &Dest);
523 bool parseOptionalScope(LLVMContext &Context, SyncScope::ID &SSID);
524 bool parseOptionalAtomicOrdering(AtomicOrdering &Order);
525 bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
526 bool parsePreOrPostInstrSymbol(MCSymbol *&Symbol);
527 bool parseHeapAllocMarker(MDNode *&Node);
528 bool parsePCSections(MDNode *&Node);
529 bool parseMMRA(MDNode *&Node);
530
531 bool parseTargetImmMnemonic(const unsigned OpCode, const unsigned OpIdx,
532 MachineOperand &Dest, const MIRFormatter &MF);
533
534private:
535 /// Convert the integer literal in the current token into an unsigned integer.
536 ///
537 /// Return true if an error occurred.
538 bool getUnsigned(unsigned &Result);
539
540 /// Convert the integer literal in the current token into an uint64.
541 ///
542 /// Return true if an error occurred.
543 bool getUint64(uint64_t &Result);
544
545 /// Convert the hexadecimal literal in the current token into an unsigned
546 /// APInt with a minimum bitwidth required to represent the value.
547 ///
548 /// Return true if the literal does not represent an integer value.
549 bool getHexUint(APInt &Result);
550
551 /// If the current token is of the given kind, consume it and return false.
552 /// Otherwise report an error and return true.
553 bool expectAndConsume(MIToken::TokenKind TokenKind);
554
555 /// If the current token is of the given kind, consume it and return true.
556 /// Otherwise return false.
557 bool consumeIfPresent(MIToken::TokenKind TokenKind);
558
559 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
560
561 bool assignRegisterTies(MachineInstr &MI,
563
564 bool verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
565 const MCInstrDesc &MCID);
566
567 const BasicBlock *getIRBlock(unsigned Slot);
568 const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
569
570 /// Get or create an MCSymbol for a given name.
571 MCSymbol *getOrCreateMCSymbol(StringRef Name);
572
573 /// parseStringConstant
574 /// ::= StringConstant
575 bool parseStringConstant(std::string &Result);
576
577 /// Map the location in the MI string to the corresponding location specified
578 /// in `SourceRange`.
579 SMLoc mapSMLoc(StringRef::iterator Loc);
580};
581
582} // end anonymous namespace
583
584MIParser::MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
585 StringRef Source)
586 : MF(PFS.MF), Error(Error), Source(Source), CurrentSource(Source), PFS(PFS)
587{}
588
589MIParser::MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
590 StringRef Source, SMRange SourceRange)
591 : MF(PFS.MF), Error(Error), Source(Source), CurrentSource(Source),
592 SourceRange(SourceRange), PFS(PFS) {}
593
594void MIParser::lex(unsigned SkipChar) {
595 CurrentSource = lexMIToken(
596 CurrentSource.substr(SkipChar), Token,
597 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
598}
599
600bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
601
602bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
603 const SourceMgr &SM = *PFS.SM;
604 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
605 const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
606 if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
607 // Create an ordinary diagnostic when the source manager's buffer is the
608 // source string.
610 return true;
611 }
612 // Create a diagnostic for a YAML string literal.
614 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
615 Source, {}, {});
616 return true;
617}
618
619SMLoc MIParser::mapSMLoc(StringRef::iterator Loc) {
620 assert(SourceRange.isValid() && "Invalid source range");
621 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
622 return SMLoc::getFromPointer(SourceRange.Start.getPointer() +
623 (Loc - Source.data()));
624}
625
626typedef function_ref<bool(StringRef::iterator Loc, const Twine &)>
628
629static const char *toString(MIToken::TokenKind TokenKind) {
630 switch (TokenKind) {
631 case MIToken::comma:
632 return "','";
633 case MIToken::equal:
634 return "'='";
635 case MIToken::colon:
636 return "':'";
637 case MIToken::lparen:
638 return "'('";
639 case MIToken::rparen:
640 return "')'";
641 default:
642 return "<unknown token>";
643 }
644}
645
646bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
647 if (Token.isNot(TokenKind))
648 return error(Twine("expected ") + toString(TokenKind));
649 lex();
650 return false;
651}
652
653bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
654 if (Token.isNot(TokenKind))
655 return false;
656 lex();
657 return true;
658}
659
660// Parse Machine Basic Block Section ID.
661bool MIParser::parseSectionID(std::optional<MBBSectionID> &SID) {
663 lex();
664 if (Token.is(MIToken::IntegerLiteral)) {
665 unsigned Value = 0;
666 if (getUnsigned(Value))
667 return error("Unknown Section ID");
668 SID = MBBSectionID{Value};
669 } else {
670 const StringRef &S = Token.stringValue();
671 if (S == "Exception")
673 else if (S == "Cold")
675 else
676 return error("Unknown Section ID");
677 }
678 lex();
679 return false;
680}
681
682// Parse Machine Basic Block ID.
683bool MIParser::parseBBID(std::optional<UniqueBBID> &BBID) {
684 if (Token.isNot(MIToken::kw_bb_id))
685 return error("expected 'bb_id'");
686 lex();
687 unsigned BaseID = 0;
688 unsigned CloneID = 0;
689 if (Token.is(MIToken::FloatingPointLiteral)) {
690 StringRef S = Token.range();
691 auto Parts = S.split('.');
692 if (Parts.first.getAsInteger(10, BaseID) ||
693 Parts.second.getAsInteger(10, CloneID))
694 return error("Unknown BB ID");
695 lex();
696 } else {
697 if (getUnsigned(BaseID))
698 return error("Unknown BB ID");
699 lex();
700 if (Token.is(MIToken::comma) || Token.is(MIToken::dot)) {
701 lex();
702 if (getUnsigned(CloneID))
703 return error("Unknown Clone ID");
704 lex();
705 } else if (Token.is(MIToken::IntegerLiteral)) {
706 if (getUnsigned(CloneID))
707 return error("Unknown Clone ID");
708 lex();
709 }
710 }
711 BBID = {BaseID, CloneID};
712 return false;
713}
714
715// Parse basic block call frame size.
716bool MIParser::parseCallFrameSize(unsigned &CallFrameSize) {
718 lex();
719 unsigned Value = 0;
720 if (getUnsigned(Value))
721 return error("Unknown call frame size");
722 CallFrameSize = Value;
723 lex();
724 return false;
725}
726
727bool MIParser::parsePrefetchTarget(CallsiteID &Target) {
728 lex();
729 std::optional<UniqueBBID> BBID;
730 if (parseBBID(BBID))
731 return true;
732 Target.BBID = *BBID;
733 if (expectAndConsume(MIToken::comma))
734 return true;
735 return getUnsigned(Target.CallsiteIndex);
736}
737
738bool MIParser::parseBasicBlockDefinition(
741 unsigned ID = 0;
742 if (getUnsigned(ID))
743 return true;
744 auto Loc = Token.location();
745 auto Name = Token.stringValue();
746 lex();
747 bool MachineBlockAddressTaken = false;
748 BasicBlock *AddressTakenIRBlock = nullptr;
749 bool IsLandingPad = false;
750 bool IsInlineAsmBrIndirectTarget = false;
751 bool IsEHFuncletEntry = false;
752 bool IsEHScopeEntry = false;
753 std::optional<MBBSectionID> SectionID;
754 uint64_t Alignment = 0;
755 std::optional<UniqueBBID> BBID;
756 unsigned CallFrameSize = 0;
757 BasicBlock *BB = nullptr;
758 if (consumeIfPresent(MIToken::lparen)) {
759 do {
760 // TODO: Report an error when multiple same attributes are specified.
761 switch (Token.kind()) {
763 MachineBlockAddressTaken = true;
764 lex();
765 break;
767 if (parseIRBlockAddressTaken(AddressTakenIRBlock))
768 return true;
769 break;
771 IsLandingPad = true;
772 lex();
773 break;
775 IsInlineAsmBrIndirectTarget = true;
776 lex();
777 break;
779 IsEHFuncletEntry = true;
780 lex();
781 break;
783 IsEHScopeEntry = true;
784 lex();
785 break;
787 if (parseAlignment(Alignment))
788 return true;
789 break;
790 case MIToken::IRBlock:
792 // TODO: Report an error when both name and ir block are specified.
793 if (parseIRBlock(BB, MF.getFunction()))
794 return true;
795 lex();
796 break;
798 if (parseSectionID(SectionID))
799 return true;
800 break;
802 if (parseBBID(BBID))
803 return true;
804 break;
806 if (parseCallFrameSize(CallFrameSize))
807 return true;
808 break;
809 default:
810 break;
811 }
812 } while (consumeIfPresent(MIToken::comma));
813 if (expectAndConsume(MIToken::rparen))
814 return true;
815 }
816 if (expectAndConsume(MIToken::colon))
817 return true;
818
819 if (!Name.empty()) {
821 MF.getFunction().getValueSymbolTable()->lookup(Name));
822 if (!BB)
823 return error(Loc, Twine("basic block '") + Name +
824 "' is not defined in the function '" +
825 MF.getName() + "'");
826 }
827 auto *MBB = MF.CreateMachineBasicBlock(BB, BBID);
828 MF.insert(MF.end(), MBB);
829 bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
830 if (!WasInserted)
831 return error(Loc, Twine("redefinition of machine basic block with id #") +
832 Twine(ID));
833 if (Alignment)
834 MBB->setAlignment(Align(Alignment));
835 if (MachineBlockAddressTaken)
837 if (AddressTakenIRBlock)
838 MBB->setAddressTakenIRBlock(AddressTakenIRBlock);
839 MBB->setIsEHPad(IsLandingPad);
840 MBB->setIsInlineAsmBrIndirectTarget(IsInlineAsmBrIndirectTarget);
841 MBB->setIsEHFuncletEntry(IsEHFuncletEntry);
842 MBB->setIsEHScopeEntry(IsEHScopeEntry);
843 if (SectionID) {
844 MBB->setSectionID(*SectionID);
845 MF.setBBSectionsType(BasicBlockSection::List);
846 }
847 MBB->setCallFrameSize(CallFrameSize);
848 return false;
849}
850
851bool MIParser::parseBasicBlockDefinitions(
853 lex();
854 // Skip until the first machine basic block.
855 while (Token.is(MIToken::Newline))
856 lex();
857 if (Token.isErrorOrEOF())
858 return Token.isError();
859 if (Token.isNot(MIToken::MachineBasicBlockLabel))
860 return error("expected a basic block definition before instructions");
861 unsigned BraceDepth = 0;
862 do {
863 if (parseBasicBlockDefinition(MBBSlots))
864 return true;
865 bool IsAfterNewline = false;
866 // Skip until the next machine basic block.
867 while (true) {
868 if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
869 Token.isErrorOrEOF())
870 break;
871 else if (Token.is(MIToken::MachineBasicBlockLabel))
872 return error("basic block definition should be located at the start of "
873 "the line");
874 else if (consumeIfPresent(MIToken::Newline)) {
875 IsAfterNewline = true;
876 continue;
877 }
878 IsAfterNewline = false;
879 if (Token.is(MIToken::lbrace))
880 ++BraceDepth;
881 if (Token.is(MIToken::rbrace)) {
882 if (!BraceDepth)
883 return error("extraneous closing brace ('}')");
884 --BraceDepth;
885 }
886 lex();
887 }
888 // Verify that we closed all of the '{' at the end of a file or a block.
889 if (!Token.isError() && BraceDepth)
890 return error("expected '}'"); // FIXME: Report a note that shows '{'.
891 } while (!Token.isErrorOrEOF());
892 return Token.isError();
893}
894
895bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
896 assert(Token.is(MIToken::kw_liveins));
897 lex();
898 if (expectAndConsume(MIToken::colon))
899 return true;
900 if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
901 return false;
902 do {
903 if (Token.isNot(MIToken::NamedRegister))
904 return error("expected a named register");
906 if (parseNamedRegister(Reg))
907 return true;
908 lex();
910 if (consumeIfPresent(MIToken::colon)) {
911 // Parse lane mask.
912 if (Token.isNot(MIToken::IntegerLiteral) &&
913 Token.isNot(MIToken::HexLiteral))
914 return error("expected a lane mask");
915 static_assert(sizeof(LaneBitmask::Type) == sizeof(uint64_t),
916 "Use correct get-function for lane mask");
918 if (getUint64(V))
919 return error("invalid lane mask value");
920 Mask = LaneBitmask(V);
921 lex();
922 }
923 MBB.addLiveIn(Reg, Mask);
924 } while (consumeIfPresent(MIToken::comma));
925 return false;
926}
927
928bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
930 lex();
931 if (expectAndConsume(MIToken::colon))
932 return true;
933 if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
934 return false;
935 do {
936 if (Token.isNot(MIToken::MachineBasicBlock))
937 return error("expected a machine basic block reference");
938 MachineBasicBlock *SuccMBB = nullptr;
939 if (parseMBBReference(SuccMBB))
940 return true;
941 lex();
942 unsigned Weight = 0;
943 if (consumeIfPresent(MIToken::lparen)) {
944 if (Token.isNot(MIToken::IntegerLiteral) &&
945 Token.isNot(MIToken::HexLiteral))
946 return error("expected an integer literal after '('");
947 if (getUnsigned(Weight))
948 return true;
949 lex();
950 if (expectAndConsume(MIToken::rparen))
951 return true;
952 }
954 } while (consumeIfPresent(MIToken::comma));
956 return false;
957}
958
959bool MIParser::parseBasicBlock(MachineBasicBlock &MBB,
960 MachineBasicBlock *&AddFalthroughFrom) {
961 // Skip the definition.
963 lex();
964 if (consumeIfPresent(MIToken::lparen)) {
965 while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
966 lex();
967 consumeIfPresent(MIToken::rparen);
968 }
969 consumeIfPresent(MIToken::colon);
970
971 // Parse the liveins and successors.
972 // N.B: Multiple lists of successors and liveins are allowed and they're
973 // merged into one.
974 // Example:
975 // liveins: $edi
976 // liveins: $esi
977 //
978 // is equivalent to
979 // liveins: $edi, $esi
980 bool ExplicitSuccessors = false;
981 while (true) {
982 if (Token.is(MIToken::kw_successors)) {
983 if (parseBasicBlockSuccessors(MBB))
984 return true;
985 ExplicitSuccessors = true;
986 } else if (Token.is(MIToken::kw_liveins)) {
987 if (parseBasicBlockLiveins(MBB))
988 return true;
989 } else if (consumeIfPresent(MIToken::Newline)) {
990 continue;
991 } else {
992 break;
993 }
994 if (!Token.isNewlineOrEOF())
995 return error("expected line break at the end of a list");
996 lex();
997 }
998
999 // Parse the instructions.
1000 bool IsInBundle = false;
1001 MachineInstr *PrevMI = nullptr;
1002 while (!Token.is(MIToken::MachineBasicBlockLabel) &&
1003 !Token.is(MIToken::Eof)) {
1004 if (consumeIfPresent(MIToken::Newline))
1005 continue;
1006 if (consumeIfPresent(MIToken::rbrace)) {
1007 // The first parsing pass should verify that all closing '}' have an
1008 // opening '{'.
1009 assert(IsInBundle);
1010 IsInBundle = false;
1011 continue;
1012 }
1013 MachineInstr *MI = nullptr;
1014 if (parse(MI))
1015 return true;
1016 MBB.insert(MBB.end(), MI);
1017 if (IsInBundle) {
1019 MI->setFlag(MachineInstr::BundledPred);
1020 }
1021 PrevMI = MI;
1022 if (Token.is(MIToken::lbrace)) {
1023 if (IsInBundle)
1024 return error("nested instruction bundles are not allowed");
1025 lex();
1026 // This instruction is the start of the bundle.
1027 MI->setFlag(MachineInstr::BundledSucc);
1028 IsInBundle = true;
1029 if (!Token.is(MIToken::Newline))
1030 // The next instruction can be on the same line.
1031 continue;
1032 }
1033 assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
1034 lex();
1035 }
1036
1037 // Construct successor list by searching for basic block machine operands.
1038 if (!ExplicitSuccessors) {
1040 bool IsFallthrough;
1041 guessSuccessors(MBB, Successors, IsFallthrough);
1042 for (MachineBasicBlock *Succ : Successors)
1043 MBB.addSuccessor(Succ);
1044
1045 if (IsFallthrough) {
1046 AddFalthroughFrom = &MBB;
1047 } else {
1049 }
1050 }
1051
1052 return false;
1053}
1054
1055bool MIParser::parseBasicBlocks() {
1056 lex();
1057 // Skip until the first machine basic block.
1058 while (Token.is(MIToken::Newline))
1059 lex();
1060 if (Token.isErrorOrEOF())
1061 return Token.isError();
1062 // The first parsing pass should have verified that this token is a MBB label
1063 // in the 'parseBasicBlockDefinitions' method.
1065 MachineBasicBlock *AddFalthroughFrom = nullptr;
1066 do {
1067 MachineBasicBlock *MBB = nullptr;
1069 return true;
1070 if (AddFalthroughFrom) {
1071 if (!AddFalthroughFrom->isSuccessor(MBB))
1072 AddFalthroughFrom->addSuccessor(MBB);
1073 AddFalthroughFrom->normalizeSuccProbs();
1074 AddFalthroughFrom = nullptr;
1075 }
1076 if (parseBasicBlock(*MBB, AddFalthroughFrom))
1077 return true;
1078 // The method 'parseBasicBlock' should parse the whole block until the next
1079 // block or the end of file.
1080 assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
1081 } while (Token.isNot(MIToken::Eof));
1082 return false;
1083}
1084
1085bool MIParser::parse(MachineInstr *&MI) {
1086 // Parse any register operands before '='
1089 while (Token.isRegister() || Token.isRegisterFlag()) {
1090 auto Loc = Token.location();
1091 std::optional<unsigned> TiedDefIdx;
1092 if (parseRegisterOperand(MO, TiedDefIdx, /*IsDef=*/true))
1093 return true;
1094 Operands.push_back(
1095 ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
1096 if (Token.isNot(MIToken::comma))
1097 break;
1098 lex();
1099 }
1100 if (!Operands.empty() && expectAndConsume(MIToken::equal))
1101 return true;
1102
1103 unsigned OpCode, Flags = 0;
1104 if (Token.isError() || parseInstruction(OpCode, Flags))
1105 return true;
1106
1107 // Parse the remaining machine operands.
1108 while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_pre_instr_symbol) &&
1109 Token.isNot(MIToken::kw_post_instr_symbol) &&
1110 Token.isNot(MIToken::kw_heap_alloc_marker) &&
1111 Token.isNot(MIToken::kw_pcsections) && Token.isNot(MIToken::kw_mmra) &&
1112 Token.isNot(MIToken::kw_cfi_type) &&
1113 Token.isNot(MIToken::kw_deactivation_symbol) &&
1114 Token.isNot(MIToken::kw_debug_location) &&
1115 Token.isNot(MIToken::kw_debug_instr_number) &&
1116 Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) {
1117 auto Loc = Token.location();
1118 std::optional<unsigned> TiedDefIdx;
1119 if (parseMachineOperandAndTargetFlags(OpCode, Operands.size(), MO, TiedDefIdx))
1120 return true;
1121 Operands.push_back(
1122 ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
1123 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
1124 Token.is(MIToken::lbrace))
1125 break;
1126 if (Token.isNot(MIToken::comma))
1127 return error("expected ',' before the next machine operand");
1128 lex();
1129 }
1130
1131 MCSymbol *PreInstrSymbol = nullptr;
1132 if (Token.is(MIToken::kw_pre_instr_symbol))
1133 if (parsePreOrPostInstrSymbol(PreInstrSymbol))
1134 return true;
1135 MCSymbol *PostInstrSymbol = nullptr;
1136 if (Token.is(MIToken::kw_post_instr_symbol))
1137 if (parsePreOrPostInstrSymbol(PostInstrSymbol))
1138 return true;
1139 MDNode *HeapAllocMarker = nullptr;
1140 if (Token.is(MIToken::kw_heap_alloc_marker))
1141 if (parseHeapAllocMarker(HeapAllocMarker))
1142 return true;
1143 MDNode *PCSections = nullptr;
1144 if (Token.is(MIToken::kw_pcsections))
1145 if (parsePCSections(PCSections))
1146 return true;
1147 MDNode *MMRA = nullptr;
1148 if (Token.is(MIToken::kw_mmra) && parseMMRA(MMRA))
1149 return true;
1150 unsigned CFIType = 0;
1151 if (Token.is(MIToken::kw_cfi_type)) {
1152 lex();
1153 if (Token.isNot(MIToken::IntegerLiteral))
1154 return error("expected an integer literal after 'cfi-type'");
1155 // getUnsigned is sufficient for 32-bit integers.
1156 if (getUnsigned(CFIType))
1157 return true;
1158 lex();
1159 // Lex past trailing comma if present.
1160 if (Token.is(MIToken::comma))
1161 lex();
1162 }
1163
1164 GlobalValue *DS = nullptr;
1165 if (Token.is(MIToken::kw_deactivation_symbol)) {
1166 lex();
1167 if (parseGlobalValue(DS))
1168 return true;
1169 lex();
1170 }
1171
1172 unsigned InstrNum = 0;
1173 if (Token.is(MIToken::kw_debug_instr_number)) {
1174 lex();
1175 if (Token.isNot(MIToken::IntegerLiteral))
1176 return error("expected an integer literal after 'debug-instr-number'");
1177 if (getUnsigned(InstrNum))
1178 return true;
1179 lex();
1180 // Lex past trailing comma if present.
1181 if (Token.is(MIToken::comma))
1182 lex();
1183 }
1184
1185 DebugLoc DebugLocation;
1186 if (Token.is(MIToken::kw_debug_location)) {
1187 lex();
1188 MDNode *Node = nullptr;
1189 if (Token.is(MIToken::exclaim)) {
1190 if (parseMDNode(Node))
1191 return true;
1192 } else if (Token.is(MIToken::md_dilocation)) {
1193 if (parseDILocation(Node))
1194 return true;
1195 } else {
1196 return error("expected a metadata node after 'debug-location'");
1197 }
1198 if (!isa<DILocation>(Node))
1199 return error("referenced metadata is not a DILocation");
1200 DebugLocation = DebugLoc(Node);
1201 }
1202
1203 // Parse the machine memory operands.
1205 if (Token.is(MIToken::coloncolon)) {
1206 lex();
1207 while (!Token.isNewlineOrEOF()) {
1208 MachineMemOperand *MemOp = nullptr;
1209 if (parseMachineMemoryOperand(MemOp))
1210 return true;
1211 MemOperands.push_back(MemOp);
1212 if (Token.isNewlineOrEOF())
1213 break;
1214 if (OpCode == TargetOpcode::BUNDLE && Token.is(MIToken::lbrace))
1215 break;
1216 if (Token.isNot(MIToken::comma))
1217 return error("expected ',' before the next machine memory operand");
1218 lex();
1219 }
1220 }
1221
1222 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
1223 if (!MCID.isVariadic()) {
1224 // FIXME: Move the implicit operand verification to the machine verifier.
1225 if (verifyImplicitOperands(Operands, MCID))
1226 return true;
1227 }
1228
1229 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
1230 MI->setFlags(Flags);
1231
1232 // Don't check the operands make sense, let the verifier catch any
1233 // improprieties.
1234 for (const auto &Operand : Operands)
1235 MI->addOperand(MF, Operand.Operand);
1236
1237 if (assignRegisterTies(*MI, Operands))
1238 return true;
1239 if (PreInstrSymbol)
1240 MI->setPreInstrSymbol(MF, PreInstrSymbol);
1241 if (PostInstrSymbol)
1242 MI->setPostInstrSymbol(MF, PostInstrSymbol);
1243 if (HeapAllocMarker)
1244 MI->setHeapAllocMarker(MF, HeapAllocMarker);
1245 if (PCSections)
1246 MI->setPCSections(MF, PCSections);
1247 if (MMRA)
1248 MI->setMMRAMetadata(MF, MMRA);
1249 if (CFIType)
1250 MI->setCFIType(MF, CFIType);
1251 if (DS)
1252 MI->setDeactivationSymbol(MF, DS);
1253 if (!MemOperands.empty())
1254 MI->setMemRefs(MF, MemOperands);
1255 if (InstrNum)
1256 MI->setDebugInstrNum(InstrNum);
1257 return false;
1258}
1259
1260bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
1261 lex();
1262 if (Token.isNot(MIToken::MachineBasicBlock))
1263 return error("expected a machine basic block reference");
1265 return true;
1266 lex();
1267 if (Token.isNot(MIToken::Eof))
1268 return error(
1269 "expected end of string after the machine basic block reference");
1270 return false;
1271}
1272
1273bool MIParser::parseStandaloneNamedRegister(Register &Reg) {
1274 lex();
1275 if (Token.isNot(MIToken::NamedRegister))
1276 return error("expected a named register");
1277 if (parseNamedRegister(Reg))
1278 return true;
1279 lex();
1280 if (Token.isNot(MIToken::Eof))
1281 return error("expected end of string after the register reference");
1282 return false;
1283}
1284
1285bool MIParser::parseStandaloneVirtualRegister(VRegInfo *&Info) {
1286 lex();
1287 if (Token.isNot(MIToken::VirtualRegister))
1288 return error("expected a virtual register");
1289 if (parseVirtualRegister(Info))
1290 return true;
1291 lex();
1292 if (Token.isNot(MIToken::Eof))
1293 return error("expected end of string after the register reference");
1294 return false;
1295}
1296
1297bool MIParser::parseStandaloneRegister(Register &Reg) {
1298 lex();
1299 if (Token.isNot(MIToken::NamedRegister) &&
1300 Token.isNot(MIToken::VirtualRegister))
1301 return error("expected either a named or virtual register");
1302
1303 VRegInfo *Info;
1304 if (parseRegister(Reg, Info))
1305 return true;
1306
1307 lex();
1308 if (Token.isNot(MIToken::Eof))
1309 return error("expected end of string after the register reference");
1310 return false;
1311}
1312
1313bool MIParser::parseStandaloneStackObject(int &FI) {
1314 lex();
1315 if (Token.isNot(MIToken::StackObject))
1316 return error("expected a stack object");
1317 if (parseStackFrameIndex(FI))
1318 return true;
1319 if (Token.isNot(MIToken::Eof))
1320 return error("expected end of string after the stack object reference");
1321 return false;
1322}
1323
1324bool MIParser::parseStandaloneMDNode(MDNode *&Node) {
1325 lex();
1326 if (Token.is(MIToken::exclaim)) {
1327 if (parseMDNode(Node))
1328 return true;
1329 } else if (Token.is(MIToken::md_diexpr)) {
1330 if (parseDIExpression(Node))
1331 return true;
1332 } else if (Token.is(MIToken::md_dilocation)) {
1333 if (parseDILocation(Node))
1334 return true;
1335 } else {
1336 return error("expected a metadata node");
1337 }
1338 if (Token.isNot(MIToken::Eof))
1339 return error("expected end of string after the metadata node");
1340 return false;
1341}
1342
1343bool MIParser::parseMachineMetadata() {
1344 lex();
1345 if (Token.isNot(MIToken::exclaim))
1346 return error("expected a metadata node");
1347
1348 lex();
1349 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1350 return error("expected metadata id after '!'");
1351 unsigned ID = 0;
1352 if (getUnsigned(ID))
1353 return true;
1354 lex();
1355 if (expectAndConsume(MIToken::equal))
1356 return true;
1357 bool IsDistinct = Token.is(MIToken::kw_distinct);
1358 if (IsDistinct)
1359 lex();
1360 if (Token.isNot(MIToken::exclaim))
1361 return error("expected a metadata node");
1362 lex();
1363
1364 MDNode *MD;
1365 if (parseMDTuple(MD, IsDistinct))
1366 return true;
1367
1368 auto FI = PFS.MachineForwardRefMDNodes.find(ID);
1369 if (FI != PFS.MachineForwardRefMDNodes.end()) {
1370 FI->second.first->replaceAllUsesWith(MD);
1371 PFS.MachineForwardRefMDNodes.erase(FI);
1372
1373 assert(PFS.MachineMetadataNodes[ID] == MD && "Tracking VH didn't work");
1374 } else {
1375 auto [It, Inserted] = PFS.MachineMetadataNodes.try_emplace(ID);
1376 if (!Inserted)
1377 return error("Metadata id is already used");
1378 It->second.reset(MD);
1379 }
1380
1381 return false;
1382}
1383
1384bool MIParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
1386 if (parseMDNodeVector(Elts))
1387 return true;
1388 MD = (IsDistinct ? MDTuple::getDistinct
1389 : MDTuple::get)(MF.getFunction().getContext(), Elts);
1390 return false;
1391}
1392
1393bool MIParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
1394 if (Token.isNot(MIToken::lbrace))
1395 return error("expected '{' here");
1396 lex();
1397
1398 if (Token.is(MIToken::rbrace)) {
1399 lex();
1400 return false;
1401 }
1402
1403 do {
1404 Metadata *MD;
1405 if (parseMetadata(MD))
1406 return true;
1407
1408 Elts.push_back(MD);
1409
1410 if (Token.isNot(MIToken::comma))
1411 break;
1412 lex();
1413 } while (true);
1414
1415 if (Token.isNot(MIToken::rbrace))
1416 return error("expected end of metadata node");
1417 lex();
1418
1419 return false;
1420}
1421
1422// ::= !42
1423// ::= !"string"
1424bool MIParser::parseMetadata(Metadata *&MD) {
1425 if (Token.isNot(MIToken::exclaim))
1426 return error("expected '!' here");
1427 lex();
1428
1429 if (Token.is(MIToken::StringConstant)) {
1430 std::string Str;
1431 if (parseStringConstant(Str))
1432 return true;
1433 MD = MDString::get(MF.getFunction().getContext(), Str);
1434 return false;
1435 }
1436
1437 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1438 return error("expected metadata id after '!'");
1439
1440 SMLoc Loc = mapSMLoc(Token.location());
1441
1442 unsigned ID = 0;
1443 if (getUnsigned(ID))
1444 return true;
1445 lex();
1446
1447 auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID);
1448 if (NodeInfo != PFS.IRSlots.MetadataNodes.end()) {
1449 MD = NodeInfo->second.get();
1450 return false;
1451 }
1452 // Check machine metadata.
1453 NodeInfo = PFS.MachineMetadataNodes.find(ID);
1454 if (NodeInfo != PFS.MachineMetadataNodes.end()) {
1455 MD = NodeInfo->second.get();
1456 return false;
1457 }
1458 // Forward reference.
1459 auto &FwdRef = PFS.MachineForwardRefMDNodes[ID];
1460 FwdRef = std::make_pair(
1461 MDTuple::getTemporary(MF.getFunction().getContext(), {}), Loc);
1462 PFS.MachineMetadataNodes[ID].reset(FwdRef.first.get());
1463 MD = FwdRef.first.get();
1464
1465 return false;
1466}
1467
1468static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
1469 assert(MO.isImplicit());
1470 return MO.isDef() ? "implicit-def" : "implicit";
1471}
1472
1473static std::string getRegisterName(const TargetRegisterInfo *TRI,
1474 Register Reg) {
1475 assert(Reg.isPhysical() && "expected phys reg");
1476 return StringRef(TRI->getName(Reg)).lower();
1477}
1478
1479/// Return true if the parsed machine operands contain a given machine operand.
1480static bool isImplicitOperandIn(const MachineOperand &ImplicitOperand,
1482 for (const auto &I : Operands) {
1483 if (ImplicitOperand.isIdenticalTo(I.Operand))
1484 return true;
1485 }
1486 return false;
1487}
1488
1489bool MIParser::verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
1490 const MCInstrDesc &MCID) {
1491 if (MCID.isCall())
1492 // We can't verify call instructions as they can contain arbitrary implicit
1493 // register and register mask operands.
1494 return false;
1495
1496 // Gather all the expected implicit operands.
1497 SmallVector<MachineOperand, 4> ImplicitOperands;
1498 for (MCPhysReg ImpDef : MCID.implicit_defs())
1499 ImplicitOperands.push_back(MachineOperand::CreateReg(ImpDef, true, true));
1500 for (MCPhysReg ImpUse : MCID.implicit_uses())
1501 ImplicitOperands.push_back(MachineOperand::CreateReg(ImpUse, false, true));
1502
1503 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1504 assert(TRI && "Expected target register info");
1505 for (const auto &I : ImplicitOperands) {
1506 if (isImplicitOperandIn(I, Operands))
1507 continue;
1508 return error(Operands.empty() ? Token.location() : Operands.back().End,
1509 Twine("missing implicit register operand '") +
1511 getRegisterName(TRI, I.getReg()) + "'");
1512 }
1513 return false;
1514}
1515
1516bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
1517 // Allow frame and fast math flags for OPCODE
1518 // clang-format off
1519 while (Token.is(MIToken::kw_frame_setup) ||
1520 Token.is(MIToken::kw_frame_destroy) ||
1521 Token.is(MIToken::kw_nnan) ||
1522 Token.is(MIToken::kw_ninf) ||
1523 Token.is(MIToken::kw_nsz) ||
1524 Token.is(MIToken::kw_arcp) ||
1525 Token.is(MIToken::kw_contract) ||
1526 Token.is(MIToken::kw_afn) ||
1527 Token.is(MIToken::kw_reassoc) ||
1528 Token.is(MIToken::kw_nuw) ||
1529 Token.is(MIToken::kw_nsw) ||
1530 Token.is(MIToken::kw_exact) ||
1531 Token.is(MIToken::kw_nofpexcept) ||
1532 Token.is(MIToken::kw_noconvergent) ||
1533 Token.is(MIToken::kw_unpredictable) ||
1534 Token.is(MIToken::kw_nneg) ||
1535 Token.is(MIToken::kw_disjoint) ||
1536 Token.is(MIToken::kw_nusw) ||
1537 Token.is(MIToken::kw_samesign) ||
1538 Token.is(MIToken::kw_inbounds)) {
1539 // clang-format on
1540 // Mine frame and fast math flags
1541 if (Token.is(MIToken::kw_frame_setup))
1543 if (Token.is(MIToken::kw_frame_destroy))
1545 if (Token.is(MIToken::kw_nnan))
1547 if (Token.is(MIToken::kw_ninf))
1549 if (Token.is(MIToken::kw_nsz))
1551 if (Token.is(MIToken::kw_arcp))
1553 if (Token.is(MIToken::kw_contract))
1555 if (Token.is(MIToken::kw_afn))
1557 if (Token.is(MIToken::kw_reassoc))
1559 if (Token.is(MIToken::kw_nuw))
1561 if (Token.is(MIToken::kw_nsw))
1563 if (Token.is(MIToken::kw_exact))
1565 if (Token.is(MIToken::kw_nofpexcept))
1567 if (Token.is(MIToken::kw_unpredictable))
1569 if (Token.is(MIToken::kw_noconvergent))
1571 if (Token.is(MIToken::kw_nneg))
1573 if (Token.is(MIToken::kw_disjoint))
1575 if (Token.is(MIToken::kw_nusw))
1577 if (Token.is(MIToken::kw_samesign))
1579 if (Token.is(MIToken::kw_inbounds))
1581
1582 lex();
1583 }
1584 if (Token.isNot(MIToken::Identifier))
1585 return error("expected a machine instruction");
1586 StringRef InstrName = Token.stringValue();
1587 if (PFS.Target.parseInstrName(InstrName, OpCode))
1588 return error(Twine("unknown machine instruction name '") + InstrName + "'");
1589 lex();
1590 return false;
1591}
1592
1593bool MIParser::parseNamedRegister(Register &Reg) {
1594 assert(Token.is(MIToken::NamedRegister) && "Needs NamedRegister token");
1595 StringRef Name = Token.stringValue();
1596 if (PFS.Target.getRegisterByName(Name, Reg))
1597 return error(Twine("unknown register name '") + Name + "'");
1598 return false;
1599}
1600
1601bool MIParser::parseNamedVirtualRegister(VRegInfo *&Info) {
1602 assert(Token.is(MIToken::NamedVirtualRegister) && "Expected NamedVReg token");
1603 StringRef Name = Token.stringValue();
1604 // TODO: Check that the VReg name is not the same as a physical register name.
1605 // If it is, then print a warning (when warnings are implemented).
1606 Info = &PFS.getVRegInfoNamed(Name);
1607 return false;
1608}
1609
1610bool MIParser::parseVirtualRegister(VRegInfo *&Info) {
1611 if (Token.is(MIToken::NamedVirtualRegister))
1612 return parseNamedVirtualRegister(Info);
1613 assert(Token.is(MIToken::VirtualRegister) && "Needs VirtualRegister token");
1614 unsigned ID;
1615 if (getUnsigned(ID))
1616 return true;
1617 Info = &PFS.getVRegInfo(ID);
1618 return false;
1619}
1620
1621bool MIParser::parseRegister(Register &Reg, VRegInfo *&Info) {
1622 switch (Token.kind()) {
1624 Reg = 0;
1625 return false;
1627 return parseNamedRegister(Reg);
1630 if (parseVirtualRegister(Info))
1631 return true;
1632 Reg = Info->VReg;
1633 return false;
1634 // TODO: Parse other register kinds.
1635 default:
1636 llvm_unreachable("The current token should be a register");
1637 }
1638}
1639
1640bool MIParser::parseRegisterClassOrBank(VRegInfo &RegInfo) {
1641 if (Token.isNot(MIToken::Identifier) && Token.isNot(MIToken::underscore))
1642 return error("expected '_', register class, or register bank name");
1643 StringRef::iterator Loc = Token.location();
1644 StringRef Name = Token.stringValue();
1645
1646 // Was it a register class?
1647 const TargetRegisterClass *RC = PFS.Target.getRegClass(Name);
1648 if (RC) {
1649 lex();
1650
1651 switch (RegInfo.Kind) {
1652 case VRegInfo::UNKNOWN:
1653 case VRegInfo::NORMAL:
1654 RegInfo.Kind = VRegInfo::NORMAL;
1655 if (RegInfo.Explicit && RegInfo.D.RC != RC) {
1656 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1657 return error(Loc, Twine("conflicting register classes, previously: ") +
1658 Twine(TRI.getRegClassName(RegInfo.D.RC)));
1659 }
1660 RegInfo.D.RC = RC;
1661 RegInfo.Explicit = true;
1662 return false;
1663
1664 case VRegInfo::GENERIC:
1665 case VRegInfo::REGBANK:
1666 return error(Loc, "register class specification on generic register");
1667 }
1668 llvm_unreachable("Unexpected register kind");
1669 }
1670
1671 // Should be a register bank or a generic register.
1672 const RegisterBank *RegBank = nullptr;
1673 if (Name != "_") {
1674 RegBank = PFS.Target.getRegBank(Name);
1675 if (!RegBank)
1676 return error(Loc, "expected '_', register class, or register bank name");
1677 }
1678
1679 lex();
1680
1681 switch (RegInfo.Kind) {
1682 case VRegInfo::UNKNOWN:
1683 case VRegInfo::GENERIC:
1684 case VRegInfo::REGBANK:
1685 RegInfo.Kind = RegBank ? VRegInfo::REGBANK : VRegInfo::GENERIC;
1686 if (RegInfo.Explicit && RegInfo.D.RegBank != RegBank)
1687 return error(Loc, "conflicting generic register banks");
1688 RegInfo.D.RegBank = RegBank;
1689 RegInfo.Explicit = true;
1690 return false;
1691
1692 case VRegInfo::NORMAL:
1693 return error(Loc, "register bank specification on normal register");
1694 }
1695 llvm_unreachable("Unexpected register kind");
1696}
1697
1698bool MIParser::parseRegisterFlag(RegState &Flags) {
1699 const RegState OldFlags = Flags;
1700 switch (Token.kind()) {
1703 break;
1706 break;
1707 case MIToken::kw_def:
1709 break;
1710 case MIToken::kw_dead:
1712 break;
1713 case MIToken::kw_killed:
1715 break;
1716 case MIToken::kw_undef:
1718 break;
1721 break;
1724 break;
1727 break;
1730 break;
1731 default:
1732 llvm_unreachable("The current token should be a register flag");
1733 }
1734 if (OldFlags == Flags)
1735 // We know that the same flag is specified more than once when the flags
1736 // weren't modified.
1737 return error("duplicate '" + Token.stringValue() + "' register flag");
1738 lex();
1739 return false;
1740}
1741
1742bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
1743 assert(Token.is(MIToken::dot));
1744 lex();
1745 if (Token.isNot(MIToken::Identifier))
1746 return error("expected a subregister index after '.'");
1747 auto Name = Token.stringValue();
1748 SubReg = PFS.Target.getSubRegIndex(Name);
1749 if (!SubReg)
1750 return error(Twine("use of unknown subregister index '") + Name + "'");
1751 lex();
1752 return false;
1753}
1754
1755bool MIParser::parseRegisterTiedDefIndex(unsigned &TiedDefIdx) {
1756 assert(Token.is(MIToken::kw_tied_def));
1757 lex();
1758 if (Token.isNot(MIToken::IntegerLiteral))
1759 return error("expected an integer literal after 'tied-def'");
1760 if (getUnsigned(TiedDefIdx))
1761 return true;
1762 lex();
1763 return expectAndConsume(MIToken::rparen);
1764}
1765
1766bool MIParser::assignRegisterTies(MachineInstr &MI,
1768 SmallVector<std::pair<unsigned, unsigned>, 4> TiedRegisterPairs;
1769 for (unsigned I = 0, E = Operands.size(); I != E; ++I) {
1770 if (!Operands[I].TiedDefIdx)
1771 continue;
1772 // The parser ensures that this operand is a register use, so we just have
1773 // to check the tied-def operand.
1774 unsigned DefIdx = *Operands[I].TiedDefIdx;
1775 if (DefIdx >= E)
1776 return error(Operands[I].Begin,
1777 Twine("use of invalid tied-def operand index '" +
1778 Twine(DefIdx) + "'; instruction has only ") +
1779 Twine(E) + " operands");
1780 const auto &DefOperand = Operands[DefIdx].Operand;
1781 if (!DefOperand.isReg() || !DefOperand.isDef())
1782 // FIXME: add note with the def operand.
1783 return error(Operands[I].Begin,
1784 Twine("use of invalid tied-def operand index '") +
1785 Twine(DefIdx) + "'; the operand #" + Twine(DefIdx) +
1786 " isn't a defined register");
1787 // Check that the tied-def operand wasn't tied elsewhere.
1788 for (const auto &TiedPair : TiedRegisterPairs) {
1789 if (TiedPair.first == DefIdx)
1790 return error(Operands[I].Begin,
1791 Twine("the tied-def operand #") + Twine(DefIdx) +
1792 " is already tied with another register operand");
1793 }
1794 TiedRegisterPairs.push_back(std::make_pair(DefIdx, I));
1795 }
1796 // FIXME: Verify that for non INLINEASM instructions, the def and use tied
1797 // indices must be less than tied max.
1798 for (const auto &TiedPair : TiedRegisterPairs)
1799 MI.tieOperands(TiedPair.first, TiedPair.second);
1800 return false;
1801}
1802
1803bool MIParser::parseRegisterOperand(MachineOperand &Dest,
1804 std::optional<unsigned> &TiedDefIdx,
1805 bool IsDef) {
1806 RegState Flags = getDefRegState(IsDef);
1807 while (Token.isRegisterFlag()) {
1808 if (parseRegisterFlag(Flags))
1809 return true;
1810 }
1811 // Update IsDef as we may have read a def flag.
1812 IsDef = hasRegState(Flags, RegState::Define);
1813 if (!Token.isRegister())
1814 return error("expected a register after register flags");
1815 Register Reg;
1816 VRegInfo *RegInfo;
1817 if (parseRegister(Reg, RegInfo))
1818 return true;
1819 lex();
1820 unsigned SubReg = 0;
1821 if (Token.is(MIToken::dot)) {
1822 if (parseSubRegisterIndex(SubReg))
1823 return true;
1824 if (!Reg.isVirtual())
1825 return error("subregister index expects a virtual register");
1826 }
1827 if (Token.is(MIToken::colon)) {
1828 if (!Reg.isVirtual())
1829 return error("register class specification expects a virtual register");
1830 lex();
1831 if (parseRegisterClassOrBank(*RegInfo))
1832 return true;
1833 }
1834
1835 if (consumeIfPresent(MIToken::lparen)) {
1836 // For a def, we only expect a type. For use we expect either a type or a
1837 // tied-def. Additionally, for physical registers, we don't expect a type.
1838 if (Token.is(MIToken::kw_tied_def)) {
1839 if (IsDef)
1840 return error("tied-def not supported for defs");
1841 unsigned Idx;
1842 if (parseRegisterTiedDefIndex(Idx))
1843 return true;
1844 TiedDefIdx = Idx;
1845 } else {
1846 if (!Reg.isVirtual())
1847 return error("unexpected type on physical register");
1848
1849 LLT Ty;
1850 // If type parsing fails, forwad the parse error for defs.
1851 if (parseLowLevelType(Token.location(), Ty))
1852 return IsDef ? true
1853 : error("expected tied-def or low-level type after '('");
1854
1855 if (expectAndConsume(MIToken::rparen))
1856 return true;
1857
1858 MachineRegisterInfo &MRI = MF.getRegInfo();
1859 if (MRI.getType(Reg).isValid() && MRI.getType(Reg) != Ty)
1860 return error("inconsistent type for generic virtual register");
1861
1862 MRI.setRegClassOrRegBank(Reg, static_cast<RegisterBank *>(nullptr));
1863 MRI.setType(Reg, Ty);
1865 }
1866 } else if (IsDef && Reg.isVirtual()) {
1867 // Generic virtual registers defs must have a type.
1868 if (RegInfo->Kind == VRegInfo::GENERIC ||
1869 RegInfo->Kind == VRegInfo::REGBANK)
1870 return error("generic virtual registers must have a type");
1871 }
1872
1873 if (IsDef) {
1874 if (hasRegState(Flags, RegState::Kill))
1875 return error("cannot have a killed def operand");
1876 } else {
1877 if (hasRegState(Flags, RegState::Dead))
1878 return error("cannot have a dead use operand");
1879 }
1880
1882 Reg, IsDef, hasRegState(Flags, RegState::Implicit),
1885 hasRegState(Flags, RegState::EarlyClobber), SubReg,
1889
1890 return false;
1891}
1892
1893bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
1895 const APSInt &Int = Token.integerValue();
1896 if (auto SImm = Int.trySExtValue(); Int.isSigned() && SImm.has_value())
1897 Dest = MachineOperand::CreateImm(*SImm);
1898 else if (auto UImm = Int.tryZExtValue(); !Int.isSigned() && UImm.has_value())
1899 Dest = MachineOperand::CreateImm(*UImm);
1900 else
1901 return error("integer literal is too large to be an immediate operand");
1902 lex();
1903 return false;
1904}
1905
1906bool MIParser::parseInlineAsmOperand(MachineOperand &Dest) {
1907 // Parse symbolic form: kind[:constraint].
1908 assert(Token.is(MIToken::Identifier) && "expected inline asm operand kind");
1909 StringRef KindStr = Token.stringValue();
1910 constexpr auto InvalidKind = static_cast<InlineAsm::Kind>(0);
1913 .Case("regdef", InlineAsm::Kind::RegDef)
1914 .Case("reguse", InlineAsm::Kind::RegUse)
1916 .Case("clobber", InlineAsm::Kind::Clobber)
1917 .Case("imm", InlineAsm::Kind::Imm)
1918 .Case("mem", InlineAsm::Kind::Mem)
1919 .Default(InvalidKind);
1920 assert(K != InvalidKind && "unknown inline asm operand kind");
1921
1922 lex();
1923
1924 // Create the flag with default of 1 operand.
1925 InlineAsm::Flag F(K, 1);
1926
1927 // Parse optional tiedto constraint: tiedto:$N.
1928 if (Token.is(MIToken::Identifier) && Token.stringValue() == "tiedto") {
1929 lex();
1930 if (Token.isNot(MIToken::colon))
1931 return error("expected ':' after 'tiedto'");
1932 lex();
1933 if (Token.isNot(MIToken::NamedRegister))
1934 return error("expected '$N' operand number after 'tiedto:'");
1935 unsigned OperandNo;
1936 if (Token.stringValue().getAsInteger(10, OperandNo))
1937 return error("invalid operand number in tiedto constraint");
1938 lex();
1939
1940 F.setMatchingOp(OperandNo);
1941
1943 return false;
1944 }
1945
1946 // Parse optional constraint after ':'.
1947 if (Token.isNot(MIToken::colon)) {
1949 return false;
1950 }
1951
1952 lex();
1953
1954 if (Token.isNot(MIToken::Identifier))
1955 return error("expected register class or memory constraint name after ':'");
1956
1957 StringRef ConstraintStr = Token.stringValue();
1958 if (K == InlineAsm::Kind::Mem) {
1991 return error("unknown memory constraint '" + ConstraintStr + "'");
1992 F.setMemConstraint(CC);
1993 } else if (K == InlineAsm::Kind::RegDef || K == InlineAsm::Kind::RegUse ||
1995 const TargetRegisterClass *RC =
1996 PFS.Target.getRegClass(ConstraintStr.lower());
1997 if (!RC)
1998 return error("unknown register class '" + ConstraintStr + "'");
1999 F.setRegClass(RC->getID());
2000 }
2001
2002 lex();
2003
2005 return false;
2006}
2007
2008bool MIParser::parseTargetImmMnemonic(const unsigned OpCode,
2009 const unsigned OpIdx,
2010 MachineOperand &Dest,
2011 const MIRFormatter &MF) {
2012 assert(Token.is(MIToken::dot));
2013 auto Loc = Token.location(); // record start position
2014 size_t Len = 1; // for "."
2015 lex();
2016
2017 // Handle the case that mnemonic starts with number.
2018 if (Token.is(MIToken::IntegerLiteral)) {
2019 Len += Token.range().size();
2020 lex();
2021 }
2022
2023 StringRef Src;
2024 if (Token.is(MIToken::comma))
2025 Src = StringRef(Loc, Len);
2026 else {
2027 assert(Token.is(MIToken::Identifier));
2028 Src = StringRef(Loc, Len + Token.stringValue().size());
2029 }
2030 int64_t Val;
2031 if (MF.parseImmMnemonic(OpCode, OpIdx, Src, Val,
2032 [this](StringRef::iterator Loc, const Twine &Msg)
2033 -> bool { return error(Loc, Msg); }))
2034 return true;
2035
2036 Dest = MachineOperand::CreateImm(Val);
2037 if (!Token.is(MIToken::comma))
2038 lex();
2039 return false;
2040}
2041
2043 PerFunctionMIParsingState &PFS, const Constant *&C,
2044 ErrorCallbackType ErrCB) {
2045 auto Source = StringValue.str(); // The source has to be null terminated.
2046 SMDiagnostic Err;
2047 C = parseConstantValue(Source, Err, *PFS.MF.getFunction().getParent(),
2048 &PFS.IRSlots);
2049 if (!C)
2050 return ErrCB(Loc + Err.getColumnNo(), Err.getMessage());
2051 return false;
2052}
2053
2054bool MIParser::parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
2055 const Constant *&C) {
2056 return ::parseIRConstant(
2057 Loc, StringValue, PFS, C,
2058 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2059 return error(Loc, Msg);
2060 });
2061}
2062
2063bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
2064 if (parseIRConstant(Loc, StringRef(Loc, Token.range().end() - Loc), C))
2065 return true;
2066 lex();
2067 return false;
2068}
2069
2070// See LLT implementation for bit size limits.
2072 return Size != 0 && isUInt<16>(Size);
2073}
2074
2076 return NumElts != 0 && isUInt<16>(NumElts);
2077}
2078
2079static bool verifyAddrSpace(uint64_t AddrSpace) {
2080 return isUInt<24>(AddrSpace);
2081}
2082
2083bool MIParser::parseLowLevelType(StringRef::iterator Loc, LLT &Ty) {
2084 if (Token.range().front() == 's' || Token.range().front() == 'p') {
2085 StringRef SizeStr = Token.range().drop_front();
2086 if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
2087 return error("expected integers after 's'/'p' type character");
2088 }
2089
2090 if (Token.range().front() == 's') {
2091 auto ScalarSize = APSInt(Token.range().drop_front()).getZExtValue();
2092 if (ScalarSize) {
2093 if (!verifyScalarSize(ScalarSize))
2094 return error("invalid size for scalar type");
2095 Ty = LLT::scalar(ScalarSize);
2096 } else {
2097 Ty = LLT::token();
2098 }
2099 lex();
2100 return false;
2101 } else if (Token.range().front() == 'p') {
2102 const DataLayout &DL = MF.getDataLayout();
2103 uint64_t AS = APSInt(Token.range().drop_front()).getZExtValue();
2104 if (!verifyAddrSpace(AS))
2105 return error("invalid address space number");
2106
2107 Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
2108 lex();
2109 return false;
2110 }
2111
2112 // Now we're looking for a vector.
2113 if (Token.isNot(MIToken::less))
2114 return error(Loc, "expected sN, pA, <M x sN>, <M x pA>, <vscale x M x sN>, "
2115 "or <vscale x M x pA> for GlobalISel type");
2116 lex();
2117
2118 bool HasVScale =
2119 Token.is(MIToken::Identifier) && Token.stringValue() == "vscale";
2120 if (HasVScale) {
2121 lex();
2122 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
2123 return error("expected <vscale x M x sN> or <vscale x M x pA>");
2124 lex();
2125 }
2126
2127 auto GetError = [this, &HasVScale, Loc]() {
2128 if (HasVScale)
2129 return error(
2130 Loc, "expected <vscale x M x sN> or <vscale M x pA> for vector type");
2131 return error(Loc, "expected <M x sN> or <M x pA> for vector type");
2132 };
2133
2134 if (Token.isNot(MIToken::IntegerLiteral))
2135 return GetError();
2136 uint64_t NumElements = Token.integerValue().getZExtValue();
2137 if (!verifyVectorElementCount(NumElements))
2138 return error("invalid number of vector elements");
2139
2140 lex();
2141
2142 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
2143 return GetError();
2144 lex();
2145
2146 if (Token.range().front() != 's' && Token.range().front() != 'p')
2147 return GetError();
2148
2149 StringRef SizeStr = Token.range().drop_front();
2150 if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
2151 return error("expected integers after 's'/'p' type character");
2152
2153 if (Token.range().front() == 's') {
2154 auto ScalarSize = APSInt(Token.range().drop_front()).getZExtValue();
2155 if (!verifyScalarSize(ScalarSize))
2156 return error("invalid size for scalar element in vector");
2157 Ty = LLT::scalar(ScalarSize);
2158 } else if (Token.range().front() == 'p') {
2159 const DataLayout &DL = MF.getDataLayout();
2160 uint64_t AS = APSInt(Token.range().drop_front()).getZExtValue();
2161 if (!verifyAddrSpace(AS))
2162 return error("invalid address space number");
2163
2164 Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
2165 } else {
2166 return GetError();
2167 }
2168 lex();
2169
2170 if (Token.isNot(MIToken::greater))
2171 return GetError();
2172
2173 lex();
2174
2175 Ty = LLT::vector(ElementCount::get(NumElements, HasVScale), Ty);
2176 return false;
2177}
2178
2179bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
2180 assert(Token.is(MIToken::Identifier));
2181 StringRef TypeStr = Token.range();
2182 if (TypeStr.front() != 'i' && TypeStr.front() != 's' &&
2183 TypeStr.front() != 'p')
2184 return error(
2185 "a typed immediate operand should start with one of 'i', 's', or 'p'");
2186 StringRef SizeStr = Token.range().drop_front();
2187 if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
2188 return error("expected integers after 'i'/'s'/'p' type character");
2189
2190 auto Loc = Token.location();
2191 lex();
2192 if (Token.isNot(MIToken::IntegerLiteral)) {
2193 if (Token.isNot(MIToken::Identifier) ||
2194 !(Token.range() == "true" || Token.range() == "false"))
2195 return error("expected an integer literal");
2196 }
2197 const Constant *C = nullptr;
2198 if (parseIRConstant(Loc, C))
2199 return true;
2201 return false;
2202}
2203
2204bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
2205 auto Loc = Token.location();
2206 lex();
2207 if (Token.isNot(MIToken::FloatingPointLiteral) &&
2208 Token.isNot(MIToken::HexLiteral))
2209 return error("expected a floating point literal");
2210 const Constant *C = nullptr;
2211 if (parseIRConstant(Loc, C))
2212 return true;
2214 return false;
2215}
2216
2217static bool getHexUint(const MIToken &Token, APInt &Result) {
2219 StringRef S = Token.range();
2220 assert(S[0] == '0' && tolower(S[1]) == 'x');
2221 // This could be a floating point literal with a special prefix.
2222 if (!isxdigit(S[2]))
2223 return true;
2224 StringRef V = S.substr(2);
2225 APInt A(V.size()*4, V, 16);
2226
2227 // If A is 0, then A.getActiveBits() is 0. This isn't a valid bitwidth. Make
2228 // sure it isn't the case before constructing result.
2229 unsigned NumBits = (A == 0) ? 32 : A.getActiveBits();
2230 Result = APInt(NumBits, ArrayRef<uint64_t>(A.getRawData(), A.getNumWords()));
2231 return false;
2232}
2233
2234static bool getUnsigned(const MIToken &Token, unsigned &Result,
2235 ErrorCallbackType ErrCB) {
2236 if (Token.hasIntegerValue()) {
2237 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
2238 const APSInt &SInt = Token.integerValue();
2239 if (SInt.isNegative())
2240 return ErrCB(Token.location(), "expected unsigned integer");
2241 uint64_t Val64 = SInt.getLimitedValue(Limit);
2242 if (Val64 == Limit)
2243 return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2244 Result = Val64;
2245 return false;
2246 }
2247 if (Token.is(MIToken::HexLiteral)) {
2248 APInt A;
2249 if (getHexUint(Token, A))
2250 return true;
2251 if (A.getBitWidth() > 32)
2252 return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2253 Result = A.getZExtValue();
2254 return false;
2255 }
2256 return true;
2257}
2258
2259bool MIParser::getUnsigned(unsigned &Result) {
2260 return ::getUnsigned(
2261 Token, Result, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2262 return error(Loc, Msg);
2263 });
2264}
2265
2266bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
2269 unsigned Number;
2270 if (getUnsigned(Number))
2271 return true;
2272 auto MBBInfo = PFS.MBBSlots.find(Number);
2273 if (MBBInfo == PFS.MBBSlots.end())
2274 return error(Twine("use of undefined machine basic block #") +
2275 Twine(Number));
2276 MBB = MBBInfo->second;
2277 // TODO: Only parse the name if it's a MachineBasicBlockLabel. Deprecate once
2278 // we drop the <irname> from the bb.<id>.<irname> format.
2279 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
2280 return error(Twine("the name of machine basic block #") + Twine(Number) +
2281 " isn't '" + Token.stringValue() + "'");
2282 return false;
2283}
2284
2285bool MIParser::parseMBBOperand(MachineOperand &Dest) {
2288 return true;
2290 lex();
2291 return false;
2292}
2293
2294bool MIParser::parseStackFrameIndex(int &FI) {
2295 assert(Token.is(MIToken::StackObject));
2296 unsigned ID;
2297 if (getUnsigned(ID))
2298 return true;
2299 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
2300 if (ObjectInfo == PFS.StackObjectSlots.end())
2301 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
2302 "'");
2304 if (const auto *Alloca =
2305 MF.getFrameInfo().getObjectAllocation(ObjectInfo->second))
2306 Name = Alloca->getName();
2307 if (!Token.stringValue().empty() && Token.stringValue() != Name)
2308 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
2309 "' isn't '" + Token.stringValue() + "'");
2310 lex();
2311 FI = ObjectInfo->second;
2312 return false;
2313}
2314
2315bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
2316 int FI;
2317 if (parseStackFrameIndex(FI))
2318 return true;
2319 Dest = MachineOperand::CreateFI(FI);
2320 return false;
2321}
2322
2323bool MIParser::parseFixedStackFrameIndex(int &FI) {
2325 unsigned ID;
2326 if (getUnsigned(ID))
2327 return true;
2328 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
2329 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
2330 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
2331 Twine(ID) + "'");
2332 lex();
2333 FI = ObjectInfo->second;
2334 return false;
2335}
2336
2337bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
2338 int FI;
2339 if (parseFixedStackFrameIndex(FI))
2340 return true;
2341 Dest = MachineOperand::CreateFI(FI);
2342 return false;
2343}
2344
2345static bool parseGlobalValue(const MIToken &Token,
2347 ErrorCallbackType ErrCB) {
2348 switch (Token.kind()) {
2350 const Module *M = PFS.MF.getFunction().getParent();
2351 GV = M->getNamedValue(Token.stringValue());
2352 if (!GV)
2353 return ErrCB(Token.location(), Twine("use of undefined global value '") +
2354 Token.range() + "'");
2355 break;
2356 }
2357 case MIToken::GlobalValue: {
2358 unsigned GVIdx;
2359 if (getUnsigned(Token, GVIdx, ErrCB))
2360 return true;
2361 GV = PFS.IRSlots.GlobalValues.get(GVIdx);
2362 if (!GV)
2363 return ErrCB(Token.location(), Twine("use of undefined global value '@") +
2364 Twine(GVIdx) + "'");
2365 break;
2366 }
2367 default:
2368 llvm_unreachable("The current token should be a global value");
2369 }
2370 return false;
2371}
2372
2373bool MIParser::parseGlobalValue(GlobalValue *&GV) {
2374 return ::parseGlobalValue(
2375 Token, PFS, GV,
2376 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2377 return error(Loc, Msg);
2378 });
2379}
2380
2381bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
2382 GlobalValue *GV = nullptr;
2383 if (parseGlobalValue(GV))
2384 return true;
2385 lex();
2386 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
2387 if (parseOperandsOffset(Dest))
2388 return true;
2389 return false;
2390}
2391
2392bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
2394 unsigned ID;
2395 if (getUnsigned(ID))
2396 return true;
2397 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
2398 if (ConstantInfo == PFS.ConstantPoolSlots.end())
2399 return error("use of undefined constant '%const." + Twine(ID) + "'");
2400 lex();
2401 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
2402 if (parseOperandsOffset(Dest))
2403 return true;
2404 return false;
2405}
2406
2407bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
2409 unsigned ID;
2410 if (getUnsigned(ID))
2411 return true;
2412 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
2413 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
2414 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
2415 lex();
2416 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
2417 return false;
2418}
2419
2420bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
2422 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
2423 lex();
2424 Dest = MachineOperand::CreateES(Symbol);
2425 if (parseOperandsOffset(Dest))
2426 return true;
2427 return false;
2428}
2429
2430bool MIParser::parseMCSymbolOperand(MachineOperand &Dest) {
2431 assert(Token.is(MIToken::MCSymbol));
2432 MCSymbol *Symbol = getOrCreateMCSymbol(Token.stringValue());
2433 lex();
2434 Dest = MachineOperand::CreateMCSymbol(Symbol);
2435 if (parseOperandsOffset(Dest))
2436 return true;
2437 return false;
2438}
2439
2440bool MIParser::parseSubRegisterIndexOperand(MachineOperand &Dest) {
2442 StringRef Name = Token.stringValue();
2443 unsigned SubRegIndex = PFS.Target.getSubRegIndex(Token.stringValue());
2444 if (SubRegIndex == 0)
2445 return error(Twine("unknown subregister index '") + Name + "'");
2446 lex();
2447 Dest = MachineOperand::CreateImm(SubRegIndex);
2448 return false;
2449}
2450
2451bool MIParser::parseMDNode(MDNode *&Node) {
2452 assert(Token.is(MIToken::exclaim));
2453
2454 auto Loc = Token.location();
2455 lex();
2456 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
2457 return error("expected metadata id after '!'");
2458 unsigned ID;
2459 if (getUnsigned(ID))
2460 return true;
2461 auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID);
2462 if (NodeInfo == PFS.IRSlots.MetadataNodes.end()) {
2463 NodeInfo = PFS.MachineMetadataNodes.find(ID);
2464 if (NodeInfo == PFS.MachineMetadataNodes.end())
2465 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
2466 }
2467 lex();
2468 Node = NodeInfo->second.get();
2469 return false;
2470}
2471
2472bool MIParser::parseDIExpression(MDNode *&Expr) {
2473 unsigned Read;
2475 CurrentSource, Read, Error, *PFS.MF.getFunction().getParent(),
2476 &PFS.IRSlots);
2477 CurrentSource = CurrentSource.substr(Read);
2478 lex();
2479 if (!Expr)
2480 return error(Error.getMessage());
2481 return false;
2482}
2483
2484bool MIParser::parseDILocation(MDNode *&Loc) {
2485 assert(Token.is(MIToken::md_dilocation));
2486 lex();
2487
2488 bool HaveLine = false;
2489 unsigned Line = 0;
2490 unsigned Column = 0;
2491 MDNode *Scope = nullptr;
2492 MDNode *InlinedAt = nullptr;
2493 bool ImplicitCode = false;
2494 uint64_t AtomGroup = 0;
2495 uint64_t AtomRank = 0;
2496
2497 if (expectAndConsume(MIToken::lparen))
2498 return true;
2499
2500 if (Token.isNot(MIToken::rparen)) {
2501 do {
2502 if (Token.is(MIToken::Identifier)) {
2503 if (Token.stringValue() == "line") {
2504 lex();
2505 if (expectAndConsume(MIToken::colon))
2506 return true;
2507 if (Token.isNot(MIToken::IntegerLiteral) ||
2508 Token.integerValue().isSigned())
2509 return error("expected unsigned integer");
2510 Line = Token.integerValue().getZExtValue();
2511 HaveLine = true;
2512 lex();
2513 continue;
2514 }
2515 if (Token.stringValue() == "column") {
2516 lex();
2517 if (expectAndConsume(MIToken::colon))
2518 return true;
2519 if (Token.isNot(MIToken::IntegerLiteral) ||
2520 Token.integerValue().isSigned())
2521 return error("expected unsigned integer");
2522 Column = Token.integerValue().getZExtValue();
2523 lex();
2524 continue;
2525 }
2526 if (Token.stringValue() == "scope") {
2527 lex();
2528 if (expectAndConsume(MIToken::colon))
2529 return true;
2530 if (parseMDNode(Scope))
2531 return error("expected metadata node");
2532 if (!isa<DIScope>(Scope))
2533 return error("expected DIScope node");
2534 continue;
2535 }
2536 if (Token.stringValue() == "inlinedAt") {
2537 lex();
2538 if (expectAndConsume(MIToken::colon))
2539 return true;
2540 if (Token.is(MIToken::exclaim)) {
2541 if (parseMDNode(InlinedAt))
2542 return true;
2543 } else if (Token.is(MIToken::md_dilocation)) {
2544 if (parseDILocation(InlinedAt))
2545 return true;
2546 } else {
2547 return error("expected metadata node");
2548 }
2549 if (!isa<DILocation>(InlinedAt))
2550 return error("expected DILocation node");
2551 continue;
2552 }
2553 if (Token.stringValue() == "isImplicitCode") {
2554 lex();
2555 if (expectAndConsume(MIToken::colon))
2556 return true;
2557 if (!Token.is(MIToken::Identifier))
2558 return error("expected true/false");
2559 // As far as I can see, we don't have any existing need for parsing
2560 // true/false in MIR yet. Do it ad-hoc until there's something else
2561 // that needs it.
2562 if (Token.stringValue() == "true")
2563 ImplicitCode = true;
2564 else if (Token.stringValue() == "false")
2565 ImplicitCode = false;
2566 else
2567 return error("expected true/false");
2568 lex();
2569 continue;
2570 }
2571 if (Token.stringValue() == "atomGroup") {
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 AtomGroup = Token.integerValue().getZExtValue();
2579 lex();
2580 continue;
2581 }
2582 if (Token.stringValue() == "atomRank") {
2583 lex();
2584 if (expectAndConsume(MIToken::colon))
2585 return true;
2586 if (Token.isNot(MIToken::IntegerLiteral) ||
2587 Token.integerValue().isSigned())
2588 return error("expected unsigned integer");
2589 AtomRank = Token.integerValue().getZExtValue();
2590 lex();
2591 continue;
2592 }
2593 }
2594 return error(Twine("invalid DILocation argument '") +
2595 Token.stringValue() + "'");
2596 } while (consumeIfPresent(MIToken::comma));
2597 }
2598
2599 if (expectAndConsume(MIToken::rparen))
2600 return true;
2601
2602 if (!HaveLine)
2603 return error("DILocation requires line number");
2604 if (!Scope)
2605 return error("DILocation requires a scope");
2606
2607 Loc = DILocation::get(MF.getFunction().getContext(), Line, Column, Scope,
2608 InlinedAt, ImplicitCode, AtomGroup, AtomRank);
2609 return false;
2610}
2611
2612bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
2613 MDNode *Node = nullptr;
2614 if (Token.is(MIToken::exclaim)) {
2615 if (parseMDNode(Node))
2616 return true;
2617 } else if (Token.is(MIToken::md_diexpr)) {
2618 if (parseDIExpression(Node))
2619 return true;
2620 }
2621 Dest = MachineOperand::CreateMetadata(Node);
2622 return false;
2623}
2624
2625bool MIParser::parseCFIOffset(int &Offset) {
2626 if (Token.isNot(MIToken::IntegerLiteral))
2627 return error("expected a cfi offset");
2628 if (Token.integerValue().getSignificantBits() > 32)
2629 return error("expected a 32 bit integer (the cfi offset is too large)");
2630 Offset = (int)Token.integerValue().getExtValue();
2631 lex();
2632 return false;
2633}
2634
2635bool MIParser::parseCFIRegister(unsigned &Reg) {
2636 if (Token.isNot(MIToken::NamedRegister))
2637 return error("expected a cfi register");
2638 Register LLVMReg;
2639 if (parseNamedRegister(LLVMReg))
2640 return true;
2641 const auto *TRI = MF.getSubtarget().getRegisterInfo();
2642 assert(TRI && "Expected target register info");
2643 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
2644 if (DwarfReg < 0)
2645 return error("invalid DWARF register");
2646 Reg = (unsigned)DwarfReg;
2647 lex();
2648 return false;
2649}
2650
2651bool MIParser::parseCFIAddressSpace(unsigned &AddressSpace) {
2652 if (Token.isNot(MIToken::IntegerLiteral))
2653 return error("expected a cfi address space literal");
2654 if (Token.integerValue().isSigned())
2655 return error("expected an unsigned integer (cfi address space)");
2656 AddressSpace = Token.integerValue().getZExtValue();
2657 lex();
2658 return false;
2659}
2660
2661bool MIParser::parseCFIEscapeValues(std::string &Values) {
2662 do {
2663 if (Token.isNot(MIToken::HexLiteral))
2664 return error("expected a hexadecimal literal");
2665 unsigned Value;
2666 if (getUnsigned(Value))
2667 return true;
2668 if (Value > UINT8_MAX)
2669 return error("expected a 8-bit integer (too large)");
2670 Values.push_back(static_cast<uint8_t>(Value));
2671 lex();
2672 } while (consumeIfPresent(MIToken::comma));
2673 return false;
2674}
2675
2676bool MIParser::parseCFIOperand(MachineOperand &Dest) {
2677 auto Kind = Token.kind();
2678 lex();
2679 int Offset;
2680 unsigned Reg;
2681 unsigned AddressSpace;
2682 unsigned CFIIndex;
2683 switch (Kind) {
2685 if (parseCFIRegister(Reg))
2686 return true;
2687 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
2688 break;
2690 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2691 parseCFIOffset(Offset))
2692 return true;
2693 CFIIndex =
2694 MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
2695 break;
2697 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2698 parseCFIOffset(Offset))
2699 return true;
2700 CFIIndex = MF.addFrameInst(
2702 break;
2704 if (parseCFIRegister(Reg))
2705 return true;
2706 CFIIndex =
2707 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
2708 break;
2710 if (parseCFIOffset(Offset))
2711 return true;
2712 CFIIndex =
2713 MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, Offset));
2714 break;
2716 if (parseCFIOffset(Offset))
2717 return true;
2718 CFIIndex = MF.addFrameInst(
2720 break;
2722 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2723 parseCFIOffset(Offset))
2724 return true;
2725 CFIIndex =
2726 MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, Offset));
2727 break;
2729 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2730 parseCFIOffset(Offset) || expectAndConsume(MIToken::comma) ||
2731 parseCFIAddressSpace(AddressSpace))
2732 return true;
2733 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMDefAspaceCfa(
2734 nullptr, Reg, Offset, AddressSpace, SMLoc()));
2735 break;
2737 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRememberState(nullptr));
2738 break;
2740 if (parseCFIRegister(Reg))
2741 return true;
2742 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, Reg));
2743 break;
2745 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestoreState(nullptr));
2746 break;
2748 if (parseCFIRegister(Reg))
2749 return true;
2750 CFIIndex = MF.addFrameInst(MCCFIInstruction::createUndefined(nullptr, Reg));
2751 break;
2753 unsigned Reg2;
2754 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2755 parseCFIRegister(Reg2))
2756 return true;
2757
2758 CFIIndex =
2759 MF.addFrameInst(MCCFIInstruction::createRegister(nullptr, Reg, Reg2));
2760 break;
2761 }
2763 CFIIndex = MF.addFrameInst(MCCFIInstruction::createWindowSave(nullptr));
2764 break;
2766 CFIIndex = MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
2767 break;
2769 CFIIndex =
2770 MF.addFrameInst(MCCFIInstruction::createNegateRAStateWithPC(nullptr));
2771 break;
2773 std::string Values;
2774 if (parseCFIEscapeValues(Values))
2775 return true;
2776 CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(nullptr, Values));
2777 break;
2778 }
2779 default:
2780 // TODO: Parse the other CFI operands.
2781 llvm_unreachable("The current token should be a cfi operand");
2782 }
2783 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
2784 return false;
2785}
2786
2787bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
2788 switch (Token.kind()) {
2789 case MIToken::NamedIRBlock: {
2791 F.getValueSymbolTable()->lookup(Token.stringValue()));
2792 if (!BB)
2793 return error(Twine("use of undefined IR block '") + Token.range() + "'");
2794 break;
2795 }
2796 case MIToken::IRBlock: {
2797 unsigned SlotNumber = 0;
2798 if (getUnsigned(SlotNumber))
2799 return true;
2800 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
2801 if (!BB)
2802 return error(Twine("use of undefined IR block '%ir-block.") +
2803 Twine(SlotNumber) + "'");
2804 break;
2805 }
2806 default:
2807 llvm_unreachable("The current token should be an IR block reference");
2808 }
2809 return false;
2810}
2811
2812bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
2814 lex();
2815 if (expectAndConsume(MIToken::lparen))
2816 return true;
2817 if (Token.isNot(MIToken::GlobalValue) &&
2818 Token.isNot(MIToken::NamedGlobalValue))
2819 return error("expected a global value");
2820 GlobalValue *GV = nullptr;
2821 if (parseGlobalValue(GV))
2822 return true;
2823 auto *F = dyn_cast<Function>(GV);
2824 if (!F)
2825 return error("expected an IR function reference");
2826 lex();
2827 if (expectAndConsume(MIToken::comma))
2828 return true;
2829 BasicBlock *BB = nullptr;
2830 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
2831 return error("expected an IR block reference");
2832 if (parseIRBlock(BB, *F))
2833 return true;
2834 lex();
2835 if (expectAndConsume(MIToken::rparen))
2836 return true;
2837 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
2838 if (parseOperandsOffset(Dest))
2839 return true;
2840 return false;
2841}
2842
2843bool MIParser::parseIntrinsicOperand(MachineOperand &Dest) {
2844 assert(Token.is(MIToken::kw_intrinsic));
2845 lex();
2846 if (expectAndConsume(MIToken::lparen))
2847 return error("expected syntax intrinsic(@llvm.whatever)");
2848
2849 if (Token.isNot(MIToken::NamedGlobalValue))
2850 return error("expected syntax intrinsic(@llvm.whatever)");
2851
2852 std::string Name = std::string(Token.stringValue());
2853 lex();
2854
2855 if (expectAndConsume(MIToken::rparen))
2856 return error("expected ')' to terminate intrinsic name");
2857
2858 // Find out what intrinsic we're dealing with.
2861 return error("unknown intrinsic name");
2863
2864 return false;
2865}
2866
2867bool MIParser::parsePredicateOperand(MachineOperand &Dest) {
2868 assert(Token.is(MIToken::kw_intpred) || Token.is(MIToken::kw_floatpred));
2869 bool IsFloat = Token.is(MIToken::kw_floatpred);
2870 lex();
2871
2872 if (expectAndConsume(MIToken::lparen))
2873 return error("expected syntax intpred(whatever) or floatpred(whatever");
2874
2875 if (Token.isNot(MIToken::Identifier))
2876 return error("whatever");
2877
2878 CmpInst::Predicate Pred;
2879 if (IsFloat) {
2880 Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2881 .Case("false", CmpInst::FCMP_FALSE)
2882 .Case("oeq", CmpInst::FCMP_OEQ)
2883 .Case("ogt", CmpInst::FCMP_OGT)
2884 .Case("oge", CmpInst::FCMP_OGE)
2885 .Case("olt", CmpInst::FCMP_OLT)
2886 .Case("ole", CmpInst::FCMP_OLE)
2887 .Case("one", CmpInst::FCMP_ONE)
2888 .Case("ord", CmpInst::FCMP_ORD)
2889 .Case("uno", CmpInst::FCMP_UNO)
2890 .Case("ueq", CmpInst::FCMP_UEQ)
2891 .Case("ugt", CmpInst::FCMP_UGT)
2892 .Case("uge", CmpInst::FCMP_UGE)
2893 .Case("ult", CmpInst::FCMP_ULT)
2894 .Case("ule", CmpInst::FCMP_ULE)
2895 .Case("une", CmpInst::FCMP_UNE)
2896 .Case("true", CmpInst::FCMP_TRUE)
2898 if (!CmpInst::isFPPredicate(Pred))
2899 return error("invalid floating-point predicate");
2900 } else {
2901 Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2902 .Case("eq", CmpInst::ICMP_EQ)
2903 .Case("ne", CmpInst::ICMP_NE)
2904 .Case("sgt", CmpInst::ICMP_SGT)
2905 .Case("sge", CmpInst::ICMP_SGE)
2906 .Case("slt", CmpInst::ICMP_SLT)
2907 .Case("sle", CmpInst::ICMP_SLE)
2908 .Case("ugt", CmpInst::ICMP_UGT)
2909 .Case("uge", CmpInst::ICMP_UGE)
2910 .Case("ult", CmpInst::ICMP_ULT)
2911 .Case("ule", CmpInst::ICMP_ULE)
2913 if (!CmpInst::isIntPredicate(Pred))
2914 return error("invalid integer predicate");
2915 }
2916
2917 lex();
2919 if (expectAndConsume(MIToken::rparen))
2920 return error("predicate should be terminated by ')'.");
2921
2922 return false;
2923}
2924
2925bool MIParser::parseShuffleMaskOperand(MachineOperand &Dest) {
2927
2928 lex();
2929 if (expectAndConsume(MIToken::lparen))
2930 return error("expected syntax shufflemask(<integer or undef>, ...)");
2931
2932 SmallVector<int, 32> ShufMask;
2933 do {
2934 if (Token.is(MIToken::kw_undef)) {
2935 ShufMask.push_back(-1);
2936 } else if (Token.is(MIToken::IntegerLiteral)) {
2937 const APSInt &Int = Token.integerValue();
2938 ShufMask.push_back(Int.getExtValue());
2939 } else {
2940 return error("expected integer constant");
2941 }
2942
2943 lex();
2944 } while (consumeIfPresent(MIToken::comma));
2945
2946 if (expectAndConsume(MIToken::rparen))
2947 return error("shufflemask should be terminated by ')'.");
2948
2949 if (ShufMask.size() < 2)
2950 return error("shufflemask should have > 1 element");
2951
2952 ArrayRef<int> MaskAlloc = MF.allocateShuffleMask(ShufMask);
2953 Dest = MachineOperand::CreateShuffleMask(MaskAlloc);
2954 return false;
2955}
2956
2957bool MIParser::parseDbgInstrRefOperand(MachineOperand &Dest) {
2959
2960 lex();
2961 if (expectAndConsume(MIToken::lparen))
2962 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
2963
2964 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
2965 return error("expected unsigned integer for instruction index");
2966 uint64_t InstrIdx = Token.integerValue().getZExtValue();
2967 assert(InstrIdx <= std::numeric_limits<unsigned>::max() &&
2968 "Instruction reference's instruction index is too large");
2969 lex();
2970
2971 if (expectAndConsume(MIToken::comma))
2972 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
2973
2974 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
2975 return error("expected unsigned integer for operand index");
2976 uint64_t OpIdx = Token.integerValue().getZExtValue();
2977 assert(OpIdx <= std::numeric_limits<unsigned>::max() &&
2978 "Instruction reference's operand index is too large");
2979 lex();
2980
2981 if (expectAndConsume(MIToken::rparen))
2982 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
2983
2984 Dest = MachineOperand::CreateDbgInstrRef(InstrIdx, OpIdx);
2985 return false;
2986}
2987
2988bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
2990 lex();
2991 if (expectAndConsume(MIToken::lparen))
2992 return true;
2993 if (Token.isNot(MIToken::Identifier))
2994 return error("expected the name of the target index");
2995 int Index = 0;
2996 if (PFS.Target.getTargetIndex(Token.stringValue(), Index))
2997 return error("use of undefined target index '" + Token.stringValue() + "'");
2998 lex();
2999 if (expectAndConsume(MIToken::rparen))
3000 return true;
3001 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
3002 if (parseOperandsOffset(Dest))
3003 return true;
3004 return false;
3005}
3006
3007bool MIParser::parseCustomRegisterMaskOperand(MachineOperand &Dest) {
3008 assert(Token.stringValue() == "CustomRegMask" && "Expected a custom RegMask");
3009 lex();
3010 if (expectAndConsume(MIToken::lparen))
3011 return true;
3012
3013 uint32_t *Mask = MF.allocateRegMask();
3014 do {
3015 if (Token.isNot(MIToken::rparen)) {
3016 if (Token.isNot(MIToken::NamedRegister))
3017 return error("expected a named register");
3018 Register Reg;
3019 if (parseNamedRegister(Reg))
3020 return true;
3021 lex();
3022 Mask[Reg.id() / 32] |= 1U << (Reg.id() % 32);
3023 }
3024
3025 // TODO: Report an error if the same register is used more than once.
3026 } while (consumeIfPresent(MIToken::comma));
3027
3028 if (expectAndConsume(MIToken::rparen))
3029 return true;
3030 Dest = MachineOperand::CreateRegMask(Mask);
3031 return false;
3032}
3033
3034bool MIParser::parseLaneMaskOperand(MachineOperand &Dest) {
3035 assert(Token.is(MIToken::kw_lanemask));
3036
3037 lex();
3038 if (expectAndConsume(MIToken::lparen))
3039 return true;
3040
3041 // Parse lanemask.
3042 if (Token.isNot(MIToken::IntegerLiteral) && Token.isNot(MIToken::HexLiteral))
3043 return error("expected a valid lane mask value");
3044 static_assert(sizeof(LaneBitmask::Type) == sizeof(uint64_t),
3045 "Use correct get-function for lane mask.");
3047 if (getUint64(V))
3048 return true;
3049 LaneBitmask LaneMask(V);
3050 lex();
3051
3052 if (expectAndConsume(MIToken::rparen))
3053 return true;
3054
3055 Dest = MachineOperand::CreateLaneMask(LaneMask);
3056 return false;
3057}
3058
3059bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
3060 assert(Token.is(MIToken::kw_liveout));
3061 uint32_t *Mask = MF.allocateRegMask();
3062 lex();
3063 if (expectAndConsume(MIToken::lparen))
3064 return true;
3065 while (true) {
3066 if (Token.isNot(MIToken::NamedRegister))
3067 return error("expected a named register");
3068 Register Reg;
3069 if (parseNamedRegister(Reg))
3070 return true;
3071 lex();
3072 Mask[Reg.id() / 32] |= 1U << (Reg.id() % 32);
3073 // TODO: Report an error if the same register is used more than once.
3074 if (Token.isNot(MIToken::comma))
3075 break;
3076 lex();
3077 }
3078 if (expectAndConsume(MIToken::rparen))
3079 return true;
3081 return false;
3082}
3083
3084bool MIParser::parseMachineOperand(const unsigned OpCode, const unsigned OpIdx,
3085 MachineOperand &Dest,
3086 std::optional<unsigned> &TiedDefIdx) {
3087 switch (Token.kind()) {
3090 case MIToken::kw_def:
3091 case MIToken::kw_dead:
3092 case MIToken::kw_killed:
3093 case MIToken::kw_undef:
3102 return parseRegisterOperand(Dest, TiedDefIdx);
3104 // TODO: Forbid numeric operands for INLINEASM once the transition to the
3105 // symbolic form is over.
3106 return parseImmediateOperand(Dest);
3107 case MIToken::kw_half:
3108 case MIToken::kw_bfloat:
3109 case MIToken::kw_float:
3110 case MIToken::kw_double:
3112 case MIToken::kw_fp128:
3114 return parseFPImmediateOperand(Dest);
3116 return parseMBBOperand(Dest);
3118 return parseStackObjectOperand(Dest);
3120 return parseFixedStackObjectOperand(Dest);
3123 return parseGlobalAddressOperand(Dest);
3125 return parseConstantPoolIndexOperand(Dest);
3127 return parseJumpTableIndexOperand(Dest);
3129 return parseExternalSymbolOperand(Dest);
3130 case MIToken::MCSymbol:
3131 return parseMCSymbolOperand(Dest);
3133 return parseSubRegisterIndexOperand(Dest);
3134 case MIToken::md_diexpr:
3135 case MIToken::exclaim:
3136 return parseMetadataOperand(Dest);
3154 return parseCFIOperand(Dest);
3156 return parseBlockAddressOperand(Dest);
3158 return parseIntrinsicOperand(Dest);
3160 return parseTargetIndexOperand(Dest);
3162 return parseLaneMaskOperand(Dest);
3164 return parseLiveoutRegisterMaskOperand(Dest);
3167 return parsePredicateOperand(Dest);
3169 return parseShuffleMaskOperand(Dest);
3171 return parseDbgInstrRefOperand(Dest);
3172 case MIToken::Error:
3173 return true;
3174 case MIToken::Identifier: {
3175 StringRef Id = Token.stringValue();
3176 bool IsInlineAsmOperand = (OpCode == TargetOpcode::INLINEASM ||
3177 OpCode == TargetOpcode::INLINEASM_BR) &&
3179 if (IsInlineAsmOperand &&
3180 (Id == "regdef" || Id == "reguse" || Id == "regdef-ec" ||
3181 Id == "clobber" || Id == "imm" || Id == "mem"))
3182 return parseInlineAsmOperand(Dest);
3183 if (const auto *RegMask = PFS.Target.getRegMask(Id)) {
3184 Dest = MachineOperand::CreateRegMask(RegMask);
3185 lex();
3186 break;
3187 } else if (Id == "CustomRegMask") {
3188 return parseCustomRegisterMaskOperand(Dest);
3189 } else {
3190 return parseTypedImmediateOperand(Dest);
3191 }
3192 }
3193 case MIToken::dot: {
3194 const auto *TII = MF.getSubtarget().getInstrInfo();
3195 if (const auto *Formatter = TII->getMIRFormatter()) {
3196 return parseTargetImmMnemonic(OpCode, OpIdx, Dest, *Formatter);
3197 }
3198 [[fallthrough]];
3199 }
3200 default:
3201 // FIXME: Parse the MCSymbol machine operand.
3202 return error("expected a machine operand");
3203 }
3204 return false;
3205}
3206
3207bool MIParser::parseMachineOperandAndTargetFlags(
3208 const unsigned OpCode, const unsigned OpIdx, MachineOperand &Dest,
3209 std::optional<unsigned> &TiedDefIdx) {
3210 unsigned TF = 0;
3211 bool HasTargetFlags = false;
3212 if (Token.is(MIToken::kw_target_flags)) {
3213 HasTargetFlags = true;
3214 lex();
3215 if (expectAndConsume(MIToken::lparen))
3216 return true;
3217 if (Token.isNot(MIToken::Identifier))
3218 return error("expected the name of the target flag");
3219 if (PFS.Target.getDirectTargetFlag(Token.stringValue(), TF)) {
3220 if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), TF))
3221 return error("use of undefined target flag '" + Token.stringValue() +
3222 "'");
3223 }
3224 lex();
3225 while (Token.is(MIToken::comma)) {
3226 lex();
3227 if (Token.isNot(MIToken::Identifier))
3228 return error("expected the name of the target flag");
3229 unsigned BitFlag = 0;
3230 if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), BitFlag))
3231 return error("use of undefined target flag '" + Token.stringValue() +
3232 "'");
3233 // TODO: Report an error when using a duplicate bit target flag.
3234 TF |= BitFlag;
3235 lex();
3236 }
3237 if (expectAndConsume(MIToken::rparen))
3238 return true;
3239 }
3240 auto Loc = Token.location();
3241 if (parseMachineOperand(OpCode, OpIdx, Dest, TiedDefIdx))
3242 return true;
3243 if (!HasTargetFlags)
3244 return false;
3245 if (Dest.isReg())
3246 return error(Loc, "register operands can't have target flags");
3247 Dest.setTargetFlags(TF);
3248 return false;
3249}
3250
3251bool MIParser::parseOffset(int64_t &Offset) {
3252 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
3253 return false;
3254 StringRef Sign = Token.range();
3255 bool IsNegative = Token.is(MIToken::minus);
3256 lex();
3257 if (Token.isNot(MIToken::IntegerLiteral))
3258 return error("expected an integer literal after '" + Sign + "'");
3259 if (Token.integerValue().getSignificantBits() > 64)
3260 return error("expected 64-bit integer (too large)");
3261 Offset = Token.integerValue().getExtValue();
3262 if (IsNegative)
3263 Offset = -Offset;
3264 lex();
3265 return false;
3266}
3267
3268bool MIParser::parseIRBlockAddressTaken(BasicBlock *&BB) {
3270 lex();
3271 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
3272 return error("expected basic block after 'ir_block_address_taken'");
3273
3274 if (parseIRBlock(BB, MF.getFunction()))
3275 return true;
3276
3277 lex();
3278 return false;
3279}
3280
3281bool MIParser::parseAlignment(uint64_t &Alignment) {
3282 assert(Token.is(MIToken::kw_align) || Token.is(MIToken::kw_basealign));
3283 lex();
3284 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3285 return error("expected an integer literal after 'align'");
3286 if (getUint64(Alignment))
3287 return true;
3288 lex();
3289
3290 if (!isPowerOf2_64(Alignment))
3291 return error("expected a power-of-2 literal after 'align'");
3292
3293 return false;
3294}
3295
3296bool MIParser::parseAddrspace(unsigned &Addrspace) {
3297 assert(Token.is(MIToken::kw_addrspace));
3298 lex();
3299 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3300 return error("expected an integer literal after 'addrspace'");
3301 if (getUnsigned(Addrspace))
3302 return true;
3303 lex();
3304 return false;
3305}
3306
3307bool MIParser::parseOperandsOffset(MachineOperand &Op) {
3308 int64_t Offset = 0;
3309 if (parseOffset(Offset))
3310 return true;
3311 Op.setOffset(Offset);
3312 return false;
3313}
3314
3315static bool parseIRValue(const MIToken &Token, PerFunctionMIParsingState &PFS,
3316 const Value *&V, ErrorCallbackType ErrCB) {
3317 switch (Token.kind()) {
3318 case MIToken::NamedIRValue: {
3319 V = PFS.MF.getFunction().getValueSymbolTable()->lookup(Token.stringValue());
3320 break;
3321 }
3322 case MIToken::IRValue: {
3323 unsigned SlotNumber = 0;
3324 if (getUnsigned(Token, SlotNumber, ErrCB))
3325 return true;
3326 V = PFS.getIRValue(SlotNumber);
3327 break;
3328 }
3330 case MIToken::GlobalValue: {
3331 GlobalValue *GV = nullptr;
3332 if (parseGlobalValue(Token, PFS, GV, ErrCB))
3333 return true;
3334 V = GV;
3335 break;
3336 }
3338 const Constant *C = nullptr;
3339 if (parseIRConstant(Token.location(), Token.stringValue(), PFS, C, ErrCB))
3340 return true;
3341 V = C;
3342 break;
3343 }
3345 V = nullptr;
3346 return false;
3347 default:
3348 llvm_unreachable("The current token should be an IR block reference");
3349 }
3350 if (!V)
3351 return ErrCB(Token.location(), Twine("use of undefined IR value '") + Token.range() + "'");
3352 return false;
3353}
3354
3355bool MIParser::parseIRValue(const Value *&V) {
3356 return ::parseIRValue(
3357 Token, PFS, V, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3358 return error(Loc, Msg);
3359 });
3360}
3361
3362bool MIParser::getUint64(uint64_t &Result) {
3363 if (Token.hasIntegerValue()) {
3364 if (Token.integerValue().getActiveBits() > 64)
3365 return error("expected 64-bit integer (too large)");
3366 Result = Token.integerValue().getZExtValue();
3367 return false;
3368 }
3369 if (Token.is(MIToken::HexLiteral)) {
3370 APInt A;
3371 if (getHexUint(A))
3372 return true;
3373 if (A.getBitWidth() > 64)
3374 return error("expected 64-bit integer (too large)");
3375 Result = A.getZExtValue();
3376 return false;
3377 }
3378 return true;
3379}
3380
3381bool MIParser::getHexUint(APInt &Result) {
3382 return ::getHexUint(Token, Result);
3383}
3384
3385bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags &Flags) {
3386 const auto OldFlags = Flags;
3387 switch (Token.kind()) {
3390 break;
3393 break;
3396 break;
3399 break;
3402 if (PFS.Target.getMMOTargetFlag(Token.stringValue(), TF))
3403 return error("use of undefined target MMO flag '" + Token.stringValue() +
3404 "'");
3405 Flags |= TF;
3406 break;
3407 }
3408 default:
3409 llvm_unreachable("The current token should be a memory operand flag");
3410 }
3411 if (OldFlags == Flags)
3412 // We know that the same flag is specified more than once when the flags
3413 // weren't modified.
3414 return error("duplicate '" + Token.stringValue() + "' memory operand flag");
3415 lex();
3416 return false;
3417}
3418
3419bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
3420 switch (Token.kind()) {
3421 case MIToken::kw_stack:
3422 PSV = MF.getPSVManager().getStack();
3423 break;
3424 case MIToken::kw_got:
3425 PSV = MF.getPSVManager().getGOT();
3426 break;
3428 PSV = MF.getPSVManager().getJumpTable();
3429 break;
3431 PSV = MF.getPSVManager().getConstantPool();
3432 break;
3434 int FI;
3435 if (parseFixedStackFrameIndex(FI))
3436 return true;
3437 PSV = MF.getPSVManager().getFixedStack(FI);
3438 // The token was already consumed, so use return here instead of break.
3439 return false;
3440 }
3441 case MIToken::StackObject: {
3442 int FI;
3443 if (parseStackFrameIndex(FI))
3444 return true;
3445 PSV = MF.getPSVManager().getFixedStack(FI);
3446 // The token was already consumed, so use return here instead of break.
3447 return false;
3448 }
3450 lex();
3451 switch (Token.kind()) {
3454 GlobalValue *GV = nullptr;
3455 if (parseGlobalValue(GV))
3456 return true;
3457 PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
3458 break;
3459 }
3461 PSV = MF.getPSVManager().getExternalSymbolCallEntry(
3462 MF.createExternalSymbolName(Token.stringValue()));
3463 break;
3464 default:
3465 return error(
3466 "expected a global value or an external symbol after 'call-entry'");
3467 }
3468 break;
3469 case MIToken::kw_custom: {
3470 lex();
3471 const auto *TII = MF.getSubtarget().getInstrInfo();
3472 if (const auto *Formatter = TII->getMIRFormatter()) {
3473 if (Formatter->parseCustomPseudoSourceValue(
3474 Token.stringValue(), MF, PFS, PSV,
3475 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3476 return error(Loc, Msg);
3477 }))
3478 return true;
3479 } else {
3480 return error("unable to parse target custom pseudo source value");
3481 }
3482 break;
3483 }
3484 default:
3485 llvm_unreachable("The current token should be pseudo source value");
3486 }
3487 lex();
3488 return false;
3489}
3490
3491bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
3492 if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
3493 Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
3494 Token.is(MIToken::FixedStackObject) || Token.is(MIToken::StackObject) ||
3495 Token.is(MIToken::kw_call_entry) || Token.is(MIToken::kw_custom)) {
3496 const PseudoSourceValue *PSV = nullptr;
3497 if (parseMemoryPseudoSourceValue(PSV))
3498 return true;
3499 int64_t Offset = 0;
3500 if (parseOffset(Offset))
3501 return true;
3502 Dest = MachinePointerInfo(PSV, Offset);
3503 return false;
3504 }
3505 if (Token.isNot(MIToken::NamedIRValue) && Token.isNot(MIToken::IRValue) &&
3506 Token.isNot(MIToken::GlobalValue) &&
3507 Token.isNot(MIToken::NamedGlobalValue) &&
3508 Token.isNot(MIToken::QuotedIRValue) &&
3509 Token.isNot(MIToken::kw_unknown_address))
3510 return error("expected an IR value reference");
3511 const Value *V = nullptr;
3512 if (parseIRValue(V))
3513 return true;
3514 if (V && !V->getType()->isPointerTy())
3515 return error("expected a pointer IR value");
3516 lex();
3517 int64_t Offset = 0;
3518 if (parseOffset(Offset))
3519 return true;
3520 Dest = MachinePointerInfo(V, Offset);
3521 return false;
3522}
3523
3524bool MIParser::parseOptionalScope(LLVMContext &Context,
3525 SyncScope::ID &SSID) {
3526 SSID = SyncScope::System;
3527 if (Token.is(MIToken::Identifier) && Token.stringValue() == "syncscope") {
3528 lex();
3529 if (expectAndConsume(MIToken::lparen))
3530 return error("expected '(' in syncscope");
3531
3532 std::string SSN;
3533 if (parseStringConstant(SSN))
3534 return true;
3535
3536 SSID = Context.getOrInsertSyncScopeID(SSN);
3537 if (expectAndConsume(MIToken::rparen))
3538 return error("expected ')' in syncscope");
3539 }
3540
3541 return false;
3542}
3543
3544bool MIParser::parseOptionalAtomicOrdering(AtomicOrdering &Order) {
3546 if (Token.isNot(MIToken::Identifier))
3547 return false;
3548
3549 Order = StringSwitch<AtomicOrdering>(Token.stringValue())
3550 .Case("unordered", AtomicOrdering::Unordered)
3551 .Case("monotonic", AtomicOrdering::Monotonic)
3552 .Case("acquire", AtomicOrdering::Acquire)
3553 .Case("release", AtomicOrdering::Release)
3557
3558 if (Order != AtomicOrdering::NotAtomic) {
3559 lex();
3560 return false;
3561 }
3562
3563 return error("expected an atomic scope, ordering or a size specification");
3564}
3565
3566bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
3567 if (expectAndConsume(MIToken::lparen))
3568 return true;
3570 while (Token.isMemoryOperandFlag()) {
3571 if (parseMemoryOperandFlag(Flags))
3572 return true;
3573 }
3574 if (Token.isNot(MIToken::Identifier) ||
3575 (Token.stringValue() != "load" && Token.stringValue() != "store"))
3576 return error("expected 'load' or 'store' memory operation");
3577 if (Token.stringValue() == "load")
3579 else
3581 lex();
3582
3583 // Optional 'store' for operands that both load and store.
3584 if (Token.is(MIToken::Identifier) && Token.stringValue() == "store") {
3586 lex();
3587 }
3588
3589 // Optional synchronization scope.
3590 SyncScope::ID SSID;
3591 if (parseOptionalScope(MF.getFunction().getContext(), SSID))
3592 return true;
3593
3594 // Up to two atomic orderings (cmpxchg provides guarantees on failure).
3595 AtomicOrdering Order, FailureOrder;
3596 if (parseOptionalAtomicOrdering(Order))
3597 return true;
3598
3599 if (parseOptionalAtomicOrdering(FailureOrder))
3600 return true;
3601
3602 if (Token.isNot(MIToken::IntegerLiteral) &&
3603 Token.isNot(MIToken::kw_unknown_size) &&
3604 Token.isNot(MIToken::lparen))
3605 return error("expected memory LLT, the size integer literal or 'unknown-size' after "
3606 "memory operation");
3607
3609 if (Token.is(MIToken::IntegerLiteral)) {
3610 uint64_t Size;
3611 if (getUint64(Size))
3612 return true;
3613
3614 // Convert from bytes to bits for storage.
3616 lex();
3617 } else if (Token.is(MIToken::kw_unknown_size)) {
3618 lex();
3619 } else {
3620 if (expectAndConsume(MIToken::lparen))
3621 return true;
3622 if (parseLowLevelType(Token.location(), MemoryType))
3623 return true;
3624 if (expectAndConsume(MIToken::rparen))
3625 return true;
3626 }
3627
3629 if (Token.is(MIToken::Identifier)) {
3630 const char *Word =
3633 ? "on"
3634 : Flags & MachineMemOperand::MOLoad ? "from" : "into";
3635 if (Token.stringValue() != Word)
3636 return error(Twine("expected '") + Word + "'");
3637 lex();
3638
3639 if (parseMachinePointerInfo(Ptr))
3640 return true;
3641 }
3642 uint64_t BaseAlignment =
3643 MemoryType.isValid()
3644 ? PowerOf2Ceil(MemoryType.getSizeInBytes().getKnownMinValue())
3645 : 1;
3646 AAMDNodes AAInfo;
3647 MDNode *Range = nullptr;
3648 while (consumeIfPresent(MIToken::comma)) {
3649 switch (Token.kind()) {
3650 case MIToken::kw_align: {
3651 // align is printed if it is different than size.
3652 uint64_t Alignment;
3653 if (parseAlignment(Alignment))
3654 return true;
3655 if (Ptr.Offset & (Alignment - 1)) {
3656 // MachineMemOperand::getAlign never returns a value greater than the
3657 // alignment of offset, so this just guards against hand-written MIR
3658 // that specifies a large "align" value when it should probably use
3659 // "basealign" instead.
3660 return error("specified alignment is more aligned than offset");
3661 }
3662 BaseAlignment = Alignment;
3663 break;
3664 }
3666 // basealign is printed if it is different than align.
3667 if (parseAlignment(BaseAlignment))
3668 return true;
3669 break;
3671 if (parseAddrspace(Ptr.AddrSpace))
3672 return true;
3673 break;
3674 case MIToken::md_tbaa:
3675 lex();
3676 if (parseMDNode(AAInfo.TBAA))
3677 return true;
3678 break;
3680 lex();
3681 if (parseMDNode(AAInfo.Scope))
3682 return true;
3683 break;
3685 lex();
3686 if (parseMDNode(AAInfo.NoAlias))
3687 return true;
3688 break;
3690 lex();
3691 if (parseMDNode(AAInfo.NoAliasAddrSpace))
3692 return true;
3693 break;
3694 case MIToken::md_range:
3695 lex();
3696 if (parseMDNode(Range))
3697 return true;
3698 break;
3699 // TODO: Report an error on duplicate metadata nodes.
3700 default:
3701 return error("expected 'align' or '!tbaa' or '!alias.scope' or "
3702 "'!noalias' or '!range' or '!noalias.addrspace'");
3703 }
3704 }
3705 if (expectAndConsume(MIToken::rparen))
3706 return true;
3707 Dest = MF.getMachineMemOperand(Ptr, Flags, MemoryType, Align(BaseAlignment),
3708 AAInfo, Range, SSID, Order, FailureOrder);
3709 return false;
3710}
3711
3712bool MIParser::parsePreOrPostInstrSymbol(MCSymbol *&Symbol) {
3714 Token.is(MIToken::kw_post_instr_symbol)) &&
3715 "Invalid token for a pre- post-instruction symbol!");
3716 lex();
3717 if (Token.isNot(MIToken::MCSymbol))
3718 return error("expected a symbol after 'pre-instr-symbol'");
3719 Symbol = getOrCreateMCSymbol(Token.stringValue());
3720 lex();
3721 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3722 Token.is(MIToken::lbrace))
3723 return false;
3724 if (Token.isNot(MIToken::comma))
3725 return error("expected ',' before the next machine operand");
3726 lex();
3727 return false;
3728}
3729
3730bool MIParser::parseHeapAllocMarker(MDNode *&Node) {
3732 "Invalid token for a heap alloc marker!");
3733 lex();
3734 if (parseMDNode(Node))
3735 return true;
3736 if (!Node)
3737 return error("expected a MDNode after 'heap-alloc-marker'");
3738 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3739 Token.is(MIToken::lbrace))
3740 return false;
3741 if (Token.isNot(MIToken::comma))
3742 return error("expected ',' before the next machine operand");
3743 lex();
3744 return false;
3745}
3746
3747bool MIParser::parsePCSections(MDNode *&Node) {
3748 assert(Token.is(MIToken::kw_pcsections) &&
3749 "Invalid token for a PC sections!");
3750 lex();
3751 if (parseMDNode(Node))
3752 return true;
3753 if (!Node)
3754 return error("expected a MDNode after 'pcsections'");
3755 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3756 Token.is(MIToken::lbrace))
3757 return false;
3758 if (Token.isNot(MIToken::comma))
3759 return error("expected ',' before the next machine operand");
3760 lex();
3761 return false;
3762}
3763
3764bool MIParser::parseMMRA(MDNode *&Node) {
3765 assert(Token.is(MIToken::kw_mmra) && "Invalid token for MMRA!");
3766 lex();
3767 if (parseMDNode(Node))
3768 return true;
3769 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3770 Token.is(MIToken::lbrace))
3771 return false;
3772 if (Token.isNot(MIToken::comma))
3773 return error("expected ',' before the next machine operand");
3774 lex();
3775 return false;
3776}
3777
3779 const Function &F,
3780 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3781 ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
3783 for (const auto &BB : F) {
3784 if (BB.hasName())
3785 continue;
3786 int Slot = MST.getLocalSlot(&BB);
3787 if (Slot == -1)
3788 continue;
3789 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
3790 }
3791}
3792
3794 unsigned Slot,
3795 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3796 return Slots2BasicBlocks.lookup(Slot);
3797}
3798
3799const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
3800 if (Slots2BasicBlocks.empty())
3801 initSlots2BasicBlocks(MF.getFunction(), Slots2BasicBlocks);
3802 return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
3803}
3804
3805const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
3806 if (&F == &MF.getFunction())
3807 return getIRBlock(Slot);
3808 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
3809 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
3810 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
3811}
3812
3813MCSymbol *MIParser::getOrCreateMCSymbol(StringRef Name) {
3814 // FIXME: Currently we can't recognize temporary or local symbols and call all
3815 // of the appropriate forms to create them. However, this handles basic cases
3816 // well as most of the special aspects are recognized by a prefix on their
3817 // name, and the input names should already be unique. For test cases, keeping
3818 // the symbol name out of the symbol table isn't terribly important.
3819 return MF.getContext().getOrCreateSymbol(Name);
3820}
3821
3822bool MIParser::parseStringConstant(std::string &Result) {
3823 if (Token.isNot(MIToken::StringConstant))
3824 return error("expected string constant");
3825 Result = std::string(Token.stringValue());
3826 lex();
3827 return false;
3828}
3829
3831 StringRef Src,
3833 return MIParser(PFS, Error, Src).parseBasicBlockDefinitions(PFS.MBBSlots);
3834}
3835
3838 return MIParser(PFS, Error, Src).parseBasicBlocks();
3839}
3840
3844 return MIParser(PFS, Error, Src).parseStandaloneMBB(MBB);
3845}
3846
3848 Register &Reg, StringRef Src,
3850 return MIParser(PFS, Error, Src).parseStandaloneRegister(Reg);
3851}
3852
3854 Register &Reg, StringRef Src,
3856 return MIParser(PFS, Error, Src).parseStandaloneNamedRegister(Reg);
3857}
3858
3860 VRegInfo *&Info, StringRef Src,
3862 return MIParser(PFS, Error, Src).parseStandaloneVirtualRegister(Info);
3863}
3864
3867 return MIParser(PFS, Error, Src).parseStandaloneStackObject(FI);
3868}
3869
3873 return MIParser(PFS, Error, Src).parsePrefetchTarget(Target);
3874}
3877 return MIParser(PFS, Error, Src).parseStandaloneMDNode(Node);
3878}
3879
3881 SMRange SrcRange, SMDiagnostic &Error) {
3882 return MIParser(PFS, Error, Src, SrcRange).parseMachineMetadata();
3883}
3884
3886 PerFunctionMIParsingState &PFS, const Value *&V,
3887 ErrorCallbackType ErrorCallback) {
3888 MIToken Token;
3889 Src = lexMIToken(Src, Token, [&](StringRef::iterator Loc, const Twine &Msg) {
3890 ErrorCallback(Loc, Msg);
3891 });
3892 V = nullptr;
3893
3894 return ::parseIRValue(Token, PFS, V, ErrorCallback);
3895}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
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.
basic Basic Alias true
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...
dxil translate DXIL Translate Metadata
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(DataExtractor &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 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 bool verifyVectorElementCount(uint64_t NumElts)
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:627
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
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file contains the declarations for metadata subclasses.
#define T
MachineInstr unsigned OpIdx
static constexpr unsigned SM(unsigned Version)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash, uint32_t &Attributes)
Parse Input that contains metadata.
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:1555
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:476
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
bool isNegative() const
Determine sign of this APSInt.
Definition APSInt.h:50
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & back() const
back - Get the last element.
Definition ArrayRef.h:151
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
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 BranchProbability getRaw(uint32_t N)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:679
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:693
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:691
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:680
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:681
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:700
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:690
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:684
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:687
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:688
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:683
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:685
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:704
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:692
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:689
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:678
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:686
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:770
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:776
This is an important base class in LLVM.
Definition Constant.h:43
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:123
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:205
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:241
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:315
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:817
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).
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static MCCFIInstruction createDefCfaRegister(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_def_cfa_register modifies a rule for computing CFA.
Definition MCDwarf.h:583
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:664
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:657
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:608
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:633
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:576
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:618
static MCCFIInstruction createNegateRAStateWithPC(MCSymbol *L, SMLoc Loc={})
.cfi_negate_ra_state_with_pc AArch64 negate RA state with PC.
Definition MCDwarf.h:649
static MCCFIInstruction createNegateRAState(MCSymbol *L, SMLoc Loc={})
.cfi_negate_ra_state AArch64 negate RA state.
Definition MCDwarf.h:644
static MCCFIInstruction createRememberState(MCSymbol *L, SMLoc Loc={})
.cfi_remember_state Save all current rules for all registers.
Definition MCDwarf.h:677
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition MCDwarf.h:591
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:688
static MCCFIInstruction createWindowSave(MCSymbol *L, SMLoc Loc={})
.cfi_window_save SPARC register window is saved.
Definition MCDwarf.h:639
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:599
static MCCFIInstruction createRestoreState(MCSymbol *L, SMLoc Loc={})
.cfi_restore_state Restore the previously saved state.
Definition MCDwarf.h:682
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:671
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:626
Describe properties that are true of each instruction in the target description file.
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:1080
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1572
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1540
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1529
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1549
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.
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 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 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 Register createIncompleteVirtualRegister(StringRef Name="")
Creates a new virtual register that has no register class, register bank or size assigned yet.
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
Root of the metadata hierarchy.
Definition Metadata.h:64
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:67
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:297
Represents a location in source code.
Definition SMLoc.h:22
static SMLoc getFromPointer(const char *Ptr)
Definition SMLoc.h:35
Represents a range in source code.
Definition SMLoc.h:47
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
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:37
bool empty() const
Definition StringMap.h:108
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition StringMap.h:321
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:730
const char * iterator
Definition StringRef.h:59
std::string str() const
str - 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:591
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:629
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:143
char front() const
front - Get the first character in the string.
Definition StringRef.h:146
LLVM_ABI std::string lower() const
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
unsigned getID() const
Return the register class ID number.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
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:262
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
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.
Definition Types.h:26
@ Offset
Definition DWP.cpp:532
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
bool parseStackObjectReference(PerFunctionMIParsingState &PFS, int &FI, StringRef Src, SMDiagnostic &Error)
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:1739
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:284
bool parseMachineBasicBlockDefinitions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine basic block definitions, and skip the machine instructions.
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...
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:385
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:236
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:189
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)
bool parseMachineInstructions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine instructions.
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:195
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool parseMachineMetadata(PerFunctionMIParsingState &PFS, StringRef Src, SMRange SourceRange, SMDiagnostic &Error)
bool parseVirtualRegisterReference(PerFunctionMIParsingState &PFS, VRegInfo *&Info, StringRef Src, SMDiagnostic &Error)
bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:763
MDNode * NoAliasAddrSpace
The tag specifying the noalias address spaces.
Definition Metadata.h:792
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:786
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:780
MDNode * NoAlias
The tag specifying the noalias scope.
Definition Metadata.h:789
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:210
bool hasIntegerValue() const
Definition MILexer.h:250
bool is(TokenKind K) const
Definition MILexer.h:237
StringRef stringValue() const
Return the token's string value.
Definition MILexer.h:246
@ kw_pre_instr_symbol
Definition MILexer.h:136
@ kw_deactivation_symbol
Definition MILexer.h:141
@ kw_call_frame_size
Definition MILexer.h:148
@ kw_cfi_aarch64_negate_ra_sign_state
Definition MILexer.h:100
@ kw_cfi_llvm_def_aspace_cfa
Definition MILexer.h:93
@ MachineBasicBlock
Definition MILexer.h:169
@ kw_dbg_instr_ref
Definition MILexer.h:84
@ NamedVirtualRegister
Definition MILexer.h:167
@ kw_early_clobber
Definition MILexer.h:59
@ kw_unpredictable
Definition MILexer.h:77
@ FloatingPointLiteral
Definition MILexer.h:179
@ kw_cfi_window_save
Definition MILexer.h:99
@ kw_frame_destroy
Definition MILexer.h:64
@ kw_cfi_undefined
Definition MILexer.h:98
@ MachineBasicBlockLabel
Definition MILexer.h:168
@ kw_cfi_register
Definition MILexer.h:94
@ kw_inlineasm_br_indirect_target
Definition MILexer.h:128
@ kw_cfi_rel_offset
Definition MILexer.h:87
@ kw_ehfunclet_entry
Definition MILexer.h:130
@ kw_cfi_aarch64_negate_ra_sign_state_with_pc
Definition MILexer.h:101
@ kw_cfi_def_cfa_register
Definition MILexer.h:88
@ kw_cfi_same_value
Definition MILexer.h:85
@ kw_cfi_adjust_cfa_offset
Definition MILexer.h:90
@ kw_dereferenceable
Definition MILexer.h:55
@ kw_implicit_define
Definition MILexer.h:52
@ kw_cfi_def_cfa_offset
Definition MILexer.h:89
@ kw_machine_block_address_taken
Definition MILexer.h:147
@ kw_cfi_remember_state
Definition MILexer.h:95
@ kw_debug_instr_number
Definition MILexer.h:83
@ kw_post_instr_symbol
Definition MILexer.h:137
@ kw_cfi_restore_state
Definition MILexer.h:97
@ kw_ir_block_address_taken
Definition MILexer.h:146
@ kw_unknown_address
Definition MILexer.h:145
@ md_noalias_addrspace
Definition MILexer.h:159
@ kw_debug_location
Definition MILexer.h:82
@ kw_heap_alloc_marker
Definition MILexer.h:138
StringRef range() const
Definition MILexer.h:243
StringRef::iterator location() const
Definition MILexer.h:241
const APSInt & integerValue() const
Definition MILexer.h:248
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*.
VRegInfo & getVRegInfo(Register Num)
Definition MIParser.cpp:329
const SlotMapping & IRSlots
Definition MIParser.h:170
const Value * getIRValue(unsigned Slot)
Definition MIParser.cpp:374
DenseMap< unsigned, MachineBasicBlock * > MBBSlots
Definition MIParser.h:176
StringMap< VRegInfo * > VRegInfosNamed
Definition MIParser.h:178
DenseMap< unsigned, const Value * > Slots2Values
Maps from slot numbers to function's unnamed values.
Definition MIParser.h:185
PerFunctionMIParsingState(MachineFunction &MF, SourceMgr &SM, const SlotMapping &IRSlots, PerTargetMIParsingState &Target)
Definition MIParser.cpp:324
PerTargetMIParsingState & Target
Definition MIParser.h:171
DenseMap< Register, VRegInfo * > VRegInfos
Definition MIParser.h:177
VRegInfo & getVRegInfoNamed(StringRef RegName)
Definition MIParser.cpp:340
bool getVRegFlagValue(StringRef FlagName, uint8_t &FlagValue) const
Definition MIParser.cpp:129
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
const RegisterBank * getRegBank(StringRef Name)
Check if the given identifier is a name of a register bank.
Definition MIParser.cpp:317
bool parseInstrName(StringRef InstrName, unsigned &OpCode)
Try to convert an instruction name to an opcode.
Definition MIParser.cpp:148
unsigned getSubRegIndex(StringRef Name)
Check if the given identifier is a name of a subregister index.
Definition MIParser.cpp:188
bool getTargetIndex(StringRef Name, int &Index)
Try to convert a name of target index to the corresponding target index.
Definition MIParser.cpp:206
void setTarget(const TargetSubtargetInfo &NewSubtarget)
Definition MIParser.cpp:81
bool getRegisterByName(StringRef RegName, Register &Reg)
Try to convert a register name to a register number.
Definition MIParser.cpp:119
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
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
const TargetRegisterClass * getRegClass(StringRef Name)
Check if the given identifier is a name of a register class.
Definition MIParser.cpp:310
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:45
union llvm::VRegInfo::@127225073067155374133234315364317264041071000132 D
const TargetRegisterClass * RC
Definition MIParser.h:44
enum llvm::VRegInfo::@374354327266250320012227113300214031244227062232 Kind
Register VReg
Definition MIParser.h:47
bool Explicit
VReg was explicitly specified in the .mir file.
Definition MIParser.h:42