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