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 parseSymbolicInlineAsmOperand(unsigned OpIdx, 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::parseSymbolicInlineAsmOperand(unsigned OpIdx,
1907 MachineOperand &Dest) {
1909 assert(Token.is(MIToken::Identifier) &&
1910 "expected symbolic inline asm operand");
1911
1912 // Parse ExtraInfo flags.
1914 unsigned ExtraInfo = 0;
1915 for (;;) {
1916 if (Token.isNot(MIToken::Identifier))
1917 break;
1918
1919 StringRef FlagName = Token.stringValue();
1920 unsigned Flag = StringSwitch<unsigned>(FlagName)
1922 .Case("mayload", InlineAsm::Extra_MayLoad)
1923 .Case("maystore", InlineAsm::Extra_MayStore)
1924 .Case("isconvergent", InlineAsm::Extra_IsConvergent)
1925 .Case("alignstack", InlineAsm::Extra_IsAlignStack)
1927 .Case("attdialect", 0)
1928 .Case("inteldialect", InlineAsm::Extra_AsmDialect)
1929 .Default(~0u);
1930 if (Flag == ~0u)
1931 return error("unknown inline asm extra info flag '" + FlagName + "'");
1932
1933 ExtraInfo |= Flag;
1934 lex();
1935 }
1936
1937 Dest = MachineOperand::CreateImm(ExtraInfo);
1938 return false;
1939 }
1940
1941 // Parse symbolic form: kind[:constraint].
1942 StringRef KindStr = Token.stringValue();
1943 constexpr auto InvalidKind = static_cast<InlineAsm::Kind>(0);
1946 .Case("regdef", InlineAsm::Kind::RegDef)
1947 .Case("reguse", InlineAsm::Kind::RegUse)
1949 .Case("clobber", InlineAsm::Kind::Clobber)
1950 .Case("imm", InlineAsm::Kind::Imm)
1951 .Case("mem", InlineAsm::Kind::Mem)
1952 .Default(InvalidKind);
1953 if (K == InvalidKind)
1954 return error("unknown inline asm operand kind '" + KindStr + "'");
1955
1956 lex();
1957
1958 // Create the flag with default of 1 operand.
1959 InlineAsm::Flag F(K, 1);
1960
1961 // Parse optional tiedto constraint: tiedto:$N.
1962 if (Token.is(MIToken::Identifier) && Token.stringValue() == "tiedto") {
1963 lex();
1964 if (Token.isNot(MIToken::colon))
1965 return error("expected ':' after 'tiedto'");
1966 lex();
1967 if (Token.isNot(MIToken::NamedRegister))
1968 return error("expected '$N' operand number after 'tiedto:'");
1969 unsigned OperandNo;
1970 if (Token.stringValue().getAsInteger(10, OperandNo))
1971 return error("invalid operand number in tiedto constraint");
1972 lex();
1973
1974 F.setMatchingOp(OperandNo);
1975
1977 return false;
1978 }
1979
1980 // Parse optional constraint after ':'.
1981 if (Token.isNot(MIToken::colon)) {
1983 return false;
1984 }
1985
1986 lex();
1987
1988 if (Token.isNot(MIToken::Identifier))
1989 return error("expected register class or memory constraint name after ':'");
1990
1991 StringRef ConstraintStr = Token.stringValue();
1992 if (K == InlineAsm::Kind::Mem) {
2025 return error("unknown memory constraint '" + ConstraintStr + "'");
2026 F.setMemConstraint(CC);
2027 } else if (K == InlineAsm::Kind::RegDef || K == InlineAsm::Kind::RegUse ||
2029 const TargetRegisterClass *RC =
2030 PFS.Target.getRegClass(ConstraintStr.lower());
2031 if (!RC)
2032 return error("unknown register class '" + ConstraintStr + "'");
2033 F.setRegClass(RC->getID());
2034 }
2035
2036 lex();
2037
2039 return false;
2040}
2041
2042bool MIParser::parseTargetImmMnemonic(const unsigned OpCode,
2043 const unsigned OpIdx,
2044 MachineOperand &Dest,
2045 const MIRFormatter &MF) {
2046 assert(Token.is(MIToken::dot));
2047 auto Loc = Token.location(); // record start position
2048 size_t Len = 1; // for "."
2049 lex();
2050
2051 // Handle the case that mnemonic starts with number.
2052 if (Token.is(MIToken::IntegerLiteral)) {
2053 Len += Token.range().size();
2054 lex();
2055 }
2056
2057 StringRef Src;
2058 if (Token.is(MIToken::comma))
2059 Src = StringRef(Loc, Len);
2060 else {
2061 assert(Token.is(MIToken::Identifier));
2062 Src = StringRef(Loc, Len + Token.stringValue().size());
2063 }
2064 int64_t Val;
2065 if (MF.parseImmMnemonic(OpCode, OpIdx, Src, Val,
2066 [this](StringRef::iterator Loc, const Twine &Msg)
2067 -> bool { return error(Loc, Msg); }))
2068 return true;
2069
2070 Dest = MachineOperand::CreateImm(Val);
2071 if (!Token.is(MIToken::comma))
2072 lex();
2073 return false;
2074}
2075
2077 PerFunctionMIParsingState &PFS, const Constant *&C,
2078 ErrorCallbackType ErrCB) {
2079 auto Source = StringValue.str(); // The source has to be null terminated.
2080 SMDiagnostic Err;
2081 C = parseConstantValue(Source, Err, *PFS.MF.getFunction().getParent(),
2082 &PFS.IRSlots);
2083 if (!C)
2084 return ErrCB(Loc + Err.getColumnNo(), Err.getMessage());
2085 return false;
2086}
2087
2088bool MIParser::parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
2089 const Constant *&C) {
2090 return ::parseIRConstant(
2091 Loc, StringValue, PFS, C,
2092 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2093 return error(Loc, Msg);
2094 });
2095}
2096
2097bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
2098 if (parseIRConstant(Loc, StringRef(Loc, Token.range().end() - Loc), C))
2099 return true;
2100 lex();
2101 return false;
2102}
2103
2104// See LLT implementation for bit size limits.
2106 return Size != 0 && isUInt<16>(Size);
2107}
2108
2110 return NumElts != 0 && isUInt<16>(NumElts);
2111}
2112
2113static bool verifyAddrSpace(uint64_t AddrSpace) {
2114 return isUInt<24>(AddrSpace);
2115}
2116
2117bool MIParser::parseLowLevelType(StringRef::iterator Loc, LLT &Ty) {
2118 StringRef TypeDigits = Token.range();
2119 if (TypeDigits.consume_front("s") || TypeDigits.consume_front("i") ||
2120 TypeDigits.consume_front("f") || TypeDigits.consume_front("p") ||
2121 TypeDigits.consume_front("bf")) {
2122 if (TypeDigits.empty() || !llvm::all_of(TypeDigits, isdigit))
2123 return error(
2124 "expected integers after 's'/'i'/'f'/'bf'/'p' type identifier");
2125 }
2126
2127 bool Scalar = Token.range().starts_with("s");
2128 if (Scalar || Token.range().starts_with("i")) {
2129 auto ScalarSize = APSInt(TypeDigits).getZExtValue();
2130 if (!ScalarSize) {
2131 Ty = LLT::token();
2132 lex();
2133 return false;
2134 }
2135
2136 if (!verifyScalarSize(ScalarSize))
2137 return error("invalid size for scalar type");
2138
2139 Ty = Scalar ? LLT::scalar(ScalarSize) : LLT::integer(ScalarSize);
2140 lex();
2141 return false;
2142 }
2143
2144 if (Token.range().starts_with("p")) {
2145 const DataLayout &DL = MF.getDataLayout();
2146 uint64_t AS = APSInt(TypeDigits).getZExtValue();
2147 if (!verifyAddrSpace(AS))
2148 return error("invalid address space number");
2149
2150 Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
2151 lex();
2152 return false;
2153 }
2154
2155 if (Token.range().starts_with("f") || Token.range().starts_with("bf")) {
2156 auto ScalarSize = APSInt(TypeDigits).getZExtValue();
2157 if (!ScalarSize || !verifyScalarSize(ScalarSize))
2158 return error("invalid size for scalar type");
2159
2160 if (Token.range().starts_with("bf") && ScalarSize != 16)
2161 return error("invalid size for bfloat");
2162
2163 Ty = Token.range().starts_with("bf") ? LLT::bfloat16()
2164 : LLT::floatIEEE(ScalarSize);
2165 lex();
2166 return false;
2167 }
2168
2169 // Now we're looking for a vector.
2170 if (Token.isNot(MIToken::less))
2171 return error(Loc, "expected tN, pA, <M x tN>, <M x pA>, <vscale x M x tN>, "
2172 "or <vscale x M x pA> for GlobalISel type, "
2173 "where t = {'s', 'i', 'f', 'bf'}");
2174 lex();
2175
2176 bool HasVScale =
2177 Token.is(MIToken::Identifier) && Token.stringValue() == "vscale";
2178 if (HasVScale) {
2179 lex();
2180 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
2181 return error(
2182 "expected <vscale x M x tN>, where t = {'s', 'i', 'f', 'bf', 'p'}");
2183 lex();
2184 }
2185
2186 auto GetError = [this, &HasVScale, Loc]() {
2187 if (HasVScale)
2188 return error(Loc, "expected <vscale x M x tN> for vector type, where t = "
2189 "{'s', 'i', 'f', 'bf', 'p'}");
2190 return error(Loc, "expected <M x tN> for vector type, where t = {'s', 'i', "
2191 "'f', 'bf', 'p'}");
2192 };
2193
2194 if (Token.isNot(MIToken::IntegerLiteral))
2195 return GetError();
2196 uint64_t NumElements = Token.integerValue().getZExtValue();
2197 if (!verifyVectorElementCount(NumElements))
2198 return error("invalid number of vector elements");
2199
2200 lex();
2201
2202 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
2203 return GetError();
2204 lex();
2205
2206 StringRef VectorTyDigits = Token.range();
2207 if (!VectorTyDigits.consume_front("s") &&
2208 !VectorTyDigits.consume_front("i") &&
2209 !VectorTyDigits.consume_front("f") &&
2210 !VectorTyDigits.consume_front("p") && !VectorTyDigits.consume_front("bf"))
2211 return GetError();
2212
2213 if (VectorTyDigits.empty() || !llvm::all_of(VectorTyDigits, isdigit))
2214 return error(
2215 "expected integers after 's'/'i'/'f'/'bf'/'p' type identifier");
2216
2217 Scalar = Token.range().starts_with("s");
2218 if (Scalar || Token.range().starts_with("i")) {
2219 auto ScalarSize = APSInt(VectorTyDigits).getZExtValue();
2220 if (!verifyScalarSize(ScalarSize))
2221 return error("invalid size for scalar element in vector");
2222 Ty = Scalar ? LLT::scalar(ScalarSize) : LLT::integer(ScalarSize);
2223 } else if (Token.range().starts_with("p")) {
2224 const DataLayout &DL = MF.getDataLayout();
2225 uint64_t AS = APSInt(VectorTyDigits).getZExtValue();
2226 if (!verifyAddrSpace(AS))
2227 return error("invalid address space number");
2228
2229 Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
2230 } else if (Token.range().starts_with("f")) {
2231 auto ScalarSize = APSInt(VectorTyDigits).getZExtValue();
2232 if (!verifyScalarSize(ScalarSize))
2233 return error("invalid size for float element in vector");
2234 Ty = LLT::floatIEEE(ScalarSize);
2235 } else if (Token.range().starts_with("bf")) {
2236 auto ScalarSize = APSInt(VectorTyDigits).getZExtValue();
2237 if (!verifyScalarSize(ScalarSize))
2238 return error("invalid size for bfloat element in vector");
2239 Ty = LLT::bfloat16();
2240 } else {
2241 return GetError();
2242 }
2243 lex();
2244
2245 if (Token.isNot(MIToken::greater))
2246 return GetError();
2247
2248 lex();
2249
2250 Ty = LLT::vector(ElementCount::get(NumElements, HasVScale), Ty);
2251 return false;
2252}
2253
2254bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
2255 assert(Token.is(MIToken::Identifier));
2256 StringRef TypeDigits = Token.range();
2257 if (!TypeDigits.consume_front("i") && !TypeDigits.consume_front("s") &&
2258 !TypeDigits.consume_front("p") && !TypeDigits.consume_front("f") &&
2259 !TypeDigits.consume_front("bf"))
2260 return error("a typed immediate operand should start with one of 'i', "
2261 "'s', 'f', 'bf', or 'p'");
2262 if (TypeDigits.empty() || !llvm::all_of(TypeDigits, isdigit))
2263 return error(
2264 "expected integers after 'i'/'s'/'f'/'bf'/'p' type identifier");
2265
2266 auto Loc = Token.location();
2267 lex();
2268 if (Token.isNot(MIToken::IntegerLiteral)) {
2269 if (Token.isNot(MIToken::Identifier) ||
2270 !(Token.range() == "true" || Token.range() == "false"))
2271 return error("expected an integer literal");
2272 }
2273 const Constant *C = nullptr;
2274 if (parseIRConstant(Loc, C))
2275 return true;
2277 return false;
2278}
2279
2280bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
2281 auto Loc = Token.location();
2282 lex();
2283 if (Token.isNot(MIToken::FloatingPointLiteral) &&
2284 Token.isNot(MIToken::HexLiteral))
2285 return error("expected a floating point literal");
2286 const Constant *C = nullptr;
2287 if (parseIRConstant(Loc, C))
2288 return true;
2290 return false;
2291}
2292
2293static bool getHexUint(const MIToken &Token, APInt &Result) {
2295 StringRef S = Token.range();
2296 assert(S[0] == '0' && tolower(S[1]) == 'x');
2297 // This could be a floating point literal with a special prefix.
2298 if (!isxdigit(S[2]))
2299 return true;
2300 StringRef V = S.substr(2);
2301 APInt A(V.size()*4, V, 16);
2302
2303 // If A is 0, then A.getActiveBits() is 0. This isn't a valid bitwidth. Make
2304 // sure it isn't the case before constructing result.
2305 unsigned NumBits = (A == 0) ? 32 : A.getActiveBits();
2306 Result = APInt(NumBits, ArrayRef<uint64_t>(A.getRawData(), A.getNumWords()));
2307 return false;
2308}
2309
2310static bool getUnsigned(const MIToken &Token, unsigned &Result,
2311 ErrorCallbackType ErrCB) {
2312 if (Token.hasIntegerValue()) {
2313 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
2314 const APSInt &SInt = Token.integerValue();
2315 if (SInt.isNegative())
2316 return ErrCB(Token.location(), "expected unsigned integer");
2317 uint64_t Val64 = SInt.getLimitedValue(Limit);
2318 if (Val64 == Limit)
2319 return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2320 Result = Val64;
2321 return false;
2322 }
2323 if (Token.is(MIToken::HexLiteral)) {
2324 APInt A;
2325 if (getHexUint(Token, A))
2326 return true;
2327 if (A.getBitWidth() > 32)
2328 return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2329 Result = A.getZExtValue();
2330 return false;
2331 }
2332 return true;
2333}
2334
2335bool MIParser::getUnsigned(unsigned &Result) {
2336 return ::getUnsigned(
2337 Token, Result, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2338 return error(Loc, Msg);
2339 });
2340}
2341
2342bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
2345 unsigned Number;
2346 if (getUnsigned(Number))
2347 return true;
2348 auto MBBInfo = PFS.MBBSlots.find(Number);
2349 if (MBBInfo == PFS.MBBSlots.end())
2350 return error(Twine("use of undefined machine basic block #") +
2351 Twine(Number));
2352 MBB = MBBInfo->second;
2353 // TODO: Only parse the name if it's a MachineBasicBlockLabel. Deprecate once
2354 // we drop the <irname> from the bb.<id>.<irname> format.
2355 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
2356 return error(Twine("the name of machine basic block #") + Twine(Number) +
2357 " isn't '" + Token.stringValue() + "'");
2358 return false;
2359}
2360
2361bool MIParser::parseMBBOperand(MachineOperand &Dest) {
2364 return true;
2366 lex();
2367 return false;
2368}
2369
2370bool MIParser::parseStackFrameIndex(int &FI) {
2371 assert(Token.is(MIToken::StackObject));
2372 unsigned ID;
2373 if (getUnsigned(ID))
2374 return true;
2375 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
2376 if (ObjectInfo == PFS.StackObjectSlots.end())
2377 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
2378 "'");
2380 if (const auto *Alloca =
2381 MF.getFrameInfo().getObjectAllocation(ObjectInfo->second))
2382 Name = Alloca->getName();
2383 if (!Token.stringValue().empty() && Token.stringValue() != Name)
2384 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
2385 "' isn't '" + Token.stringValue() + "'");
2386 lex();
2387 FI = ObjectInfo->second;
2388 return false;
2389}
2390
2391bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
2392 int FI;
2393 if (parseStackFrameIndex(FI))
2394 return true;
2395 Dest = MachineOperand::CreateFI(FI);
2396 return false;
2397}
2398
2399bool MIParser::parseFixedStackFrameIndex(int &FI) {
2401 unsigned ID;
2402 if (getUnsigned(ID))
2403 return true;
2404 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
2405 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
2406 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
2407 Twine(ID) + "'");
2408 lex();
2409 FI = ObjectInfo->second;
2410 return false;
2411}
2412
2413bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
2414 int FI;
2415 if (parseFixedStackFrameIndex(FI))
2416 return true;
2417 Dest = MachineOperand::CreateFI(FI);
2418 return false;
2419}
2420
2421static bool parseGlobalValue(const MIToken &Token,
2423 ErrorCallbackType ErrCB) {
2424 switch (Token.kind()) {
2426 const Module *M = PFS.MF.getFunction().getParent();
2427 GV = M->getNamedValue(Token.stringValue());
2428 if (!GV)
2429 return ErrCB(Token.location(), Twine("use of undefined global value '") +
2430 Token.range() + "'");
2431 break;
2432 }
2433 case MIToken::GlobalValue: {
2434 unsigned GVIdx;
2435 if (getUnsigned(Token, GVIdx, ErrCB))
2436 return true;
2437 GV = PFS.IRSlots.GlobalValues.get(GVIdx);
2438 if (!GV)
2439 return ErrCB(Token.location(), Twine("use of undefined global value '@") +
2440 Twine(GVIdx) + "'");
2441 break;
2442 }
2443 default:
2444 llvm_unreachable("The current token should be a global value");
2445 }
2446 return false;
2447}
2448
2449bool MIParser::parseGlobalValue(GlobalValue *&GV) {
2450 return ::parseGlobalValue(
2451 Token, PFS, GV,
2452 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2453 return error(Loc, Msg);
2454 });
2455}
2456
2457bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
2458 GlobalValue *GV = nullptr;
2459 if (parseGlobalValue(GV))
2460 return true;
2461 lex();
2462 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
2463 if (parseOperandsOffset(Dest))
2464 return true;
2465 return false;
2466}
2467
2468bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
2470 unsigned ID;
2471 if (getUnsigned(ID))
2472 return true;
2473 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
2474 if (ConstantInfo == PFS.ConstantPoolSlots.end())
2475 return error("use of undefined constant '%const." + Twine(ID) + "'");
2476 lex();
2477 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
2478 if (parseOperandsOffset(Dest))
2479 return true;
2480 return false;
2481}
2482
2483bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
2485 unsigned ID;
2486 if (getUnsigned(ID))
2487 return true;
2488 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
2489 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
2490 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
2491 lex();
2492 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
2493 return false;
2494}
2495
2496bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
2498 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
2499 lex();
2500 Dest = MachineOperand::CreateES(Symbol);
2501 if (parseOperandsOffset(Dest))
2502 return true;
2503 return false;
2504}
2505
2506bool MIParser::parseMCSymbolOperand(MachineOperand &Dest) {
2507 assert(Token.is(MIToken::MCSymbol));
2508 MCSymbol *Symbol = getOrCreateMCSymbol(Token.stringValue());
2509 lex();
2510 Dest = MachineOperand::CreateMCSymbol(Symbol);
2511 if (parseOperandsOffset(Dest))
2512 return true;
2513 return false;
2514}
2515
2516bool MIParser::parseSubRegisterIndexOperand(MachineOperand &Dest) {
2518 StringRef Name = Token.stringValue();
2519 unsigned SubRegIndex = PFS.Target.getSubRegIndex(Token.stringValue());
2520 if (SubRegIndex == 0)
2521 return error(Twine("unknown subregister index '") + Name + "'");
2522 lex();
2523 Dest = MachineOperand::CreateImm(SubRegIndex);
2524 return false;
2525}
2526
2527bool MIParser::parseMDNode(MDNode *&Node) {
2528 assert(Token.is(MIToken::exclaim));
2529
2530 auto Loc = Token.location();
2531 lex();
2532 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
2533 return error("expected metadata id after '!'");
2534 unsigned ID;
2535 if (getUnsigned(ID))
2536 return true;
2537 auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID);
2538 if (NodeInfo == PFS.IRSlots.MetadataNodes.end()) {
2539 NodeInfo = PFS.MachineMetadataNodes.find(ID);
2540 if (NodeInfo == PFS.MachineMetadataNodes.end())
2541 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
2542 }
2543 lex();
2544 Node = NodeInfo->second.get();
2545 return false;
2546}
2547
2548bool MIParser::parseDIExpression(MDNode *&Expr) {
2549 unsigned Read;
2551 CurrentSource, Read, Error, *PFS.MF.getFunction().getParent(),
2552 &PFS.IRSlots);
2553 CurrentSource = CurrentSource.substr(Read);
2554 lex();
2555 if (!Expr)
2556 return error(Error.getMessage());
2557 return false;
2558}
2559
2560bool MIParser::parseDILocation(MDNode *&Loc) {
2561 assert(Token.is(MIToken::md_dilocation));
2562 lex();
2563
2564 bool HaveLine = false;
2565 unsigned Line = 0;
2566 unsigned Column = 0;
2567 MDNode *Scope = nullptr;
2568 MDNode *InlinedAt = nullptr;
2569 bool ImplicitCode = false;
2570 uint64_t AtomGroup = 0;
2571 uint64_t AtomRank = 0;
2572
2573 if (expectAndConsume(MIToken::lparen))
2574 return true;
2575
2576 if (Token.isNot(MIToken::rparen)) {
2577 do {
2578 if (Token.is(MIToken::Identifier)) {
2579 if (Token.stringValue() == "line") {
2580 lex();
2581 if (expectAndConsume(MIToken::colon))
2582 return true;
2583 if (Token.isNot(MIToken::IntegerLiteral) ||
2584 Token.integerValue().isSigned())
2585 return error("expected unsigned integer");
2586 Line = Token.integerValue().getZExtValue();
2587 HaveLine = true;
2588 lex();
2589 continue;
2590 }
2591 if (Token.stringValue() == "column") {
2592 lex();
2593 if (expectAndConsume(MIToken::colon))
2594 return true;
2595 if (Token.isNot(MIToken::IntegerLiteral) ||
2596 Token.integerValue().isSigned())
2597 return error("expected unsigned integer");
2598 Column = Token.integerValue().getZExtValue();
2599 lex();
2600 continue;
2601 }
2602 if (Token.stringValue() == "scope") {
2603 lex();
2604 if (expectAndConsume(MIToken::colon))
2605 return true;
2606 if (parseMDNode(Scope))
2607 return error("expected metadata node");
2608 if (!isa<DIScope>(Scope))
2609 return error("expected DIScope node");
2610 continue;
2611 }
2612 if (Token.stringValue() == "inlinedAt") {
2613 lex();
2614 if (expectAndConsume(MIToken::colon))
2615 return true;
2616 if (Token.is(MIToken::exclaim)) {
2617 if (parseMDNode(InlinedAt))
2618 return true;
2619 } else if (Token.is(MIToken::md_dilocation)) {
2620 if (parseDILocation(InlinedAt))
2621 return true;
2622 } else {
2623 return error("expected metadata node");
2624 }
2625 if (!isa<DILocation>(InlinedAt))
2626 return error("expected DILocation node");
2627 continue;
2628 }
2629 if (Token.stringValue() == "isImplicitCode") {
2630 lex();
2631 if (expectAndConsume(MIToken::colon))
2632 return true;
2633 if (!Token.is(MIToken::Identifier))
2634 return error("expected true/false");
2635 // As far as I can see, we don't have any existing need for parsing
2636 // true/false in MIR yet. Do it ad-hoc until there's something else
2637 // that needs it.
2638 if (Token.stringValue() == "true")
2639 ImplicitCode = true;
2640 else if (Token.stringValue() == "false")
2641 ImplicitCode = false;
2642 else
2643 return error("expected true/false");
2644 lex();
2645 continue;
2646 }
2647 if (Token.stringValue() == "atomGroup") {
2648 lex();
2649 if (expectAndConsume(MIToken::colon))
2650 return true;
2651 if (Token.isNot(MIToken::IntegerLiteral) ||
2652 Token.integerValue().isSigned())
2653 return error("expected unsigned integer");
2654 AtomGroup = Token.integerValue().getZExtValue();
2655 lex();
2656 continue;
2657 }
2658 if (Token.stringValue() == "atomRank") {
2659 lex();
2660 if (expectAndConsume(MIToken::colon))
2661 return true;
2662 if (Token.isNot(MIToken::IntegerLiteral) ||
2663 Token.integerValue().isSigned())
2664 return error("expected unsigned integer");
2665 AtomRank = Token.integerValue().getZExtValue();
2666 lex();
2667 continue;
2668 }
2669 }
2670 return error(Twine("invalid DILocation argument '") +
2671 Token.stringValue() + "'");
2672 } while (consumeIfPresent(MIToken::comma));
2673 }
2674
2675 if (expectAndConsume(MIToken::rparen))
2676 return true;
2677
2678 if (!HaveLine)
2679 return error("DILocation requires line number");
2680 if (!Scope)
2681 return error("DILocation requires a scope");
2682
2683 Loc = DILocation::get(MF.getFunction().getContext(), Line, Column, Scope,
2684 InlinedAt, ImplicitCode, AtomGroup, AtomRank);
2685 return false;
2686}
2687
2688bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
2689 MDNode *Node = nullptr;
2690 if (Token.is(MIToken::exclaim)) {
2691 if (parseMDNode(Node))
2692 return true;
2693 } else if (Token.is(MIToken::md_diexpr)) {
2694 if (parseDIExpression(Node))
2695 return true;
2696 }
2697 Dest = MachineOperand::CreateMetadata(Node);
2698 return false;
2699}
2700
2701bool MIParser::parseCFIOffset(int &Offset) {
2702 if (Token.isNot(MIToken::IntegerLiteral))
2703 return error("expected a cfi offset");
2704 if (Token.integerValue().getSignificantBits() > 32)
2705 return error("expected a 32 bit integer (the cfi offset is too large)");
2706 Offset = (int)Token.integerValue().getExtValue();
2707 lex();
2708 return false;
2709}
2710
2711bool MIParser::parseCFIRegister(unsigned &Reg) {
2712 if (Token.isNot(MIToken::NamedRegister))
2713 return error("expected a cfi register");
2714 Register LLVMReg;
2715 if (parseNamedRegister(LLVMReg))
2716 return true;
2717 const auto *TRI = MF.getSubtarget().getRegisterInfo();
2718 assert(TRI && "Expected target register info");
2719 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
2720 if (DwarfReg < 0)
2721 return error("invalid DWARF register");
2722 Reg = (unsigned)DwarfReg;
2723 lex();
2724 return false;
2725}
2726
2727bool MIParser::parseCFIAddressSpace(unsigned &AddressSpace) {
2728 if (Token.isNot(MIToken::IntegerLiteral))
2729 return error("expected a cfi address space literal");
2730 if (Token.integerValue().isSigned())
2731 return error("expected an unsigned integer (cfi address space)");
2732 AddressSpace = Token.integerValue().getZExtValue();
2733 lex();
2734 return false;
2735}
2736
2737bool MIParser::parseCFIEscapeValues(std::string &Values) {
2738 do {
2739 if (Token.isNot(MIToken::HexLiteral))
2740 return error("expected a hexadecimal literal");
2741 unsigned Value;
2742 if (getUnsigned(Value))
2743 return true;
2744 if (Value > UINT8_MAX)
2745 return error("expected a 8-bit integer (too large)");
2746 Values.push_back(static_cast<uint8_t>(Value));
2747 lex();
2748 } while (consumeIfPresent(MIToken::comma));
2749 return false;
2750}
2751
2752bool MIParser::parseCFIOperand(MachineOperand &Dest) {
2753 auto Kind = Token.kind();
2754 lex();
2755 int Offset;
2756 unsigned Reg;
2757 unsigned AddressSpace;
2758 unsigned CFIIndex;
2759 switch (Kind) {
2761 if (parseCFIRegister(Reg))
2762 return true;
2763 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
2764 break;
2766 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2767 parseCFIOffset(Offset))
2768 return true;
2769 CFIIndex =
2770 MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
2771 break;
2773 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2774 parseCFIOffset(Offset))
2775 return true;
2776 CFIIndex = MF.addFrameInst(
2778 break;
2780 if (parseCFIRegister(Reg))
2781 return true;
2782 CFIIndex =
2783 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
2784 break;
2786 if (parseCFIOffset(Offset))
2787 return true;
2788 CFIIndex =
2789 MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, Offset));
2790 break;
2792 if (parseCFIOffset(Offset))
2793 return true;
2794 CFIIndex = MF.addFrameInst(
2796 break;
2798 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2799 parseCFIOffset(Offset))
2800 return true;
2801 CFIIndex =
2802 MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, Offset));
2803 break;
2805 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2806 parseCFIOffset(Offset) || expectAndConsume(MIToken::comma) ||
2807 parseCFIAddressSpace(AddressSpace))
2808 return true;
2809 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMDefAspaceCfa(
2810 nullptr, Reg, Offset, AddressSpace, SMLoc()));
2811 break;
2813 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRememberState(nullptr));
2814 break;
2816 if (parseCFIRegister(Reg))
2817 return true;
2818 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, Reg));
2819 break;
2821 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestoreState(nullptr));
2822 break;
2824 if (parseCFIRegister(Reg))
2825 return true;
2826 CFIIndex = MF.addFrameInst(MCCFIInstruction::createUndefined(nullptr, Reg));
2827 break;
2829 unsigned Reg2;
2830 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2831 parseCFIRegister(Reg2))
2832 return true;
2833
2834 CFIIndex =
2835 MF.addFrameInst(MCCFIInstruction::createRegister(nullptr, Reg, Reg2));
2836 break;
2837 }
2839 CFIIndex = MF.addFrameInst(MCCFIInstruction::createWindowSave(nullptr));
2840 break;
2842 CFIIndex = MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
2843 break;
2845 CFIIndex =
2846 MF.addFrameInst(MCCFIInstruction::createNegateRAStateWithPC(nullptr));
2847 break;
2849 std::string Values;
2850 if (parseCFIEscapeValues(Values))
2851 return true;
2852 CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(nullptr, Values));
2853 break;
2854 }
2855 default:
2856 // TODO: Parse the other CFI operands.
2857 llvm_unreachable("The current token should be a cfi operand");
2858 }
2859 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
2860 return false;
2861}
2862
2863bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
2864 switch (Token.kind()) {
2865 case MIToken::NamedIRBlock: {
2867 F.getValueSymbolTable()->lookup(Token.stringValue()));
2868 if (!BB)
2869 return error(Twine("use of undefined IR block '") + Token.range() + "'");
2870 break;
2871 }
2872 case MIToken::IRBlock: {
2873 unsigned SlotNumber = 0;
2874 if (getUnsigned(SlotNumber))
2875 return true;
2876 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
2877 if (!BB)
2878 return error(Twine("use of undefined IR block '%ir-block.") +
2879 Twine(SlotNumber) + "'");
2880 break;
2881 }
2882 default:
2883 llvm_unreachable("The current token should be an IR block reference");
2884 }
2885 return false;
2886}
2887
2888bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
2890 lex();
2891 if (expectAndConsume(MIToken::lparen))
2892 return true;
2893 if (Token.isNot(MIToken::GlobalValue) &&
2894 Token.isNot(MIToken::NamedGlobalValue))
2895 return error("expected a global value");
2896 GlobalValue *GV = nullptr;
2897 if (parseGlobalValue(GV))
2898 return true;
2899 auto *F = dyn_cast<Function>(GV);
2900 if (!F)
2901 return error("expected an IR function reference");
2902 lex();
2903 if (expectAndConsume(MIToken::comma))
2904 return true;
2905 BasicBlock *BB = nullptr;
2906 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
2907 return error("expected an IR block reference");
2908 if (parseIRBlock(BB, *F))
2909 return true;
2910 lex();
2911 if (expectAndConsume(MIToken::rparen))
2912 return true;
2913 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
2914 if (parseOperandsOffset(Dest))
2915 return true;
2916 return false;
2917}
2918
2919bool MIParser::parseIntrinsicOperand(MachineOperand &Dest) {
2920 assert(Token.is(MIToken::kw_intrinsic));
2921 lex();
2922 if (expectAndConsume(MIToken::lparen))
2923 return error("expected syntax intrinsic(@llvm.whatever)");
2924
2925 if (Token.isNot(MIToken::NamedGlobalValue))
2926 return error("expected syntax intrinsic(@llvm.whatever)");
2927
2928 std::string Name = std::string(Token.stringValue());
2929 lex();
2930
2931 if (expectAndConsume(MIToken::rparen))
2932 return error("expected ')' to terminate intrinsic name");
2933
2934 // Find out what intrinsic we're dealing with.
2937 return error("unknown intrinsic name");
2939
2940 return false;
2941}
2942
2943bool MIParser::parsePredicateOperand(MachineOperand &Dest) {
2944 assert(Token.is(MIToken::kw_intpred) || Token.is(MIToken::kw_floatpred));
2945 bool IsFloat = Token.is(MIToken::kw_floatpred);
2946 lex();
2947
2948 if (expectAndConsume(MIToken::lparen))
2949 return error("expected syntax intpred(whatever) or floatpred(whatever");
2950
2951 if (Token.isNot(MIToken::Identifier))
2952 return error("whatever");
2953
2954 CmpInst::Predicate Pred;
2955 if (IsFloat) {
2956 Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2957 .Case("false", CmpInst::FCMP_FALSE)
2958 .Case("oeq", CmpInst::FCMP_OEQ)
2959 .Case("ogt", CmpInst::FCMP_OGT)
2960 .Case("oge", CmpInst::FCMP_OGE)
2961 .Case("olt", CmpInst::FCMP_OLT)
2962 .Case("ole", CmpInst::FCMP_OLE)
2963 .Case("one", CmpInst::FCMP_ONE)
2964 .Case("ord", CmpInst::FCMP_ORD)
2965 .Case("uno", CmpInst::FCMP_UNO)
2966 .Case("ueq", CmpInst::FCMP_UEQ)
2967 .Case("ugt", CmpInst::FCMP_UGT)
2968 .Case("uge", CmpInst::FCMP_UGE)
2969 .Case("ult", CmpInst::FCMP_ULT)
2970 .Case("ule", CmpInst::FCMP_ULE)
2971 .Case("une", CmpInst::FCMP_UNE)
2972 .Case("true", CmpInst::FCMP_TRUE)
2974 if (!CmpInst::isFPPredicate(Pred))
2975 return error("invalid floating-point predicate");
2976 } else {
2977 Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2978 .Case("eq", CmpInst::ICMP_EQ)
2979 .Case("ne", CmpInst::ICMP_NE)
2980 .Case("sgt", CmpInst::ICMP_SGT)
2981 .Case("sge", CmpInst::ICMP_SGE)
2982 .Case("slt", CmpInst::ICMP_SLT)
2983 .Case("sle", CmpInst::ICMP_SLE)
2984 .Case("ugt", CmpInst::ICMP_UGT)
2985 .Case("uge", CmpInst::ICMP_UGE)
2986 .Case("ult", CmpInst::ICMP_ULT)
2987 .Case("ule", CmpInst::ICMP_ULE)
2989 if (!CmpInst::isIntPredicate(Pred))
2990 return error("invalid integer predicate");
2991 }
2992
2993 lex();
2995 if (expectAndConsume(MIToken::rparen))
2996 return error("predicate should be terminated by ')'.");
2997
2998 return false;
2999}
3000
3001bool MIParser::parseShuffleMaskOperand(MachineOperand &Dest) {
3003
3004 lex();
3005 if (expectAndConsume(MIToken::lparen))
3006 return error("expected syntax shufflemask(<integer or undef>, ...)");
3007
3008 SmallVector<int, 32> ShufMask;
3009 do {
3010 if (Token.is(MIToken::kw_undef)) {
3011 ShufMask.push_back(-1);
3012 } else if (Token.is(MIToken::IntegerLiteral)) {
3013 const APSInt &Int = Token.integerValue();
3014 ShufMask.push_back(Int.getExtValue());
3015 } else {
3016 return error("expected integer constant");
3017 }
3018
3019 lex();
3020 } while (consumeIfPresent(MIToken::comma));
3021
3022 if (expectAndConsume(MIToken::rparen))
3023 return error("shufflemask should be terminated by ')'.");
3024
3025 if (ShufMask.size() < 2)
3026 return error("shufflemask should have > 1 element");
3027
3028 ArrayRef<int> MaskAlloc = MF.allocateShuffleMask(ShufMask);
3029 Dest = MachineOperand::CreateShuffleMask(MaskAlloc);
3030 return false;
3031}
3032
3033bool MIParser::parseDbgInstrRefOperand(MachineOperand &Dest) {
3035
3036 lex();
3037 if (expectAndConsume(MIToken::lparen))
3038 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
3039
3040 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
3041 return error("expected unsigned integer for instruction index");
3042 uint64_t InstrIdx = Token.integerValue().getZExtValue();
3043 assert(InstrIdx <= std::numeric_limits<unsigned>::max() &&
3044 "Instruction reference's instruction index is too large");
3045 lex();
3046
3047 if (expectAndConsume(MIToken::comma))
3048 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
3049
3050 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
3051 return error("expected unsigned integer for operand index");
3052 uint64_t OpIdx = Token.integerValue().getZExtValue();
3053 assert(OpIdx <= std::numeric_limits<unsigned>::max() &&
3054 "Instruction reference's operand index is too large");
3055 lex();
3056
3057 if (expectAndConsume(MIToken::rparen))
3058 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
3059
3060 Dest = MachineOperand::CreateDbgInstrRef(InstrIdx, OpIdx);
3061 return false;
3062}
3063
3064bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
3066 lex();
3067 if (expectAndConsume(MIToken::lparen))
3068 return true;
3069 if (Token.isNot(MIToken::Identifier))
3070 return error("expected the name of the target index");
3071 int Index = 0;
3072 if (PFS.Target.getTargetIndex(Token.stringValue(), Index))
3073 return error("use of undefined target index '" + Token.stringValue() + "'");
3074 lex();
3075 if (expectAndConsume(MIToken::rparen))
3076 return true;
3077 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
3078 if (parseOperandsOffset(Dest))
3079 return true;
3080 return false;
3081}
3082
3083bool MIParser::parseCustomRegisterMaskOperand(MachineOperand &Dest) {
3084 assert(Token.stringValue() == "CustomRegMask" && "Expected a custom RegMask");
3085 lex();
3086 if (expectAndConsume(MIToken::lparen))
3087 return true;
3088
3089 uint32_t *Mask = MF.allocateRegMask();
3090 do {
3091 if (Token.isNot(MIToken::rparen)) {
3092 if (Token.isNot(MIToken::NamedRegister))
3093 return error("expected a named register");
3094 Register Reg;
3095 if (parseNamedRegister(Reg))
3096 return true;
3097 lex();
3098 Mask[Reg.id() / 32] |= 1U << (Reg.id() % 32);
3099 }
3100
3101 // TODO: Report an error if the same register is used more than once.
3102 } while (consumeIfPresent(MIToken::comma));
3103
3104 if (expectAndConsume(MIToken::rparen))
3105 return true;
3106 Dest = MachineOperand::CreateRegMask(Mask);
3107 return false;
3108}
3109
3110bool MIParser::parseLaneMaskOperand(MachineOperand &Dest) {
3111 assert(Token.is(MIToken::kw_lanemask));
3112
3113 lex();
3114 if (expectAndConsume(MIToken::lparen))
3115 return true;
3116
3117 // Parse lanemask.
3118 if (Token.isNot(MIToken::IntegerLiteral) && Token.isNot(MIToken::HexLiteral))
3119 return error("expected a valid lane mask value");
3120 static_assert(sizeof(LaneBitmask::Type) == sizeof(uint64_t),
3121 "Use correct get-function for lane mask.");
3123 if (getUint64(V))
3124 return true;
3125 LaneBitmask LaneMask(V);
3126 lex();
3127
3128 if (expectAndConsume(MIToken::rparen))
3129 return true;
3130
3131 Dest = MachineOperand::CreateLaneMask(LaneMask);
3132 return false;
3133}
3134
3135bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
3136 assert(Token.is(MIToken::kw_liveout));
3137 uint32_t *Mask = MF.allocateRegMask();
3138 lex();
3139 if (expectAndConsume(MIToken::lparen))
3140 return true;
3141 while (true) {
3142 if (Token.isNot(MIToken::NamedRegister))
3143 return error("expected a named register");
3144 Register Reg;
3145 if (parseNamedRegister(Reg))
3146 return true;
3147 lex();
3148 Mask[Reg.id() / 32] |= 1U << (Reg.id() % 32);
3149 // TODO: Report an error if the same register is used more than once.
3150 if (Token.isNot(MIToken::comma))
3151 break;
3152 lex();
3153 }
3154 if (expectAndConsume(MIToken::rparen))
3155 return true;
3157 return false;
3158}
3159
3160bool MIParser::parseMachineOperand(const unsigned OpCode, const unsigned OpIdx,
3161 MachineOperand &Dest,
3162 std::optional<unsigned> &TiedDefIdx) {
3163 switch (Token.kind()) {
3166 case MIToken::kw_def:
3167 case MIToken::kw_dead:
3168 case MIToken::kw_killed:
3169 case MIToken::kw_undef:
3178 return parseRegisterOperand(Dest, TiedDefIdx);
3180 // TODO: Forbid numeric operands for INLINEASM once the transition to the
3181 // symbolic form is over.
3182 return parseImmediateOperand(Dest);
3183 case MIToken::kw_half:
3184 case MIToken::kw_bfloat:
3185 case MIToken::kw_float:
3186 case MIToken::kw_double:
3188 case MIToken::kw_fp128:
3190 return parseFPImmediateOperand(Dest);
3192 return parseMBBOperand(Dest);
3194 return parseStackObjectOperand(Dest);
3196 return parseFixedStackObjectOperand(Dest);
3199 return parseGlobalAddressOperand(Dest);
3201 return parseConstantPoolIndexOperand(Dest);
3203 return parseJumpTableIndexOperand(Dest);
3205 return parseExternalSymbolOperand(Dest);
3206 case MIToken::MCSymbol:
3207 return parseMCSymbolOperand(Dest);
3209 return parseSubRegisterIndexOperand(Dest);
3210 case MIToken::md_diexpr:
3211 case MIToken::exclaim:
3212 return parseMetadataOperand(Dest);
3230 return parseCFIOperand(Dest);
3232 return parseBlockAddressOperand(Dest);
3234 return parseIntrinsicOperand(Dest);
3236 return parseTargetIndexOperand(Dest);
3238 return parseLaneMaskOperand(Dest);
3240 return parseLiveoutRegisterMaskOperand(Dest);
3243 return parsePredicateOperand(Dest);
3245 return parseShuffleMaskOperand(Dest);
3247 return parseDbgInstrRefOperand(Dest);
3248 case MIToken::Error:
3249 return true;
3250 case MIToken::Identifier: {
3251 bool IsInlineAsm = OpCode == TargetOpcode::INLINEASM ||
3252 OpCode == TargetOpcode::INLINEASM_BR;
3253 if (IsInlineAsm)
3254 return parseSymbolicInlineAsmOperand(OpIdx, Dest);
3255
3256 StringRef Id = Token.stringValue();
3257 if (const auto *RegMask = PFS.Target.getRegMask(Id)) {
3258 Dest = MachineOperand::CreateRegMask(RegMask);
3259 lex();
3260 break;
3261 } else if (Id == "CustomRegMask") {
3262 return parseCustomRegisterMaskOperand(Dest);
3263 } else {
3264 return parseTypedImmediateOperand(Dest);
3265 }
3266 }
3267 case MIToken::dot: {
3268 const auto *TII = MF.getSubtarget().getInstrInfo();
3269 if (const auto *Formatter = TII->getMIRFormatter()) {
3270 return parseTargetImmMnemonic(OpCode, OpIdx, Dest, *Formatter);
3271 }
3272 [[fallthrough]];
3273 }
3274 default:
3275 // FIXME: Parse the MCSymbol machine operand.
3276 return error("expected a machine operand");
3277 }
3278 return false;
3279}
3280
3281bool MIParser::parseMachineOperandAndTargetFlags(
3282 const unsigned OpCode, const unsigned OpIdx, MachineOperand &Dest,
3283 std::optional<unsigned> &TiedDefIdx) {
3284 unsigned TF = 0;
3285 bool HasTargetFlags = false;
3286 if (Token.is(MIToken::kw_target_flags)) {
3287 HasTargetFlags = true;
3288 lex();
3289 if (expectAndConsume(MIToken::lparen))
3290 return true;
3291 if (Token.isNot(MIToken::Identifier))
3292 return error("expected the name of the target flag");
3293 if (PFS.Target.getDirectTargetFlag(Token.stringValue(), TF)) {
3294 if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), TF))
3295 return error("use of undefined target flag '" + Token.stringValue() +
3296 "'");
3297 }
3298 lex();
3299 while (Token.is(MIToken::comma)) {
3300 lex();
3301 if (Token.isNot(MIToken::Identifier))
3302 return error("expected the name of the target flag");
3303 unsigned BitFlag = 0;
3304 if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), BitFlag))
3305 return error("use of undefined target flag '" + Token.stringValue() +
3306 "'");
3307 // TODO: Report an error when using a duplicate bit target flag.
3308 TF |= BitFlag;
3309 lex();
3310 }
3311 if (expectAndConsume(MIToken::rparen))
3312 return true;
3313 }
3314 auto Loc = Token.location();
3315 if (parseMachineOperand(OpCode, OpIdx, Dest, TiedDefIdx))
3316 return true;
3317 if (!HasTargetFlags)
3318 return false;
3319 if (Dest.isReg())
3320 return error(Loc, "register operands can't have target flags");
3321 Dest.setTargetFlags(TF);
3322 return false;
3323}
3324
3325bool MIParser::parseOffset(int64_t &Offset) {
3326 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
3327 return false;
3328 StringRef Sign = Token.range();
3329 bool IsNegative = Token.is(MIToken::minus);
3330 lex();
3331 if (Token.isNot(MIToken::IntegerLiteral))
3332 return error("expected an integer literal after '" + Sign + "'");
3333 if (Token.integerValue().getSignificantBits() > 64)
3334 return error("expected 64-bit integer (too large)");
3335 Offset = Token.integerValue().getExtValue();
3336 if (IsNegative)
3337 Offset = -Offset;
3338 lex();
3339 return false;
3340}
3341
3342bool MIParser::parseIRBlockAddressTaken(BasicBlock *&BB) {
3344 lex();
3345 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
3346 return error("expected basic block after 'ir_block_address_taken'");
3347
3348 if (parseIRBlock(BB, MF.getFunction()))
3349 return true;
3350
3351 lex();
3352 return false;
3353}
3354
3355bool MIParser::parseAlignment(uint64_t &Alignment) {
3356 assert(Token.is(MIToken::kw_align) || Token.is(MIToken::kw_basealign));
3357 lex();
3358 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3359 return error("expected an integer literal after 'align'");
3360 if (getUint64(Alignment))
3361 return true;
3362 lex();
3363
3364 if (!isPowerOf2_64(Alignment))
3365 return error("expected a power-of-2 literal after 'align'");
3366
3367 return false;
3368}
3369
3370bool MIParser::parseAddrspace(unsigned &Addrspace) {
3371 assert(Token.is(MIToken::kw_addrspace));
3372 lex();
3373 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3374 return error("expected an integer literal after 'addrspace'");
3375 if (getUnsigned(Addrspace))
3376 return true;
3377 lex();
3378 return false;
3379}
3380
3381bool MIParser::parseOperandsOffset(MachineOperand &Op) {
3382 int64_t Offset = 0;
3383 if (parseOffset(Offset))
3384 return true;
3385 Op.setOffset(Offset);
3386 return false;
3387}
3388
3389static bool parseIRValue(const MIToken &Token, PerFunctionMIParsingState &PFS,
3390 const Value *&V, ErrorCallbackType ErrCB) {
3391 switch (Token.kind()) {
3392 case MIToken::NamedIRValue: {
3393 V = PFS.MF.getFunction().getValueSymbolTable()->lookup(Token.stringValue());
3394 break;
3395 }
3396 case MIToken::IRValue: {
3397 unsigned SlotNumber = 0;
3398 if (getUnsigned(Token, SlotNumber, ErrCB))
3399 return true;
3400 V = PFS.getIRValue(SlotNumber);
3401 break;
3402 }
3404 case MIToken::GlobalValue: {
3405 GlobalValue *GV = nullptr;
3406 if (parseGlobalValue(Token, PFS, GV, ErrCB))
3407 return true;
3408 V = GV;
3409 break;
3410 }
3412 const Constant *C = nullptr;
3413 if (parseIRConstant(Token.location(), Token.stringValue(), PFS, C, ErrCB))
3414 return true;
3415 V = C;
3416 break;
3417 }
3419 V = nullptr;
3420 return false;
3421 default:
3422 llvm_unreachable("The current token should be an IR block reference");
3423 }
3424 if (!V)
3425 return ErrCB(Token.location(), Twine("use of undefined IR value '") + Token.range() + "'");
3426 return false;
3427}
3428
3429bool MIParser::parseIRValue(const Value *&V) {
3430 return ::parseIRValue(
3431 Token, PFS, V, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3432 return error(Loc, Msg);
3433 });
3434}
3435
3436bool MIParser::getUint64(uint64_t &Result) {
3437 if (Token.hasIntegerValue()) {
3438 if (Token.integerValue().getActiveBits() > 64)
3439 return error("expected 64-bit integer (too large)");
3440 Result = Token.integerValue().getZExtValue();
3441 return false;
3442 }
3443 if (Token.is(MIToken::HexLiteral)) {
3444 APInt A;
3445 if (getHexUint(A))
3446 return true;
3447 if (A.getBitWidth() > 64)
3448 return error("expected 64-bit integer (too large)");
3449 Result = A.getZExtValue();
3450 return false;
3451 }
3452 return true;
3453}
3454
3455bool MIParser::getHexUint(APInt &Result) {
3456 return ::getHexUint(Token, Result);
3457}
3458
3459bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags &Flags) {
3460 const auto OldFlags = Flags;
3461 switch (Token.kind()) {
3464 break;
3467 break;
3470 break;
3473 break;
3476 if (PFS.Target.getMMOTargetFlag(Token.stringValue(), TF))
3477 return error("use of undefined target MMO flag '" + Token.stringValue() +
3478 "'");
3479 Flags |= TF;
3480 break;
3481 }
3482 default:
3483 llvm_unreachable("The current token should be a memory operand flag");
3484 }
3485 if (OldFlags == Flags)
3486 // We know that the same flag is specified more than once when the flags
3487 // weren't modified.
3488 return error("duplicate '" + Token.stringValue() + "' memory operand flag");
3489 lex();
3490 return false;
3491}
3492
3493bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
3494 switch (Token.kind()) {
3495 case MIToken::kw_stack:
3496 PSV = MF.getPSVManager().getStack();
3497 break;
3498 case MIToken::kw_got:
3499 PSV = MF.getPSVManager().getGOT();
3500 break;
3502 PSV = MF.getPSVManager().getJumpTable();
3503 break;
3505 PSV = MF.getPSVManager().getConstantPool();
3506 break;
3508 int FI;
3509 if (parseFixedStackFrameIndex(FI))
3510 return true;
3511 PSV = MF.getPSVManager().getFixedStack(FI);
3512 // The token was already consumed, so use return here instead of break.
3513 return false;
3514 }
3515 case MIToken::StackObject: {
3516 int FI;
3517 if (parseStackFrameIndex(FI))
3518 return true;
3519 PSV = MF.getPSVManager().getFixedStack(FI);
3520 // The token was already consumed, so use return here instead of break.
3521 return false;
3522 }
3524 lex();
3525 switch (Token.kind()) {
3528 GlobalValue *GV = nullptr;
3529 if (parseGlobalValue(GV))
3530 return true;
3531 PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
3532 break;
3533 }
3535 PSV = MF.getPSVManager().getExternalSymbolCallEntry(
3536 MF.createExternalSymbolName(Token.stringValue()));
3537 break;
3538 default:
3539 return error(
3540 "expected a global value or an external symbol after 'call-entry'");
3541 }
3542 break;
3543 case MIToken::kw_custom: {
3544 lex();
3545 const auto *TII = MF.getSubtarget().getInstrInfo();
3546 if (const auto *Formatter = TII->getMIRFormatter()) {
3547 if (Formatter->parseCustomPseudoSourceValue(
3548 Token.stringValue(), MF, PFS, PSV,
3549 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3550 return error(Loc, Msg);
3551 }))
3552 return true;
3553 } else {
3554 return error("unable to parse target custom pseudo source value");
3555 }
3556 break;
3557 }
3558 default:
3559 llvm_unreachable("The current token should be pseudo source value");
3560 }
3561 lex();
3562 return false;
3563}
3564
3565bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
3566 if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
3567 Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
3568 Token.is(MIToken::FixedStackObject) || Token.is(MIToken::StackObject) ||
3569 Token.is(MIToken::kw_call_entry) || Token.is(MIToken::kw_custom)) {
3570 const PseudoSourceValue *PSV = nullptr;
3571 if (parseMemoryPseudoSourceValue(PSV))
3572 return true;
3573 int64_t Offset = 0;
3574 if (parseOffset(Offset))
3575 return true;
3576 Dest = MachinePointerInfo(PSV, Offset);
3577 return false;
3578 }
3579 if (Token.isNot(MIToken::NamedIRValue) && Token.isNot(MIToken::IRValue) &&
3580 Token.isNot(MIToken::GlobalValue) &&
3581 Token.isNot(MIToken::NamedGlobalValue) &&
3582 Token.isNot(MIToken::QuotedIRValue) &&
3583 Token.isNot(MIToken::kw_unknown_address))
3584 return error("expected an IR value reference");
3585 const Value *V = nullptr;
3586 if (parseIRValue(V))
3587 return true;
3588 if (V && !V->getType()->isPointerTy())
3589 return error("expected a pointer IR value");
3590 lex();
3591 int64_t Offset = 0;
3592 if (parseOffset(Offset))
3593 return true;
3594 Dest = MachinePointerInfo(V, Offset);
3595 return false;
3596}
3597
3598bool MIParser::parseOptionalScope(LLVMContext &Context,
3599 SyncScope::ID &SSID) {
3600 SSID = SyncScope::System;
3601 if (Token.is(MIToken::Identifier) && Token.stringValue() == "syncscope") {
3602 lex();
3603 if (expectAndConsume(MIToken::lparen))
3604 return error("expected '(' in syncscope");
3605
3606 std::string SSN;
3607 if (parseStringConstant(SSN))
3608 return true;
3609
3610 SSID = Context.getOrInsertSyncScopeID(SSN);
3611 if (expectAndConsume(MIToken::rparen))
3612 return error("expected ')' in syncscope");
3613 }
3614
3615 return false;
3616}
3617
3618bool MIParser::parseOptionalAtomicOrdering(AtomicOrdering &Order) {
3620 if (Token.isNot(MIToken::Identifier))
3621 return false;
3622
3623 Order = StringSwitch<AtomicOrdering>(Token.stringValue())
3624 .Case("unordered", AtomicOrdering::Unordered)
3625 .Case("monotonic", AtomicOrdering::Monotonic)
3626 .Case("acquire", AtomicOrdering::Acquire)
3627 .Case("release", AtomicOrdering::Release)
3631
3632 if (Order != AtomicOrdering::NotAtomic) {
3633 lex();
3634 return false;
3635 }
3636
3637 return error("expected an atomic scope, ordering or a size specification");
3638}
3639
3640bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
3641 if (expectAndConsume(MIToken::lparen))
3642 return true;
3644 while (Token.isMemoryOperandFlag()) {
3645 if (parseMemoryOperandFlag(Flags))
3646 return true;
3647 }
3648 if (Token.isNot(MIToken::Identifier) ||
3649 (Token.stringValue() != "load" && Token.stringValue() != "store"))
3650 return error("expected 'load' or 'store' memory operation");
3651 if (Token.stringValue() == "load")
3653 else
3655 lex();
3656
3657 // Optional 'store' for operands that both load and store.
3658 if (Token.is(MIToken::Identifier) && Token.stringValue() == "store") {
3660 lex();
3661 }
3662
3663 // Optional synchronization scope.
3664 SyncScope::ID SSID;
3665 if (parseOptionalScope(MF.getFunction().getContext(), SSID))
3666 return true;
3667
3668 // Up to two atomic orderings (cmpxchg provides guarantees on failure).
3669 AtomicOrdering Order, FailureOrder;
3670 if (parseOptionalAtomicOrdering(Order))
3671 return true;
3672
3673 if (parseOptionalAtomicOrdering(FailureOrder))
3674 return true;
3675
3676 if (Token.isNot(MIToken::IntegerLiteral) &&
3677 Token.isNot(MIToken::kw_unknown_size) &&
3678 Token.isNot(MIToken::lparen))
3679 return error("expected memory LLT, the size integer literal or 'unknown-size' after "
3680 "memory operation");
3681
3683 if (Token.is(MIToken::IntegerLiteral)) {
3684 uint64_t Size;
3685 if (getUint64(Size))
3686 return true;
3687
3688 // Convert from bytes to bits for storage.
3690 lex();
3691 } else if (Token.is(MIToken::kw_unknown_size)) {
3692 lex();
3693 } else {
3694 if (expectAndConsume(MIToken::lparen))
3695 return true;
3696 if (parseLowLevelType(Token.location(), MemoryType))
3697 return true;
3698 if (expectAndConsume(MIToken::rparen))
3699 return true;
3700 }
3701
3703 if (Token.is(MIToken::Identifier)) {
3704 const char *Word =
3707 ? "on"
3708 : Flags & MachineMemOperand::MOLoad ? "from" : "into";
3709 if (Token.stringValue() != Word)
3710 return error(Twine("expected '") + Word + "'");
3711 lex();
3712
3713 if (parseMachinePointerInfo(Ptr))
3714 return true;
3715 }
3716 uint64_t BaseAlignment =
3717 MemoryType.isValid()
3718 ? PowerOf2Ceil(MemoryType.getSizeInBytes().getKnownMinValue())
3719 : 1;
3720 AAMDNodes AAInfo;
3721 MDNode *Range = nullptr;
3722 while (consumeIfPresent(MIToken::comma)) {
3723 switch (Token.kind()) {
3724 case MIToken::kw_align: {
3725 // align is printed if it is different than size.
3726 uint64_t Alignment;
3727 if (parseAlignment(Alignment))
3728 return true;
3729 if (Ptr.Offset & (Alignment - 1)) {
3730 // MachineMemOperand::getAlign never returns a value greater than the
3731 // alignment of offset, so this just guards against hand-written MIR
3732 // that specifies a large "align" value when it should probably use
3733 // "basealign" instead.
3734 return error("specified alignment is more aligned than offset");
3735 }
3736 BaseAlignment = Alignment;
3737 break;
3738 }
3740 // basealign is printed if it is different than align.
3741 if (parseAlignment(BaseAlignment))
3742 return true;
3743 break;
3745 if (parseAddrspace(Ptr.AddrSpace))
3746 return true;
3747 break;
3748 case MIToken::md_tbaa:
3749 lex();
3750 if (parseMDNode(AAInfo.TBAA))
3751 return true;
3752 break;
3754 lex();
3755 if (parseMDNode(AAInfo.Scope))
3756 return true;
3757 break;
3759 lex();
3760 if (parseMDNode(AAInfo.NoAlias))
3761 return true;
3762 break;
3764 lex();
3765 if (parseMDNode(AAInfo.NoAliasAddrSpace))
3766 return true;
3767 break;
3768 case MIToken::md_range:
3769 lex();
3770 if (parseMDNode(Range))
3771 return true;
3772 break;
3773 // TODO: Report an error on duplicate metadata nodes.
3774 default:
3775 return error("expected 'align' or '!tbaa' or '!alias.scope' or "
3776 "'!noalias' or '!range' or '!noalias.addrspace'");
3777 }
3778 }
3779 if (expectAndConsume(MIToken::rparen))
3780 return true;
3781 Dest = MF.getMachineMemOperand(Ptr, Flags, MemoryType, Align(BaseAlignment),
3782 AAInfo, Range, SSID, Order, FailureOrder);
3783 return false;
3784}
3785
3786bool MIParser::parsePreOrPostInstrSymbol(MCSymbol *&Symbol) {
3788 Token.is(MIToken::kw_post_instr_symbol)) &&
3789 "Invalid token for a pre- post-instruction symbol!");
3790 lex();
3791 if (Token.isNot(MIToken::MCSymbol))
3792 return error("expected a symbol after 'pre-instr-symbol'");
3793 Symbol = getOrCreateMCSymbol(Token.stringValue());
3794 lex();
3795 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3796 Token.is(MIToken::lbrace))
3797 return false;
3798 if (Token.isNot(MIToken::comma))
3799 return error("expected ',' before the next machine operand");
3800 lex();
3801 return false;
3802}
3803
3804bool MIParser::parseHeapAllocMarker(MDNode *&Node) {
3806 "Invalid token for a heap alloc marker!");
3807 lex();
3808 if (parseMDNode(Node))
3809 return true;
3810 if (!Node)
3811 return error("expected a MDNode after 'heap-alloc-marker'");
3812 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3813 Token.is(MIToken::lbrace))
3814 return false;
3815 if (Token.isNot(MIToken::comma))
3816 return error("expected ',' before the next machine operand");
3817 lex();
3818 return false;
3819}
3820
3821bool MIParser::parsePCSections(MDNode *&Node) {
3822 assert(Token.is(MIToken::kw_pcsections) &&
3823 "Invalid token for a PC sections!");
3824 lex();
3825 if (parseMDNode(Node))
3826 return true;
3827 if (!Node)
3828 return error("expected a MDNode after 'pcsections'");
3829 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3830 Token.is(MIToken::lbrace))
3831 return false;
3832 if (Token.isNot(MIToken::comma))
3833 return error("expected ',' before the next machine operand");
3834 lex();
3835 return false;
3836}
3837
3838bool MIParser::parseMMRA(MDNode *&Node) {
3839 assert(Token.is(MIToken::kw_mmra) && "Invalid token for MMRA!");
3840 lex();
3841 if (parseMDNode(Node))
3842 return true;
3843 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3844 Token.is(MIToken::lbrace))
3845 return false;
3846 if (Token.isNot(MIToken::comma))
3847 return error("expected ',' before the next machine operand");
3848 lex();
3849 return false;
3850}
3851
3853 const Function &F,
3854 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3855 ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
3857 for (const auto &BB : F) {
3858 if (BB.hasName())
3859 continue;
3860 int Slot = MST.getLocalSlot(&BB);
3861 if (Slot == -1)
3862 continue;
3863 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
3864 }
3865}
3866
3868 unsigned Slot,
3869 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3870 return Slots2BasicBlocks.lookup(Slot);
3871}
3872
3873const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
3874 if (Slots2BasicBlocks.empty())
3875 initSlots2BasicBlocks(MF.getFunction(), Slots2BasicBlocks);
3876 return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
3877}
3878
3879const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
3880 if (&F == &MF.getFunction())
3881 return getIRBlock(Slot);
3882 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
3883 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
3884 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
3885}
3886
3887MCSymbol *MIParser::getOrCreateMCSymbol(StringRef Name) {
3888 // FIXME: Currently we can't recognize temporary or local symbols and call all
3889 // of the appropriate forms to create them. However, this handles basic cases
3890 // well as most of the special aspects are recognized by a prefix on their
3891 // name, and the input names should already be unique. For test cases, keeping
3892 // the symbol name out of the symbol table isn't terribly important.
3893 return MF.getContext().getOrCreateSymbol(Name);
3894}
3895
3896bool MIParser::parseStringConstant(std::string &Result) {
3897 if (Token.isNot(MIToken::StringConstant))
3898 return error("expected string constant");
3899 Result = std::string(Token.stringValue());
3900 lex();
3901 return false;
3902}
3903
3905 StringRef Src,
3907 return MIParser(PFS, Error, Src).parseBasicBlockDefinitions(PFS.MBBSlots);
3908}
3909
3912 return MIParser(PFS, Error, Src).parseBasicBlocks();
3913}
3914
3918 return MIParser(PFS, Error, Src).parseStandaloneMBB(MBB);
3919}
3920
3922 Register &Reg, StringRef Src,
3924 return MIParser(PFS, Error, Src).parseStandaloneRegister(Reg);
3925}
3926
3928 Register &Reg, StringRef Src,
3930 return MIParser(PFS, Error, Src).parseStandaloneNamedRegister(Reg);
3931}
3932
3934 VRegInfo *&Info, StringRef Src,
3936 return MIParser(PFS, Error, Src).parseStandaloneVirtualRegister(Info);
3937}
3938
3941 return MIParser(PFS, Error, Src).parseStandaloneStackObject(FI);
3942}
3943
3947 return MIParser(PFS, Error, Src).parsePrefetchTarget(Target);
3948}
3951 return MIParser(PFS, Error, Src).parseStandaloneMDNode(Node);
3952}
3953
3955 SMRange SrcRange, SMDiagnostic &Error) {
3956 return MIParser(PFS, Error, Src, SrcRange).parseMachineMetadata();
3957}
3958
3960 PerFunctionMIParsingState &PFS, const Value *&V,
3961 ErrorCallbackType ErrorCallback) {
3962 MIToken Token;
3963 Src = lexMIToken(Src, Token, [&](StringRef::iterator Loc, const Twine &Msg) {
3964 ErrorCallback(Loc, Msg);
3965 });
3966 V = nullptr;
3967
3968 return ::parseIRValue(Token, PFS, V, ErrorCallback);
3969}
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).
static constexpr LLT bfloat16()
static LLT floatIEEE(unsigned SizeInBits)
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
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
LLVM_ABI std::string lower() const
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:655
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:261
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.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h: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.
@ 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