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 = getDefRegState(IsDef);
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 (!hasRegState(Flags, RegState::Define)) {
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 (hasRegState(Flags, RegState::Define)) {
1847 if (hasRegState(Flags, RegState::Kill))
1848 return error("cannot have a killed def operand");
1849 } else {
1850 if (hasRegState(Flags, RegState::Dead))
1851 return error("cannot have a dead use operand");
1852 }
1853
1863
1864 return false;
1865}
1866
1867bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
1869 const APSInt &Int = Token.integerValue();
1870 if (auto SImm = Int.trySExtValue(); Int.isSigned() && SImm.has_value())
1871 Dest = MachineOperand::CreateImm(*SImm);
1872 else if (auto UImm = Int.tryZExtValue(); !Int.isSigned() && UImm.has_value())
1873 Dest = MachineOperand::CreateImm(*UImm);
1874 else
1875 return error("integer literal is too large to be an immediate operand");
1876 lex();
1877 return false;
1878}
1879
1880bool MIParser::parseTargetImmMnemonic(const unsigned OpCode,
1881 const unsigned OpIdx,
1882 MachineOperand &Dest,
1883 const MIRFormatter &MF) {
1884 assert(Token.is(MIToken::dot));
1885 auto Loc = Token.location(); // record start position
1886 size_t Len = 1; // for "."
1887 lex();
1888
1889 // Handle the case that mnemonic starts with number.
1890 if (Token.is(MIToken::IntegerLiteral)) {
1891 Len += Token.range().size();
1892 lex();
1893 }
1894
1895 StringRef Src;
1896 if (Token.is(MIToken::comma))
1897 Src = StringRef(Loc, Len);
1898 else {
1899 assert(Token.is(MIToken::Identifier));
1900 Src = StringRef(Loc, Len + Token.stringValue().size());
1901 }
1902 int64_t Val;
1903 if (MF.parseImmMnemonic(OpCode, OpIdx, Src, Val,
1904 [this](StringRef::iterator Loc, const Twine &Msg)
1905 -> bool { return error(Loc, Msg); }))
1906 return true;
1907
1908 Dest = MachineOperand::CreateImm(Val);
1909 if (!Token.is(MIToken::comma))
1910 lex();
1911 return false;
1912}
1913
1915 PerFunctionMIParsingState &PFS, const Constant *&C,
1916 ErrorCallbackType ErrCB) {
1917 auto Source = StringValue.str(); // The source has to be null terminated.
1918 SMDiagnostic Err;
1919 C = parseConstantValue(Source, Err, *PFS.MF.getFunction().getParent(),
1920 &PFS.IRSlots);
1921 if (!C)
1922 return ErrCB(Loc + Err.getColumnNo(), Err.getMessage());
1923 return false;
1924}
1925
1926bool MIParser::parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
1927 const Constant *&C) {
1928 return ::parseIRConstant(
1929 Loc, StringValue, PFS, C,
1930 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
1931 return error(Loc, Msg);
1932 });
1933}
1934
1935bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
1936 if (parseIRConstant(Loc, StringRef(Loc, Token.range().end() - Loc), C))
1937 return true;
1938 lex();
1939 return false;
1940}
1941
1942// See LLT implementation for bit size limits.
1944 return Size != 0 && isUInt<16>(Size);
1945}
1946
1948 return NumElts != 0 && isUInt<16>(NumElts);
1949}
1950
1951static bool verifyAddrSpace(uint64_t AddrSpace) {
1952 return isUInt<24>(AddrSpace);
1953}
1954
1955bool MIParser::parseLowLevelType(StringRef::iterator Loc, LLT &Ty) {
1956 if (Token.range().front() == 's' || Token.range().front() == 'p') {
1957 StringRef SizeStr = Token.range().drop_front();
1958 if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
1959 return error("expected integers after 's'/'p' type character");
1960 }
1961
1962 if (Token.range().front() == 's') {
1963 auto ScalarSize = APSInt(Token.range().drop_front()).getZExtValue();
1964 if (ScalarSize) {
1965 if (!verifyScalarSize(ScalarSize))
1966 return error("invalid size for scalar type");
1967 Ty = LLT::scalar(ScalarSize);
1968 } else {
1969 Ty = LLT::token();
1970 }
1971 lex();
1972 return false;
1973 } else if (Token.range().front() == 'p') {
1974 const DataLayout &DL = MF.getDataLayout();
1975 uint64_t AS = APSInt(Token.range().drop_front()).getZExtValue();
1976 if (!verifyAddrSpace(AS))
1977 return error("invalid address space number");
1978
1979 Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
1980 lex();
1981 return false;
1982 }
1983
1984 // Now we're looking for a vector.
1985 if (Token.isNot(MIToken::less))
1986 return error(Loc, "expected sN, pA, <M x sN>, <M x pA>, <vscale x M x sN>, "
1987 "or <vscale x M x pA> for GlobalISel type");
1988 lex();
1989
1990 bool HasVScale =
1991 Token.is(MIToken::Identifier) && Token.stringValue() == "vscale";
1992 if (HasVScale) {
1993 lex();
1994 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
1995 return error("expected <vscale x M x sN> or <vscale x M x pA>");
1996 lex();
1997 }
1998
1999 auto GetError = [this, &HasVScale, Loc]() {
2000 if (HasVScale)
2001 return error(
2002 Loc, "expected <vscale x M x sN> or <vscale M x pA> for vector type");
2003 return error(Loc, "expected <M x sN> or <M x pA> for vector type");
2004 };
2005
2006 if (Token.isNot(MIToken::IntegerLiteral))
2007 return GetError();
2008 uint64_t NumElements = Token.integerValue().getZExtValue();
2009 if (!verifyVectorElementCount(NumElements))
2010 return error("invalid number of vector elements");
2011
2012 lex();
2013
2014 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
2015 return GetError();
2016 lex();
2017
2018 if (Token.range().front() != 's' && Token.range().front() != 'p')
2019 return GetError();
2020
2021 StringRef SizeStr = Token.range().drop_front();
2022 if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
2023 return error("expected integers after 's'/'p' type character");
2024
2025 if (Token.range().front() == 's') {
2026 auto ScalarSize = APSInt(Token.range().drop_front()).getZExtValue();
2027 if (!verifyScalarSize(ScalarSize))
2028 return error("invalid size for scalar element in vector");
2029 Ty = LLT::scalar(ScalarSize);
2030 } else if (Token.range().front() == 'p') {
2031 const DataLayout &DL = MF.getDataLayout();
2032 uint64_t AS = APSInt(Token.range().drop_front()).getZExtValue();
2033 if (!verifyAddrSpace(AS))
2034 return error("invalid address space number");
2035
2036 Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
2037 } else
2038 return GetError();
2039 lex();
2040
2041 if (Token.isNot(MIToken::greater))
2042 return GetError();
2043
2044 lex();
2045
2046 Ty = LLT::vector(ElementCount::get(NumElements, HasVScale), Ty);
2047 return false;
2048}
2049
2050bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
2051 assert(Token.is(MIToken::Identifier));
2052 StringRef TypeStr = Token.range();
2053 if (TypeStr.front() != 'i' && TypeStr.front() != 's' &&
2054 TypeStr.front() != 'p')
2055 return error(
2056 "a typed immediate operand should start with one of 'i', 's', or 'p'");
2057 StringRef SizeStr = Token.range().drop_front();
2058 if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
2059 return error("expected integers after 'i'/'s'/'p' type character");
2060
2061 auto Loc = Token.location();
2062 lex();
2063 if (Token.isNot(MIToken::IntegerLiteral)) {
2064 if (Token.isNot(MIToken::Identifier) ||
2065 !(Token.range() == "true" || Token.range() == "false"))
2066 return error("expected an integer literal");
2067 }
2068 const Constant *C = nullptr;
2069 if (parseIRConstant(Loc, C))
2070 return true;
2072 return false;
2073}
2074
2075bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
2076 auto Loc = Token.location();
2077 lex();
2078 if (Token.isNot(MIToken::FloatingPointLiteral) &&
2079 Token.isNot(MIToken::HexLiteral))
2080 return error("expected a floating point literal");
2081 const Constant *C = nullptr;
2082 if (parseIRConstant(Loc, C))
2083 return true;
2085 return false;
2086}
2087
2088static bool getHexUint(const MIToken &Token, APInt &Result) {
2090 StringRef S = Token.range();
2091 assert(S[0] == '0' && tolower(S[1]) == 'x');
2092 // This could be a floating point literal with a special prefix.
2093 if (!isxdigit(S[2]))
2094 return true;
2095 StringRef V = S.substr(2);
2096 APInt A(V.size()*4, V, 16);
2097
2098 // If A is 0, then A.getActiveBits() is 0. This isn't a valid bitwidth. Make
2099 // sure it isn't the case before constructing result.
2100 unsigned NumBits = (A == 0) ? 32 : A.getActiveBits();
2101 Result = APInt(NumBits, ArrayRef<uint64_t>(A.getRawData(), A.getNumWords()));
2102 return false;
2103}
2104
2105static bool getUnsigned(const MIToken &Token, unsigned &Result,
2106 ErrorCallbackType ErrCB) {
2107 if (Token.hasIntegerValue()) {
2108 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
2109 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
2110 if (Val64 == Limit)
2111 return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2112 Result = Val64;
2113 return false;
2114 }
2115 if (Token.is(MIToken::HexLiteral)) {
2116 APInt A;
2117 if (getHexUint(Token, A))
2118 return true;
2119 if (A.getBitWidth() > 32)
2120 return ErrCB(Token.location(), "expected 32-bit integer (too large)");
2121 Result = A.getZExtValue();
2122 return false;
2123 }
2124 return true;
2125}
2126
2127bool MIParser::getUnsigned(unsigned &Result) {
2128 return ::getUnsigned(
2129 Token, Result, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2130 return error(Loc, Msg);
2131 });
2132}
2133
2134bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
2137 unsigned Number;
2138 if (getUnsigned(Number))
2139 return true;
2140 auto MBBInfo = PFS.MBBSlots.find(Number);
2141 if (MBBInfo == PFS.MBBSlots.end())
2142 return error(Twine("use of undefined machine basic block #") +
2143 Twine(Number));
2144 MBB = MBBInfo->second;
2145 // TODO: Only parse the name if it's a MachineBasicBlockLabel. Deprecate once
2146 // we drop the <irname> from the bb.<id>.<irname> format.
2147 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
2148 return error(Twine("the name of machine basic block #") + Twine(Number) +
2149 " isn't '" + Token.stringValue() + "'");
2150 return false;
2151}
2152
2153bool MIParser::parseMBBOperand(MachineOperand &Dest) {
2156 return true;
2158 lex();
2159 return false;
2160}
2161
2162bool MIParser::parseStackFrameIndex(int &FI) {
2163 assert(Token.is(MIToken::StackObject));
2164 unsigned ID;
2165 if (getUnsigned(ID))
2166 return true;
2167 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
2168 if (ObjectInfo == PFS.StackObjectSlots.end())
2169 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
2170 "'");
2172 if (const auto *Alloca =
2173 MF.getFrameInfo().getObjectAllocation(ObjectInfo->second))
2174 Name = Alloca->getName();
2175 if (!Token.stringValue().empty() && Token.stringValue() != Name)
2176 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
2177 "' isn't '" + Token.stringValue() + "'");
2178 lex();
2179 FI = ObjectInfo->second;
2180 return false;
2181}
2182
2183bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
2184 int FI;
2185 if (parseStackFrameIndex(FI))
2186 return true;
2187 Dest = MachineOperand::CreateFI(FI);
2188 return false;
2189}
2190
2191bool MIParser::parseFixedStackFrameIndex(int &FI) {
2193 unsigned ID;
2194 if (getUnsigned(ID))
2195 return true;
2196 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
2197 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
2198 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
2199 Twine(ID) + "'");
2200 lex();
2201 FI = ObjectInfo->second;
2202 return false;
2203}
2204
2205bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
2206 int FI;
2207 if (parseFixedStackFrameIndex(FI))
2208 return true;
2209 Dest = MachineOperand::CreateFI(FI);
2210 return false;
2211}
2212
2213static bool parseGlobalValue(const MIToken &Token,
2215 ErrorCallbackType ErrCB) {
2216 switch (Token.kind()) {
2218 const Module *M = PFS.MF.getFunction().getParent();
2219 GV = M->getNamedValue(Token.stringValue());
2220 if (!GV)
2221 return ErrCB(Token.location(), Twine("use of undefined global value '") +
2222 Token.range() + "'");
2223 break;
2224 }
2225 case MIToken::GlobalValue: {
2226 unsigned GVIdx;
2227 if (getUnsigned(Token, GVIdx, ErrCB))
2228 return true;
2229 GV = PFS.IRSlots.GlobalValues.get(GVIdx);
2230 if (!GV)
2231 return ErrCB(Token.location(), Twine("use of undefined global value '@") +
2232 Twine(GVIdx) + "'");
2233 break;
2234 }
2235 default:
2236 llvm_unreachable("The current token should be a global value");
2237 }
2238 return false;
2239}
2240
2241bool MIParser::parseGlobalValue(GlobalValue *&GV) {
2242 return ::parseGlobalValue(
2243 Token, PFS, GV,
2244 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
2245 return error(Loc, Msg);
2246 });
2247}
2248
2249bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
2250 GlobalValue *GV = nullptr;
2251 if (parseGlobalValue(GV))
2252 return true;
2253 lex();
2254 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
2255 if (parseOperandsOffset(Dest))
2256 return true;
2257 return false;
2258}
2259
2260bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
2262 unsigned ID;
2263 if (getUnsigned(ID))
2264 return true;
2265 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
2266 if (ConstantInfo == PFS.ConstantPoolSlots.end())
2267 return error("use of undefined constant '%const." + Twine(ID) + "'");
2268 lex();
2269 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
2270 if (parseOperandsOffset(Dest))
2271 return true;
2272 return false;
2273}
2274
2275bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
2277 unsigned ID;
2278 if (getUnsigned(ID))
2279 return true;
2280 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
2281 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
2282 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
2283 lex();
2284 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
2285 return false;
2286}
2287
2288bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
2290 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
2291 lex();
2292 Dest = MachineOperand::CreateES(Symbol);
2293 if (parseOperandsOffset(Dest))
2294 return true;
2295 return false;
2296}
2297
2298bool MIParser::parseMCSymbolOperand(MachineOperand &Dest) {
2299 assert(Token.is(MIToken::MCSymbol));
2300 MCSymbol *Symbol = getOrCreateMCSymbol(Token.stringValue());
2301 lex();
2302 Dest = MachineOperand::CreateMCSymbol(Symbol);
2303 if (parseOperandsOffset(Dest))
2304 return true;
2305 return false;
2306}
2307
2308bool MIParser::parseSubRegisterIndexOperand(MachineOperand &Dest) {
2310 StringRef Name = Token.stringValue();
2311 unsigned SubRegIndex = PFS.Target.getSubRegIndex(Token.stringValue());
2312 if (SubRegIndex == 0)
2313 return error(Twine("unknown subregister index '") + Name + "'");
2314 lex();
2315 Dest = MachineOperand::CreateImm(SubRegIndex);
2316 return false;
2317}
2318
2319bool MIParser::parseMDNode(MDNode *&Node) {
2320 assert(Token.is(MIToken::exclaim));
2321
2322 auto Loc = Token.location();
2323 lex();
2324 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
2325 return error("expected metadata id after '!'");
2326 unsigned ID;
2327 if (getUnsigned(ID))
2328 return true;
2329 auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID);
2330 if (NodeInfo == PFS.IRSlots.MetadataNodes.end()) {
2331 NodeInfo = PFS.MachineMetadataNodes.find(ID);
2332 if (NodeInfo == PFS.MachineMetadataNodes.end())
2333 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
2334 }
2335 lex();
2336 Node = NodeInfo->second.get();
2337 return false;
2338}
2339
2340bool MIParser::parseDIExpression(MDNode *&Expr) {
2341 unsigned Read;
2343 CurrentSource, Read, Error, *PFS.MF.getFunction().getParent(),
2344 &PFS.IRSlots);
2345 CurrentSource = CurrentSource.substr(Read);
2346 lex();
2347 if (!Expr)
2348 return error(Error.getMessage());
2349 return false;
2350}
2351
2352bool MIParser::parseDILocation(MDNode *&Loc) {
2353 assert(Token.is(MIToken::md_dilocation));
2354 lex();
2355
2356 bool HaveLine = false;
2357 unsigned Line = 0;
2358 unsigned Column = 0;
2359 MDNode *Scope = nullptr;
2360 MDNode *InlinedAt = nullptr;
2361 bool ImplicitCode = false;
2362 uint64_t AtomGroup = 0;
2363 uint64_t AtomRank = 0;
2364
2365 if (expectAndConsume(MIToken::lparen))
2366 return true;
2367
2368 if (Token.isNot(MIToken::rparen)) {
2369 do {
2370 if (Token.is(MIToken::Identifier)) {
2371 if (Token.stringValue() == "line") {
2372 lex();
2373 if (expectAndConsume(MIToken::colon))
2374 return true;
2375 if (Token.isNot(MIToken::IntegerLiteral) ||
2376 Token.integerValue().isSigned())
2377 return error("expected unsigned integer");
2378 Line = Token.integerValue().getZExtValue();
2379 HaveLine = true;
2380 lex();
2381 continue;
2382 }
2383 if (Token.stringValue() == "column") {
2384 lex();
2385 if (expectAndConsume(MIToken::colon))
2386 return true;
2387 if (Token.isNot(MIToken::IntegerLiteral) ||
2388 Token.integerValue().isSigned())
2389 return error("expected unsigned integer");
2390 Column = Token.integerValue().getZExtValue();
2391 lex();
2392 continue;
2393 }
2394 if (Token.stringValue() == "scope") {
2395 lex();
2396 if (expectAndConsume(MIToken::colon))
2397 return true;
2398 if (parseMDNode(Scope))
2399 return error("expected metadata node");
2400 if (!isa<DIScope>(Scope))
2401 return error("expected DIScope node");
2402 continue;
2403 }
2404 if (Token.stringValue() == "inlinedAt") {
2405 lex();
2406 if (expectAndConsume(MIToken::colon))
2407 return true;
2408 if (Token.is(MIToken::exclaim)) {
2409 if (parseMDNode(InlinedAt))
2410 return true;
2411 } else if (Token.is(MIToken::md_dilocation)) {
2412 if (parseDILocation(InlinedAt))
2413 return true;
2414 } else
2415 return error("expected metadata node");
2416 if (!isa<DILocation>(InlinedAt))
2417 return error("expected DILocation node");
2418 continue;
2419 }
2420 if (Token.stringValue() == "isImplicitCode") {
2421 lex();
2422 if (expectAndConsume(MIToken::colon))
2423 return true;
2424 if (!Token.is(MIToken::Identifier))
2425 return error("expected true/false");
2426 // As far as I can see, we don't have any existing need for parsing
2427 // true/false in MIR yet. Do it ad-hoc until there's something else
2428 // that needs it.
2429 if (Token.stringValue() == "true")
2430 ImplicitCode = true;
2431 else if (Token.stringValue() == "false")
2432 ImplicitCode = false;
2433 else
2434 return error("expected true/false");
2435 lex();
2436 continue;
2437 }
2438 if (Token.stringValue() == "atomGroup") {
2439 lex();
2440 if (expectAndConsume(MIToken::colon))
2441 return true;
2442 if (Token.isNot(MIToken::IntegerLiteral) ||
2443 Token.integerValue().isSigned())
2444 return error("expected unsigned integer");
2445 AtomGroup = Token.integerValue().getZExtValue();
2446 lex();
2447 continue;
2448 }
2449 if (Token.stringValue() == "atomRank") {
2450 lex();
2451 if (expectAndConsume(MIToken::colon))
2452 return true;
2453 if (Token.isNot(MIToken::IntegerLiteral) ||
2454 Token.integerValue().isSigned())
2455 return error("expected unsigned integer");
2456 AtomRank = Token.integerValue().getZExtValue();
2457 lex();
2458 continue;
2459 }
2460 }
2461 return error(Twine("invalid DILocation argument '") +
2462 Token.stringValue() + "'");
2463 } while (consumeIfPresent(MIToken::comma));
2464 }
2465
2466 if (expectAndConsume(MIToken::rparen))
2467 return true;
2468
2469 if (!HaveLine)
2470 return error("DILocation requires line number");
2471 if (!Scope)
2472 return error("DILocation requires a scope");
2473
2474 Loc = DILocation::get(MF.getFunction().getContext(), Line, Column, Scope,
2475 InlinedAt, ImplicitCode, AtomGroup, AtomRank);
2476 return false;
2477}
2478
2479bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
2480 MDNode *Node = nullptr;
2481 if (Token.is(MIToken::exclaim)) {
2482 if (parseMDNode(Node))
2483 return true;
2484 } else if (Token.is(MIToken::md_diexpr)) {
2485 if (parseDIExpression(Node))
2486 return true;
2487 }
2488 Dest = MachineOperand::CreateMetadata(Node);
2489 return false;
2490}
2491
2492bool MIParser::parseCFIOffset(int &Offset) {
2493 if (Token.isNot(MIToken::IntegerLiteral))
2494 return error("expected a cfi offset");
2495 if (Token.integerValue().getSignificantBits() > 32)
2496 return error("expected a 32 bit integer (the cfi offset is too large)");
2497 Offset = (int)Token.integerValue().getExtValue();
2498 lex();
2499 return false;
2500}
2501
2502bool MIParser::parseCFIRegister(unsigned &Reg) {
2503 if (Token.isNot(MIToken::NamedRegister))
2504 return error("expected a cfi register");
2505 Register LLVMReg;
2506 if (parseNamedRegister(LLVMReg))
2507 return true;
2508 const auto *TRI = MF.getSubtarget().getRegisterInfo();
2509 assert(TRI && "Expected target register info");
2510 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
2511 if (DwarfReg < 0)
2512 return error("invalid DWARF register");
2513 Reg = (unsigned)DwarfReg;
2514 lex();
2515 return false;
2516}
2517
2518bool MIParser::parseCFIAddressSpace(unsigned &AddressSpace) {
2519 if (Token.isNot(MIToken::IntegerLiteral))
2520 return error("expected a cfi address space literal");
2521 if (Token.integerValue().isSigned())
2522 return error("expected an unsigned integer (cfi address space)");
2523 AddressSpace = Token.integerValue().getZExtValue();
2524 lex();
2525 return false;
2526}
2527
2528bool MIParser::parseCFIEscapeValues(std::string &Values) {
2529 do {
2530 if (Token.isNot(MIToken::HexLiteral))
2531 return error("expected a hexadecimal literal");
2532 unsigned Value;
2533 if (getUnsigned(Value))
2534 return true;
2535 if (Value > UINT8_MAX)
2536 return error("expected a 8-bit integer (too large)");
2537 Values.push_back(static_cast<uint8_t>(Value));
2538 lex();
2539 } while (consumeIfPresent(MIToken::comma));
2540 return false;
2541}
2542
2543bool MIParser::parseCFIOperand(MachineOperand &Dest) {
2544 auto Kind = Token.kind();
2545 lex();
2546 int Offset;
2547 unsigned Reg;
2548 unsigned AddressSpace;
2549 unsigned CFIIndex;
2550 switch (Kind) {
2552 if (parseCFIRegister(Reg))
2553 return true;
2554 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
2555 break;
2557 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2558 parseCFIOffset(Offset))
2559 return true;
2560 CFIIndex =
2561 MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
2562 break;
2564 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2565 parseCFIOffset(Offset))
2566 return true;
2567 CFIIndex = MF.addFrameInst(
2569 break;
2571 if (parseCFIRegister(Reg))
2572 return true;
2573 CFIIndex =
2574 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
2575 break;
2577 if (parseCFIOffset(Offset))
2578 return true;
2579 CFIIndex =
2580 MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, Offset));
2581 break;
2583 if (parseCFIOffset(Offset))
2584 return true;
2585 CFIIndex = MF.addFrameInst(
2587 break;
2589 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2590 parseCFIOffset(Offset))
2591 return true;
2592 CFIIndex =
2593 MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, Offset));
2594 break;
2596 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2597 parseCFIOffset(Offset) || expectAndConsume(MIToken::comma) ||
2598 parseCFIAddressSpace(AddressSpace))
2599 return true;
2600 CFIIndex = MF.addFrameInst(MCCFIInstruction::createLLVMDefAspaceCfa(
2601 nullptr, Reg, Offset, AddressSpace, SMLoc()));
2602 break;
2604 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRememberState(nullptr));
2605 break;
2607 if (parseCFIRegister(Reg))
2608 return true;
2609 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, Reg));
2610 break;
2612 CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestoreState(nullptr));
2613 break;
2615 if (parseCFIRegister(Reg))
2616 return true;
2617 CFIIndex = MF.addFrameInst(MCCFIInstruction::createUndefined(nullptr, Reg));
2618 break;
2620 unsigned Reg2;
2621 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
2622 parseCFIRegister(Reg2))
2623 return true;
2624
2625 CFIIndex =
2626 MF.addFrameInst(MCCFIInstruction::createRegister(nullptr, Reg, Reg2));
2627 break;
2628 }
2630 CFIIndex = MF.addFrameInst(MCCFIInstruction::createWindowSave(nullptr));
2631 break;
2633 CFIIndex = MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
2634 break;
2636 CFIIndex =
2637 MF.addFrameInst(MCCFIInstruction::createNegateRAStateWithPC(nullptr));
2638 break;
2640 std::string Values;
2641 if (parseCFIEscapeValues(Values))
2642 return true;
2643 CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(nullptr, Values));
2644 break;
2645 }
2646 default:
2647 // TODO: Parse the other CFI operands.
2648 llvm_unreachable("The current token should be a cfi operand");
2649 }
2650 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
2651 return false;
2652}
2653
2654bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
2655 switch (Token.kind()) {
2656 case MIToken::NamedIRBlock: {
2658 F.getValueSymbolTable()->lookup(Token.stringValue()));
2659 if (!BB)
2660 return error(Twine("use of undefined IR block '") + Token.range() + "'");
2661 break;
2662 }
2663 case MIToken::IRBlock: {
2664 unsigned SlotNumber = 0;
2665 if (getUnsigned(SlotNumber))
2666 return true;
2667 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
2668 if (!BB)
2669 return error(Twine("use of undefined IR block '%ir-block.") +
2670 Twine(SlotNumber) + "'");
2671 break;
2672 }
2673 default:
2674 llvm_unreachable("The current token should be an IR block reference");
2675 }
2676 return false;
2677}
2678
2679bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
2681 lex();
2682 if (expectAndConsume(MIToken::lparen))
2683 return true;
2684 if (Token.isNot(MIToken::GlobalValue) &&
2685 Token.isNot(MIToken::NamedGlobalValue))
2686 return error("expected a global value");
2687 GlobalValue *GV = nullptr;
2688 if (parseGlobalValue(GV))
2689 return true;
2690 auto *F = dyn_cast<Function>(GV);
2691 if (!F)
2692 return error("expected an IR function reference");
2693 lex();
2694 if (expectAndConsume(MIToken::comma))
2695 return true;
2696 BasicBlock *BB = nullptr;
2697 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
2698 return error("expected an IR block reference");
2699 if (parseIRBlock(BB, *F))
2700 return true;
2701 lex();
2702 if (expectAndConsume(MIToken::rparen))
2703 return true;
2704 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
2705 if (parseOperandsOffset(Dest))
2706 return true;
2707 return false;
2708}
2709
2710bool MIParser::parseIntrinsicOperand(MachineOperand &Dest) {
2711 assert(Token.is(MIToken::kw_intrinsic));
2712 lex();
2713 if (expectAndConsume(MIToken::lparen))
2714 return error("expected syntax intrinsic(@llvm.whatever)");
2715
2716 if (Token.isNot(MIToken::NamedGlobalValue))
2717 return error("expected syntax intrinsic(@llvm.whatever)");
2718
2719 std::string Name = std::string(Token.stringValue());
2720 lex();
2721
2722 if (expectAndConsume(MIToken::rparen))
2723 return error("expected ')' to terminate intrinsic name");
2724
2725 // Find out what intrinsic we're dealing with.
2728 return error("unknown intrinsic name");
2730
2731 return false;
2732}
2733
2734bool MIParser::parsePredicateOperand(MachineOperand &Dest) {
2735 assert(Token.is(MIToken::kw_intpred) || Token.is(MIToken::kw_floatpred));
2736 bool IsFloat = Token.is(MIToken::kw_floatpred);
2737 lex();
2738
2739 if (expectAndConsume(MIToken::lparen))
2740 return error("expected syntax intpred(whatever) or floatpred(whatever");
2741
2742 if (Token.isNot(MIToken::Identifier))
2743 return error("whatever");
2744
2745 CmpInst::Predicate Pred;
2746 if (IsFloat) {
2747 Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2748 .Case("false", CmpInst::FCMP_FALSE)
2749 .Case("oeq", CmpInst::FCMP_OEQ)
2750 .Case("ogt", CmpInst::FCMP_OGT)
2751 .Case("oge", CmpInst::FCMP_OGE)
2752 .Case("olt", CmpInst::FCMP_OLT)
2753 .Case("ole", CmpInst::FCMP_OLE)
2754 .Case("one", CmpInst::FCMP_ONE)
2755 .Case("ord", CmpInst::FCMP_ORD)
2756 .Case("uno", CmpInst::FCMP_UNO)
2757 .Case("ueq", CmpInst::FCMP_UEQ)
2758 .Case("ugt", CmpInst::FCMP_UGT)
2759 .Case("uge", CmpInst::FCMP_UGE)
2760 .Case("ult", CmpInst::FCMP_ULT)
2761 .Case("ule", CmpInst::FCMP_ULE)
2762 .Case("une", CmpInst::FCMP_UNE)
2763 .Case("true", CmpInst::FCMP_TRUE)
2765 if (!CmpInst::isFPPredicate(Pred))
2766 return error("invalid floating-point predicate");
2767 } else {
2768 Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2769 .Case("eq", CmpInst::ICMP_EQ)
2770 .Case("ne", CmpInst::ICMP_NE)
2771 .Case("sgt", CmpInst::ICMP_SGT)
2772 .Case("sge", CmpInst::ICMP_SGE)
2773 .Case("slt", CmpInst::ICMP_SLT)
2774 .Case("sle", CmpInst::ICMP_SLE)
2775 .Case("ugt", CmpInst::ICMP_UGT)
2776 .Case("uge", CmpInst::ICMP_UGE)
2777 .Case("ult", CmpInst::ICMP_ULT)
2778 .Case("ule", CmpInst::ICMP_ULE)
2780 if (!CmpInst::isIntPredicate(Pred))
2781 return error("invalid integer predicate");
2782 }
2783
2784 lex();
2786 if (expectAndConsume(MIToken::rparen))
2787 return error("predicate should be terminated by ')'.");
2788
2789 return false;
2790}
2791
2792bool MIParser::parseShuffleMaskOperand(MachineOperand &Dest) {
2794
2795 lex();
2796 if (expectAndConsume(MIToken::lparen))
2797 return error("expected syntax shufflemask(<integer or undef>, ...)");
2798
2799 SmallVector<int, 32> ShufMask;
2800 do {
2801 if (Token.is(MIToken::kw_undef)) {
2802 ShufMask.push_back(-1);
2803 } else if (Token.is(MIToken::IntegerLiteral)) {
2804 const APSInt &Int = Token.integerValue();
2805 ShufMask.push_back(Int.getExtValue());
2806 } else
2807 return error("expected integer constant");
2808
2809 lex();
2810 } while (consumeIfPresent(MIToken::comma));
2811
2812 if (expectAndConsume(MIToken::rparen))
2813 return error("shufflemask should be terminated by ')'.");
2814
2815 if (ShufMask.size() < 2)
2816 return error("shufflemask should have > 1 element");
2817
2818 ArrayRef<int> MaskAlloc = MF.allocateShuffleMask(ShufMask);
2819 Dest = MachineOperand::CreateShuffleMask(MaskAlloc);
2820 return false;
2821}
2822
2823bool MIParser::parseDbgInstrRefOperand(MachineOperand &Dest) {
2825
2826 lex();
2827 if (expectAndConsume(MIToken::lparen))
2828 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
2829
2830 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
2831 return error("expected unsigned integer for instruction index");
2832 uint64_t InstrIdx = Token.integerValue().getZExtValue();
2833 assert(InstrIdx <= std::numeric_limits<unsigned>::max() &&
2834 "Instruction reference's instruction index is too large");
2835 lex();
2836
2837 if (expectAndConsume(MIToken::comma))
2838 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
2839
2840 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isNegative())
2841 return error("expected unsigned integer for operand index");
2842 uint64_t OpIdx = Token.integerValue().getZExtValue();
2843 assert(OpIdx <= std::numeric_limits<unsigned>::max() &&
2844 "Instruction reference's operand index is too large");
2845 lex();
2846
2847 if (expectAndConsume(MIToken::rparen))
2848 return error("expected syntax dbg-instr-ref(<unsigned>, <unsigned>)");
2849
2850 Dest = MachineOperand::CreateDbgInstrRef(InstrIdx, OpIdx);
2851 return false;
2852}
2853
2854bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
2856 lex();
2857 if (expectAndConsume(MIToken::lparen))
2858 return true;
2859 if (Token.isNot(MIToken::Identifier))
2860 return error("expected the name of the target index");
2861 int Index = 0;
2862 if (PFS.Target.getTargetIndex(Token.stringValue(), Index))
2863 return error("use of undefined target index '" + Token.stringValue() + "'");
2864 lex();
2865 if (expectAndConsume(MIToken::rparen))
2866 return true;
2867 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
2868 if (parseOperandsOffset(Dest))
2869 return true;
2870 return false;
2871}
2872
2873bool MIParser::parseCustomRegisterMaskOperand(MachineOperand &Dest) {
2874 assert(Token.stringValue() == "CustomRegMask" && "Expected a custom RegMask");
2875 lex();
2876 if (expectAndConsume(MIToken::lparen))
2877 return true;
2878
2879 uint32_t *Mask = MF.allocateRegMask();
2880 do {
2881 if (Token.isNot(MIToken::rparen)) {
2882 if (Token.isNot(MIToken::NamedRegister))
2883 return error("expected a named register");
2884 Register Reg;
2885 if (parseNamedRegister(Reg))
2886 return true;
2887 lex();
2888 Mask[Reg.id() / 32] |= 1U << (Reg.id() % 32);
2889 }
2890
2891 // TODO: Report an error if the same register is used more than once.
2892 } while (consumeIfPresent(MIToken::comma));
2893
2894 if (expectAndConsume(MIToken::rparen))
2895 return true;
2896 Dest = MachineOperand::CreateRegMask(Mask);
2897 return false;
2898}
2899
2900bool MIParser::parseLaneMaskOperand(MachineOperand &Dest) {
2901 assert(Token.is(MIToken::kw_lanemask));
2902
2903 lex();
2904 if (expectAndConsume(MIToken::lparen))
2905 return true;
2906
2907 // Parse lanemask.
2908 if (Token.isNot(MIToken::IntegerLiteral) && Token.isNot(MIToken::HexLiteral))
2909 return error("expected a valid lane mask value");
2910 static_assert(sizeof(LaneBitmask::Type) == sizeof(uint64_t),
2911 "Use correct get-function for lane mask.");
2913 if (getUint64(V))
2914 return true;
2915 LaneBitmask LaneMask(V);
2916 lex();
2917
2918 if (expectAndConsume(MIToken::rparen))
2919 return true;
2920
2921 Dest = MachineOperand::CreateLaneMask(LaneMask);
2922 return false;
2923}
2924
2925bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
2926 assert(Token.is(MIToken::kw_liveout));
2927 uint32_t *Mask = MF.allocateRegMask();
2928 lex();
2929 if (expectAndConsume(MIToken::lparen))
2930 return true;
2931 while (true) {
2932 if (Token.isNot(MIToken::NamedRegister))
2933 return error("expected a named register");
2934 Register Reg;
2935 if (parseNamedRegister(Reg))
2936 return true;
2937 lex();
2938 Mask[Reg.id() / 32] |= 1U << (Reg.id() % 32);
2939 // TODO: Report an error if the same register is used more than once.
2940 if (Token.isNot(MIToken::comma))
2941 break;
2942 lex();
2943 }
2944 if (expectAndConsume(MIToken::rparen))
2945 return true;
2947 return false;
2948}
2949
2950bool MIParser::parseMachineOperand(const unsigned OpCode, const unsigned OpIdx,
2951 MachineOperand &Dest,
2952 std::optional<unsigned> &TiedDefIdx) {
2953 switch (Token.kind()) {
2956 case MIToken::kw_def:
2957 case MIToken::kw_dead:
2958 case MIToken::kw_killed:
2959 case MIToken::kw_undef:
2968 return parseRegisterOperand(Dest, TiedDefIdx);
2970 return parseImmediateOperand(Dest);
2971 case MIToken::kw_half:
2972 case MIToken::kw_bfloat:
2973 case MIToken::kw_float:
2974 case MIToken::kw_double:
2976 case MIToken::kw_fp128:
2978 return parseFPImmediateOperand(Dest);
2980 return parseMBBOperand(Dest);
2982 return parseStackObjectOperand(Dest);
2984 return parseFixedStackObjectOperand(Dest);
2987 return parseGlobalAddressOperand(Dest);
2989 return parseConstantPoolIndexOperand(Dest);
2991 return parseJumpTableIndexOperand(Dest);
2993 return parseExternalSymbolOperand(Dest);
2994 case MIToken::MCSymbol:
2995 return parseMCSymbolOperand(Dest);
2997 return parseSubRegisterIndexOperand(Dest);
2998 case MIToken::md_diexpr:
2999 case MIToken::exclaim:
3000 return parseMetadataOperand(Dest);
3018 return parseCFIOperand(Dest);
3020 return parseBlockAddressOperand(Dest);
3022 return parseIntrinsicOperand(Dest);
3024 return parseTargetIndexOperand(Dest);
3026 return parseLaneMaskOperand(Dest);
3028 return parseLiveoutRegisterMaskOperand(Dest);
3031 return parsePredicateOperand(Dest);
3033 return parseShuffleMaskOperand(Dest);
3035 return parseDbgInstrRefOperand(Dest);
3036 case MIToken::Error:
3037 return true;
3039 if (const auto *RegMask = PFS.Target.getRegMask(Token.stringValue())) {
3040 Dest = MachineOperand::CreateRegMask(RegMask);
3041 lex();
3042 break;
3043 } else if (Token.stringValue() == "CustomRegMask") {
3044 return parseCustomRegisterMaskOperand(Dest);
3045 } else
3046 return parseTypedImmediateOperand(Dest);
3047 case MIToken::dot: {
3048 const auto *TII = MF.getSubtarget().getInstrInfo();
3049 if (const auto *Formatter = TII->getMIRFormatter()) {
3050 return parseTargetImmMnemonic(OpCode, OpIdx, Dest, *Formatter);
3051 }
3052 [[fallthrough]];
3053 }
3054 default:
3055 // FIXME: Parse the MCSymbol machine operand.
3056 return error("expected a machine operand");
3057 }
3058 return false;
3059}
3060
3061bool MIParser::parseMachineOperandAndTargetFlags(
3062 const unsigned OpCode, const unsigned OpIdx, MachineOperand &Dest,
3063 std::optional<unsigned> &TiedDefIdx) {
3064 unsigned TF = 0;
3065 bool HasTargetFlags = false;
3066 if (Token.is(MIToken::kw_target_flags)) {
3067 HasTargetFlags = true;
3068 lex();
3069 if (expectAndConsume(MIToken::lparen))
3070 return true;
3071 if (Token.isNot(MIToken::Identifier))
3072 return error("expected the name of the target flag");
3073 if (PFS.Target.getDirectTargetFlag(Token.stringValue(), TF)) {
3074 if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), TF))
3075 return error("use of undefined target flag '" + Token.stringValue() +
3076 "'");
3077 }
3078 lex();
3079 while (Token.is(MIToken::comma)) {
3080 lex();
3081 if (Token.isNot(MIToken::Identifier))
3082 return error("expected the name of the target flag");
3083 unsigned BitFlag = 0;
3084 if (PFS.Target.getBitmaskTargetFlag(Token.stringValue(), BitFlag))
3085 return error("use of undefined target flag '" + Token.stringValue() +
3086 "'");
3087 // TODO: Report an error when using a duplicate bit target flag.
3088 TF |= BitFlag;
3089 lex();
3090 }
3091 if (expectAndConsume(MIToken::rparen))
3092 return true;
3093 }
3094 auto Loc = Token.location();
3095 if (parseMachineOperand(OpCode, OpIdx, Dest, TiedDefIdx))
3096 return true;
3097 if (!HasTargetFlags)
3098 return false;
3099 if (Dest.isReg())
3100 return error(Loc, "register operands can't have target flags");
3101 Dest.setTargetFlags(TF);
3102 return false;
3103}
3104
3105bool MIParser::parseOffset(int64_t &Offset) {
3106 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
3107 return false;
3108 StringRef Sign = Token.range();
3109 bool IsNegative = Token.is(MIToken::minus);
3110 lex();
3111 if (Token.isNot(MIToken::IntegerLiteral))
3112 return error("expected an integer literal after '" + Sign + "'");
3113 if (Token.integerValue().getSignificantBits() > 64)
3114 return error("expected 64-bit integer (too large)");
3115 Offset = Token.integerValue().getExtValue();
3116 if (IsNegative)
3117 Offset = -Offset;
3118 lex();
3119 return false;
3120}
3121
3122bool MIParser::parseIRBlockAddressTaken(BasicBlock *&BB) {
3124 lex();
3125 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
3126 return error("expected basic block after 'ir_block_address_taken'");
3127
3128 if (parseIRBlock(BB, MF.getFunction()))
3129 return true;
3130
3131 lex();
3132 return false;
3133}
3134
3135bool MIParser::parseAlignment(uint64_t &Alignment) {
3136 assert(Token.is(MIToken::kw_align) || Token.is(MIToken::kw_basealign));
3137 lex();
3138 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3139 return error("expected an integer literal after 'align'");
3140 if (getUint64(Alignment))
3141 return true;
3142 lex();
3143
3144 if (!isPowerOf2_64(Alignment))
3145 return error("expected a power-of-2 literal after 'align'");
3146
3147 return false;
3148}
3149
3150bool MIParser::parseAddrspace(unsigned &Addrspace) {
3151 assert(Token.is(MIToken::kw_addrspace));
3152 lex();
3153 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
3154 return error("expected an integer literal after 'addrspace'");
3155 if (getUnsigned(Addrspace))
3156 return true;
3157 lex();
3158 return false;
3159}
3160
3161bool MIParser::parseOperandsOffset(MachineOperand &Op) {
3162 int64_t Offset = 0;
3163 if (parseOffset(Offset))
3164 return true;
3165 Op.setOffset(Offset);
3166 return false;
3167}
3168
3169static bool parseIRValue(const MIToken &Token, PerFunctionMIParsingState &PFS,
3170 const Value *&V, ErrorCallbackType ErrCB) {
3171 switch (Token.kind()) {
3172 case MIToken::NamedIRValue: {
3173 V = PFS.MF.getFunction().getValueSymbolTable()->lookup(Token.stringValue());
3174 break;
3175 }
3176 case MIToken::IRValue: {
3177 unsigned SlotNumber = 0;
3178 if (getUnsigned(Token, SlotNumber, ErrCB))
3179 return true;
3180 V = PFS.getIRValue(SlotNumber);
3181 break;
3182 }
3184 case MIToken::GlobalValue: {
3185 GlobalValue *GV = nullptr;
3186 if (parseGlobalValue(Token, PFS, GV, ErrCB))
3187 return true;
3188 V = GV;
3189 break;
3190 }
3192 const Constant *C = nullptr;
3193 if (parseIRConstant(Token.location(), Token.stringValue(), PFS, C, ErrCB))
3194 return true;
3195 V = C;
3196 break;
3197 }
3199 V = nullptr;
3200 return false;
3201 default:
3202 llvm_unreachable("The current token should be an IR block reference");
3203 }
3204 if (!V)
3205 return ErrCB(Token.location(), Twine("use of undefined IR value '") + Token.range() + "'");
3206 return false;
3207}
3208
3209bool MIParser::parseIRValue(const Value *&V) {
3210 return ::parseIRValue(
3211 Token, PFS, V, [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3212 return error(Loc, Msg);
3213 });
3214}
3215
3216bool MIParser::getUint64(uint64_t &Result) {
3217 if (Token.hasIntegerValue()) {
3218 if (Token.integerValue().getActiveBits() > 64)
3219 return error("expected 64-bit integer (too large)");
3220 Result = Token.integerValue().getZExtValue();
3221 return false;
3222 }
3223 if (Token.is(MIToken::HexLiteral)) {
3224 APInt A;
3225 if (getHexUint(A))
3226 return true;
3227 if (A.getBitWidth() > 64)
3228 return error("expected 64-bit integer (too large)");
3229 Result = A.getZExtValue();
3230 return false;
3231 }
3232 return true;
3233}
3234
3235bool MIParser::getHexUint(APInt &Result) {
3236 return ::getHexUint(Token, Result);
3237}
3238
3239bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags &Flags) {
3240 const auto OldFlags = Flags;
3241 switch (Token.kind()) {
3244 break;
3247 break;
3250 break;
3253 break;
3256 if (PFS.Target.getMMOTargetFlag(Token.stringValue(), TF))
3257 return error("use of undefined target MMO flag '" + Token.stringValue() +
3258 "'");
3259 Flags |= TF;
3260 break;
3261 }
3262 default:
3263 llvm_unreachable("The current token should be a memory operand flag");
3264 }
3265 if (OldFlags == Flags)
3266 // We know that the same flag is specified more than once when the flags
3267 // weren't modified.
3268 return error("duplicate '" + Token.stringValue() + "' memory operand flag");
3269 lex();
3270 return false;
3271}
3272
3273bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
3274 switch (Token.kind()) {
3275 case MIToken::kw_stack:
3276 PSV = MF.getPSVManager().getStack();
3277 break;
3278 case MIToken::kw_got:
3279 PSV = MF.getPSVManager().getGOT();
3280 break;
3282 PSV = MF.getPSVManager().getJumpTable();
3283 break;
3285 PSV = MF.getPSVManager().getConstantPool();
3286 break;
3288 int FI;
3289 if (parseFixedStackFrameIndex(FI))
3290 return true;
3291 PSV = MF.getPSVManager().getFixedStack(FI);
3292 // The token was already consumed, so use return here instead of break.
3293 return false;
3294 }
3295 case MIToken::StackObject: {
3296 int FI;
3297 if (parseStackFrameIndex(FI))
3298 return true;
3299 PSV = MF.getPSVManager().getFixedStack(FI);
3300 // The token was already consumed, so use return here instead of break.
3301 return false;
3302 }
3304 lex();
3305 switch (Token.kind()) {
3308 GlobalValue *GV = nullptr;
3309 if (parseGlobalValue(GV))
3310 return true;
3311 PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
3312 break;
3313 }
3315 PSV = MF.getPSVManager().getExternalSymbolCallEntry(
3316 MF.createExternalSymbolName(Token.stringValue()));
3317 break;
3318 default:
3319 return error(
3320 "expected a global value or an external symbol after 'call-entry'");
3321 }
3322 break;
3323 case MIToken::kw_custom: {
3324 lex();
3325 const auto *TII = MF.getSubtarget().getInstrInfo();
3326 if (const auto *Formatter = TII->getMIRFormatter()) {
3327 if (Formatter->parseCustomPseudoSourceValue(
3328 Token.stringValue(), MF, PFS, PSV,
3329 [this](StringRef::iterator Loc, const Twine &Msg) -> bool {
3330 return error(Loc, Msg);
3331 }))
3332 return true;
3333 } else
3334 return error("unable to parse target custom pseudo source value");
3335 break;
3336 }
3337 default:
3338 llvm_unreachable("The current token should be pseudo source value");
3339 }
3340 lex();
3341 return false;
3342}
3343
3344bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
3345 if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
3346 Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
3347 Token.is(MIToken::FixedStackObject) || Token.is(MIToken::StackObject) ||
3348 Token.is(MIToken::kw_call_entry) || Token.is(MIToken::kw_custom)) {
3349 const PseudoSourceValue *PSV = nullptr;
3350 if (parseMemoryPseudoSourceValue(PSV))
3351 return true;
3352 int64_t Offset = 0;
3353 if (parseOffset(Offset))
3354 return true;
3355 Dest = MachinePointerInfo(PSV, Offset);
3356 return false;
3357 }
3358 if (Token.isNot(MIToken::NamedIRValue) && Token.isNot(MIToken::IRValue) &&
3359 Token.isNot(MIToken::GlobalValue) &&
3360 Token.isNot(MIToken::NamedGlobalValue) &&
3361 Token.isNot(MIToken::QuotedIRValue) &&
3362 Token.isNot(MIToken::kw_unknown_address))
3363 return error("expected an IR value reference");
3364 const Value *V = nullptr;
3365 if (parseIRValue(V))
3366 return true;
3367 if (V && !V->getType()->isPointerTy())
3368 return error("expected a pointer IR value");
3369 lex();
3370 int64_t Offset = 0;
3371 if (parseOffset(Offset))
3372 return true;
3373 Dest = MachinePointerInfo(V, Offset);
3374 return false;
3375}
3376
3377bool MIParser::parseOptionalScope(LLVMContext &Context,
3378 SyncScope::ID &SSID) {
3379 SSID = SyncScope::System;
3380 if (Token.is(MIToken::Identifier) && Token.stringValue() == "syncscope") {
3381 lex();
3382 if (expectAndConsume(MIToken::lparen))
3383 return error("expected '(' in syncscope");
3384
3385 std::string SSN;
3386 if (parseStringConstant(SSN))
3387 return true;
3388
3389 SSID = Context.getOrInsertSyncScopeID(SSN);
3390 if (expectAndConsume(MIToken::rparen))
3391 return error("expected ')' in syncscope");
3392 }
3393
3394 return false;
3395}
3396
3397bool MIParser::parseOptionalAtomicOrdering(AtomicOrdering &Order) {
3399 if (Token.isNot(MIToken::Identifier))
3400 return false;
3401
3402 Order = StringSwitch<AtomicOrdering>(Token.stringValue())
3403 .Case("unordered", AtomicOrdering::Unordered)
3404 .Case("monotonic", AtomicOrdering::Monotonic)
3405 .Case("acquire", AtomicOrdering::Acquire)
3406 .Case("release", AtomicOrdering::Release)
3410
3411 if (Order != AtomicOrdering::NotAtomic) {
3412 lex();
3413 return false;
3414 }
3415
3416 return error("expected an atomic scope, ordering or a size specification");
3417}
3418
3419bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
3420 if (expectAndConsume(MIToken::lparen))
3421 return true;
3423 while (Token.isMemoryOperandFlag()) {
3424 if (parseMemoryOperandFlag(Flags))
3425 return true;
3426 }
3427 if (Token.isNot(MIToken::Identifier) ||
3428 (Token.stringValue() != "load" && Token.stringValue() != "store"))
3429 return error("expected 'load' or 'store' memory operation");
3430 if (Token.stringValue() == "load")
3432 else
3434 lex();
3435
3436 // Optional 'store' for operands that both load and store.
3437 if (Token.is(MIToken::Identifier) && Token.stringValue() == "store") {
3439 lex();
3440 }
3441
3442 // Optional synchronization scope.
3443 SyncScope::ID SSID;
3444 if (parseOptionalScope(MF.getFunction().getContext(), SSID))
3445 return true;
3446
3447 // Up to two atomic orderings (cmpxchg provides guarantees on failure).
3448 AtomicOrdering Order, FailureOrder;
3449 if (parseOptionalAtomicOrdering(Order))
3450 return true;
3451
3452 if (parseOptionalAtomicOrdering(FailureOrder))
3453 return true;
3454
3455 if (Token.isNot(MIToken::IntegerLiteral) &&
3456 Token.isNot(MIToken::kw_unknown_size) &&
3457 Token.isNot(MIToken::lparen))
3458 return error("expected memory LLT, the size integer literal or 'unknown-size' after "
3459 "memory operation");
3460
3462 if (Token.is(MIToken::IntegerLiteral)) {
3463 uint64_t Size;
3464 if (getUint64(Size))
3465 return true;
3466
3467 // Convert from bytes to bits for storage.
3469 lex();
3470 } else if (Token.is(MIToken::kw_unknown_size)) {
3471 lex();
3472 } else {
3473 if (expectAndConsume(MIToken::lparen))
3474 return true;
3475 if (parseLowLevelType(Token.location(), MemoryType))
3476 return true;
3477 if (expectAndConsume(MIToken::rparen))
3478 return true;
3479 }
3480
3482 if (Token.is(MIToken::Identifier)) {
3483 const char *Word =
3486 ? "on"
3487 : Flags & MachineMemOperand::MOLoad ? "from" : "into";
3488 if (Token.stringValue() != Word)
3489 return error(Twine("expected '") + Word + "'");
3490 lex();
3491
3492 if (parseMachinePointerInfo(Ptr))
3493 return true;
3494 }
3495 uint64_t BaseAlignment =
3496 MemoryType.isValid()
3497 ? PowerOf2Ceil(MemoryType.getSizeInBytes().getKnownMinValue())
3498 : 1;
3499 AAMDNodes AAInfo;
3500 MDNode *Range = nullptr;
3501 while (consumeIfPresent(MIToken::comma)) {
3502 switch (Token.kind()) {
3503 case MIToken::kw_align: {
3504 // align is printed if it is different than size.
3505 uint64_t Alignment;
3506 if (parseAlignment(Alignment))
3507 return true;
3508 if (Ptr.Offset & (Alignment - 1)) {
3509 // MachineMemOperand::getAlign never returns a value greater than the
3510 // alignment of offset, so this just guards against hand-written MIR
3511 // that specifies a large "align" value when it should probably use
3512 // "basealign" instead.
3513 return error("specified alignment is more aligned than offset");
3514 }
3515 BaseAlignment = Alignment;
3516 break;
3517 }
3519 // basealign is printed if it is different than align.
3520 if (parseAlignment(BaseAlignment))
3521 return true;
3522 break;
3524 if (parseAddrspace(Ptr.AddrSpace))
3525 return true;
3526 break;
3527 case MIToken::md_tbaa:
3528 lex();
3529 if (parseMDNode(AAInfo.TBAA))
3530 return true;
3531 break;
3533 lex();
3534 if (parseMDNode(AAInfo.Scope))
3535 return true;
3536 break;
3538 lex();
3539 if (parseMDNode(AAInfo.NoAlias))
3540 return true;
3541 break;
3543 lex();
3544 if (parseMDNode(AAInfo.NoAliasAddrSpace))
3545 return true;
3546 break;
3547 case MIToken::md_range:
3548 lex();
3549 if (parseMDNode(Range))
3550 return true;
3551 break;
3552 // TODO: Report an error on duplicate metadata nodes.
3553 default:
3554 return error("expected 'align' or '!tbaa' or '!alias.scope' or "
3555 "'!noalias' or '!range' or '!noalias.addrspace'");
3556 }
3557 }
3558 if (expectAndConsume(MIToken::rparen))
3559 return true;
3560 Dest = MF.getMachineMemOperand(Ptr, Flags, MemoryType, Align(BaseAlignment),
3561 AAInfo, Range, SSID, Order, FailureOrder);
3562 return false;
3563}
3564
3565bool MIParser::parsePreOrPostInstrSymbol(MCSymbol *&Symbol) {
3567 Token.is(MIToken::kw_post_instr_symbol)) &&
3568 "Invalid token for a pre- post-instruction symbol!");
3569 lex();
3570 if (Token.isNot(MIToken::MCSymbol))
3571 return error("expected a symbol after 'pre-instr-symbol'");
3572 Symbol = getOrCreateMCSymbol(Token.stringValue());
3573 lex();
3574 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3575 Token.is(MIToken::lbrace))
3576 return false;
3577 if (Token.isNot(MIToken::comma))
3578 return error("expected ',' before the next machine operand");
3579 lex();
3580 return false;
3581}
3582
3583bool MIParser::parseHeapAllocMarker(MDNode *&Node) {
3585 "Invalid token for a heap alloc marker!");
3586 lex();
3587 if (parseMDNode(Node))
3588 return true;
3589 if (!Node)
3590 return error("expected a MDNode after 'heap-alloc-marker'");
3591 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3592 Token.is(MIToken::lbrace))
3593 return false;
3594 if (Token.isNot(MIToken::comma))
3595 return error("expected ',' before the next machine operand");
3596 lex();
3597 return false;
3598}
3599
3600bool MIParser::parsePCSections(MDNode *&Node) {
3601 assert(Token.is(MIToken::kw_pcsections) &&
3602 "Invalid token for a PC sections!");
3603 lex();
3604 if (parseMDNode(Node))
3605 return true;
3606 if (!Node)
3607 return error("expected a MDNode after 'pcsections'");
3608 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
3609 Token.is(MIToken::lbrace))
3610 return false;
3611 if (Token.isNot(MIToken::comma))
3612 return error("expected ',' before the next machine operand");
3613 lex();
3614 return false;
3615}
3616
3618 const Function &F,
3619 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3620 ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
3622 for (const auto &BB : F) {
3623 if (BB.hasName())
3624 continue;
3625 int Slot = MST.getLocalSlot(&BB);
3626 if (Slot == -1)
3627 continue;
3628 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
3629 }
3630}
3631
3633 unsigned Slot,
3634 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
3635 return Slots2BasicBlocks.lookup(Slot);
3636}
3637
3638const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
3639 if (Slots2BasicBlocks.empty())
3640 initSlots2BasicBlocks(MF.getFunction(), Slots2BasicBlocks);
3641 return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
3642}
3643
3644const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
3645 if (&F == &MF.getFunction())
3646 return getIRBlock(Slot);
3647 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
3648 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
3649 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
3650}
3651
3652MCSymbol *MIParser::getOrCreateMCSymbol(StringRef Name) {
3653 // FIXME: Currently we can't recognize temporary or local symbols and call all
3654 // of the appropriate forms to create them. However, this handles basic cases
3655 // well as most of the special aspects are recognized by a prefix on their
3656 // name, and the input names should already be unique. For test cases, keeping
3657 // the symbol name out of the symbol table isn't terribly important.
3658 return MF.getContext().getOrCreateSymbol(Name);
3659}
3660
3661bool MIParser::parseStringConstant(std::string &Result) {
3662 if (Token.isNot(MIToken::StringConstant))
3663 return error("expected string constant");
3664 Result = std::string(Token.stringValue());
3665 lex();
3666 return false;
3667}
3668
3670 StringRef Src,
3672 return MIParser(PFS, Error, Src).parseBasicBlockDefinitions(PFS.MBBSlots);
3673}
3674
3677 return MIParser(PFS, Error, Src).parseBasicBlocks();
3678}
3679
3683 return MIParser(PFS, Error, Src).parseStandaloneMBB(MBB);
3684}
3685
3687 Register &Reg, StringRef Src,
3689 return MIParser(PFS, Error, Src).parseStandaloneRegister(Reg);
3690}
3691
3693 Register &Reg, StringRef Src,
3695 return MIParser(PFS, Error, Src).parseStandaloneNamedRegister(Reg);
3696}
3697
3699 VRegInfo *&Info, StringRef Src,
3701 return MIParser(PFS, Error, Src).parseStandaloneVirtualRegister(Info);
3702}
3703
3705 int &FI, StringRef Src,
3707 return MIParser(PFS, Error, Src).parseStandaloneStackObject(FI);
3708}
3709
3712 return MIParser(PFS, Error, Src).parseStandaloneMDNode(Node);
3713}
3714
3716 SMRange SrcRange, SMDiagnostic &Error) {
3717 return MIParser(PFS, Error, Src, SrcRange).parseMachineMetadata();
3718}
3719
3721 PerFunctionMIParsingState &PFS, const Value *&V,
3722 ErrorCallbackType ErrorCallback) {
3723 MIToken Token;
3724 Src = lexMIToken(Src, Token, [&](StringRef::iterator Loc, const Twine &Msg) {
3725 ErrorCallback(Loc, Msg);
3726 });
3727 V = nullptr;
3728
3729 return ::parseIRValue(Token, PFS, V, ErrorCallback);
3730}
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:1549
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:614
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
constexpr bool hasRegState(unsigned Value, unsigned Test)
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
constexpr unsigned getDefRegState(bool B)
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