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