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