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