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