1 //===- MIParser.cpp - Machine instructions parser implementation ----------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the parsing of machine instructions.
11 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/APSInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/MemoryLocation.h"
27 #include "llvm/AsmParser/Parser.h"
28 #include "llvm/AsmParser/SlotMapping.h"
29 #include "llvm/CodeGen/MIRPrinter.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineMemOperand.h"
36 #include "llvm/CodeGen/MachineOperand.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/TargetInstrInfo.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSubtargetInfo.h"
41 #include "llvm/IR/BasicBlock.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/DebugInfoMetadata.h"
45 #include "llvm/IR/DebugLoc.h"
46 #include "llvm/IR/Function.h"
47 #include "llvm/IR/InstrTypes.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/ModuleSlotTracker.h"
53 #include "llvm/IR/Type.h"
54 #include "llvm/IR/Value.h"
55 #include "llvm/IR/ValueSymbolTable.h"
56 #include "llvm/MC/LaneBitmask.h"
57 #include "llvm/MC/MCContext.h"
58 #include "llvm/MC/MCDwarf.h"
59 #include "llvm/MC/MCInstrDesc.h"
60 #include "llvm/MC/MCRegisterInfo.h"
61 #include "llvm/Support/AtomicOrdering.h"
62 #include "llvm/Support/BranchProbability.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/LowLevelTypeImpl.h"
66 #include "llvm/Support/MemoryBuffer.h"
67 #include "llvm/Support/SMLoc.h"
68 #include "llvm/Support/SourceMgr.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/Target/TargetIntrinsicInfo.h"
71 #include "llvm/Target/TargetMachine.h"
83 PerFunctionMIParsingState::PerFunctionMIParsingState(MachineFunction
&MF
,
84 SourceMgr
&SM
, const SlotMapping
&IRSlots
,
85 const Name2RegClassMap
&Names2RegClasses
,
86 const Name2RegBankMap
&Names2RegBanks
)
87 : MF(MF
), SM(&SM
), IRSlots(IRSlots
), Names2RegClasses(Names2RegClasses
),
88 Names2RegBanks(Names2RegBanks
) {
91 VRegInfo
&PerFunctionMIParsingState::getVRegInfo(unsigned Num
) {
92 auto I
= VRegInfos
.insert(std::make_pair(Num
, nullptr));
94 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
95 VRegInfo
*Info
= new (Allocator
) VRegInfo
;
96 Info
->VReg
= MRI
.createIncompleteVirtualRegister();
97 I
.first
->second
= Info
;
99 return *I
.first
->second
;
102 VRegInfo
&PerFunctionMIParsingState::getVRegInfoNamed(StringRef RegName
) {
103 assert(RegName
!= "" && "Expected named reg.");
105 auto I
= VRegInfosNamed
.insert(std::make_pair(RegName
.str(), nullptr));
107 VRegInfo
*Info
= new (Allocator
) VRegInfo
;
108 Info
->VReg
= MF
.getRegInfo().createIncompleteVirtualRegister(RegName
);
109 I
.first
->second
= Info
;
111 return *I
.first
->second
;
116 /// A wrapper struct around the 'MachineOperand' struct that includes a source
117 /// range and other attributes.
118 struct ParsedMachineOperand
{
119 MachineOperand Operand
;
120 StringRef::iterator Begin
;
121 StringRef::iterator End
;
122 Optional
<unsigned> TiedDefIdx
;
124 ParsedMachineOperand(const MachineOperand
&Operand
, StringRef::iterator Begin
,
125 StringRef::iterator End
, Optional
<unsigned> &TiedDefIdx
)
126 : Operand(Operand
), Begin(Begin
), End(End
), TiedDefIdx(TiedDefIdx
) {
128 assert(Operand
.isReg() && Operand
.isUse() &&
129 "Only used register operands can be tied");
136 StringRef Source
, CurrentSource
;
138 PerFunctionMIParsingState
&PFS
;
139 /// Maps from instruction names to op codes.
140 StringMap
<unsigned> Names2InstrOpCodes
;
141 /// Maps from register names to registers.
142 StringMap
<unsigned> Names2Regs
;
143 /// Maps from register mask names to register masks.
144 StringMap
<const uint32_t *> Names2RegMasks
;
145 /// Maps from subregister names to subregister indices.
146 StringMap
<unsigned> Names2SubRegIndices
;
147 /// Maps from slot numbers to function's unnamed basic blocks.
148 DenseMap
<unsigned, const BasicBlock
*> Slots2BasicBlocks
;
149 /// Maps from slot numbers to function's unnamed values.
150 DenseMap
<unsigned, const Value
*> Slots2Values
;
151 /// Maps from target index names to target indices.
152 StringMap
<int> Names2TargetIndices
;
153 /// Maps from direct target flag names to the direct target flag values.
154 StringMap
<unsigned> Names2DirectTargetFlags
;
155 /// Maps from direct target flag names to the bitmask target flag values.
156 StringMap
<unsigned> Names2BitmaskTargetFlags
;
157 /// Maps from MMO target flag names to MMO target flag values.
158 StringMap
<MachineMemOperand::Flags
> Names2MMOTargetFlags
;
161 MIParser(PerFunctionMIParsingState
&PFS
, SMDiagnostic
&Error
,
164 /// \p SkipChar gives the number of characters to skip before looking
165 /// for the next token.
166 void lex(unsigned SkipChar
= 0);
168 /// Report an error at the current location with the given message.
170 /// This function always return true.
171 bool error(const Twine
&Msg
);
173 /// Report an error at the given location with the given message.
175 /// This function always return true.
176 bool error(StringRef::iterator Loc
, const Twine
&Msg
);
179 parseBasicBlockDefinitions(DenseMap
<unsigned, MachineBasicBlock
*> &MBBSlots
);
180 bool parseBasicBlocks();
181 bool parse(MachineInstr
*&MI
);
182 bool parseStandaloneMBB(MachineBasicBlock
*&MBB
);
183 bool parseStandaloneNamedRegister(unsigned &Reg
);
184 bool parseStandaloneVirtualRegister(VRegInfo
*&Info
);
185 bool parseStandaloneRegister(unsigned &Reg
);
186 bool parseStandaloneStackObject(int &FI
);
187 bool parseStandaloneMDNode(MDNode
*&Node
);
190 parseBasicBlockDefinition(DenseMap
<unsigned, MachineBasicBlock
*> &MBBSlots
);
191 bool parseBasicBlock(MachineBasicBlock
&MBB
,
192 MachineBasicBlock
*&AddFalthroughFrom
);
193 bool parseBasicBlockLiveins(MachineBasicBlock
&MBB
);
194 bool parseBasicBlockSuccessors(MachineBasicBlock
&MBB
);
196 bool parseNamedRegister(unsigned &Reg
);
197 bool parseVirtualRegister(VRegInfo
*&Info
);
198 bool parseNamedVirtualRegister(VRegInfo
*&Info
);
199 bool parseRegister(unsigned &Reg
, VRegInfo
*&VRegInfo
);
200 bool parseRegisterFlag(unsigned &Flags
);
201 bool parseRegisterClassOrBank(VRegInfo
&RegInfo
);
202 bool parseSubRegisterIndex(unsigned &SubReg
);
203 bool parseRegisterTiedDefIndex(unsigned &TiedDefIdx
);
204 bool parseRegisterOperand(MachineOperand
&Dest
,
205 Optional
<unsigned> &TiedDefIdx
, bool IsDef
= false);
206 bool parseImmediateOperand(MachineOperand
&Dest
);
207 bool parseIRConstant(StringRef::iterator Loc
, StringRef StringValue
,
209 bool parseIRConstant(StringRef::iterator Loc
, const Constant
*&C
);
210 bool parseLowLevelType(StringRef::iterator Loc
, LLT
&Ty
);
211 bool parseTypedImmediateOperand(MachineOperand
&Dest
);
212 bool parseFPImmediateOperand(MachineOperand
&Dest
);
213 bool parseMBBReference(MachineBasicBlock
*&MBB
);
214 bool parseMBBOperand(MachineOperand
&Dest
);
215 bool parseStackFrameIndex(int &FI
);
216 bool parseStackObjectOperand(MachineOperand
&Dest
);
217 bool parseFixedStackFrameIndex(int &FI
);
218 bool parseFixedStackObjectOperand(MachineOperand
&Dest
);
219 bool parseGlobalValue(GlobalValue
*&GV
);
220 bool parseGlobalAddressOperand(MachineOperand
&Dest
);
221 bool parseConstantPoolIndexOperand(MachineOperand
&Dest
);
222 bool parseSubRegisterIndexOperand(MachineOperand
&Dest
);
223 bool parseJumpTableIndexOperand(MachineOperand
&Dest
);
224 bool parseExternalSymbolOperand(MachineOperand
&Dest
);
225 bool parseMCSymbolOperand(MachineOperand
&Dest
);
226 bool parseMDNode(MDNode
*&Node
);
227 bool parseDIExpression(MDNode
*&Expr
);
228 bool parseDILocation(MDNode
*&Expr
);
229 bool parseMetadataOperand(MachineOperand
&Dest
);
230 bool parseCFIOffset(int &Offset
);
231 bool parseCFIRegister(unsigned &Reg
);
232 bool parseCFIEscapeValues(std::string
& Values
);
233 bool parseCFIOperand(MachineOperand
&Dest
);
234 bool parseIRBlock(BasicBlock
*&BB
, const Function
&F
);
235 bool parseBlockAddressOperand(MachineOperand
&Dest
);
236 bool parseIntrinsicOperand(MachineOperand
&Dest
);
237 bool parsePredicateOperand(MachineOperand
&Dest
);
238 bool parseTargetIndexOperand(MachineOperand
&Dest
);
239 bool parseCustomRegisterMaskOperand(MachineOperand
&Dest
);
240 bool parseLiveoutRegisterMaskOperand(MachineOperand
&Dest
);
241 bool parseMachineOperand(MachineOperand
&Dest
,
242 Optional
<unsigned> &TiedDefIdx
);
243 bool parseMachineOperandAndTargetFlags(MachineOperand
&Dest
,
244 Optional
<unsigned> &TiedDefIdx
);
245 bool parseOffset(int64_t &Offset
);
246 bool parseAlignment(unsigned &Alignment
);
247 bool parseAddrspace(unsigned &Addrspace
);
248 bool parseOperandsOffset(MachineOperand
&Op
);
249 bool parseIRValue(const Value
*&V
);
250 bool parseMemoryOperandFlag(MachineMemOperand::Flags
&Flags
);
251 bool parseMemoryPseudoSourceValue(const PseudoSourceValue
*&PSV
);
252 bool parseMachinePointerInfo(MachinePointerInfo
&Dest
);
253 bool parseOptionalScope(LLVMContext
&Context
, SyncScope::ID
&SSID
);
254 bool parseOptionalAtomicOrdering(AtomicOrdering
&Order
);
255 bool parseMachineMemoryOperand(MachineMemOperand
*&Dest
);
256 bool parsePreOrPostInstrSymbol(MCSymbol
*&Symbol
);
259 /// Convert the integer literal in the current token into an unsigned integer.
261 /// Return true if an error occurred.
262 bool getUnsigned(unsigned &Result
);
264 /// Convert the integer literal in the current token into an uint64.
266 /// Return true if an error occurred.
267 bool getUint64(uint64_t &Result
);
269 /// Convert the hexadecimal literal in the current token into an unsigned
270 /// APInt with a minimum bitwidth required to represent the value.
272 /// Return true if the literal does not represent an integer value.
273 bool getHexUint(APInt
&Result
);
275 /// If the current token is of the given kind, consume it and return false.
276 /// Otherwise report an error and return true.
277 bool expectAndConsume(MIToken::TokenKind TokenKind
);
279 /// If the current token is of the given kind, consume it and return true.
280 /// Otherwise return false.
281 bool consumeIfPresent(MIToken::TokenKind TokenKind
);
283 void initNames2InstrOpCodes();
285 /// Try to convert an instruction name to an opcode. Return true if the
286 /// instruction name is invalid.
287 bool parseInstrName(StringRef InstrName
, unsigned &OpCode
);
289 bool parseInstruction(unsigned &OpCode
, unsigned &Flags
);
291 bool assignRegisterTies(MachineInstr
&MI
,
292 ArrayRef
<ParsedMachineOperand
> Operands
);
294 bool verifyImplicitOperands(ArrayRef
<ParsedMachineOperand
> Operands
,
295 const MCInstrDesc
&MCID
);
297 void initNames2Regs();
299 /// Try to convert a register name to a register number. Return true if the
300 /// register name is invalid.
301 bool getRegisterByName(StringRef RegName
, unsigned &Reg
);
303 void initNames2RegMasks();
305 /// Check if the given identifier is a name of a register mask.
307 /// Return null if the identifier isn't a register mask.
308 const uint32_t *getRegMask(StringRef Identifier
);
310 void initNames2SubRegIndices();
312 /// Check if the given identifier is a name of a subregister index.
314 /// Return 0 if the name isn't a subregister index class.
315 unsigned getSubRegIndex(StringRef Name
);
317 const BasicBlock
*getIRBlock(unsigned Slot
);
318 const BasicBlock
*getIRBlock(unsigned Slot
, const Function
&F
);
320 const Value
*getIRValue(unsigned Slot
);
322 void initNames2TargetIndices();
324 /// Try to convert a name of target index to the corresponding target index.
326 /// Return true if the name isn't a name of a target index.
327 bool getTargetIndex(StringRef Name
, int &Index
);
329 void initNames2DirectTargetFlags();
331 /// Try to convert a name of a direct target flag to the corresponding
334 /// Return true if the name isn't a name of a direct flag.
335 bool getDirectTargetFlag(StringRef Name
, unsigned &Flag
);
337 void initNames2BitmaskTargetFlags();
339 /// Try to convert a name of a bitmask target flag to the corresponding
342 /// Return true if the name isn't a name of a bitmask target flag.
343 bool getBitmaskTargetFlag(StringRef Name
, unsigned &Flag
);
345 void initNames2MMOTargetFlags();
347 /// Try to convert a name of a MachineMemOperand target flag to the
348 /// corresponding target flag.
350 /// Return true if the name isn't a name of a target MMO flag.
351 bool getMMOTargetFlag(StringRef Name
, MachineMemOperand::Flags
&Flag
);
353 /// Get or create an MCSymbol for a given name.
354 MCSymbol
*getOrCreateMCSymbol(StringRef Name
);
356 /// parseStringConstant
357 /// ::= StringConstant
358 bool parseStringConstant(std::string
&Result
);
361 } // end anonymous namespace
363 MIParser::MIParser(PerFunctionMIParsingState
&PFS
, SMDiagnostic
&Error
,
365 : MF(PFS
.MF
), Error(Error
), Source(Source
), CurrentSource(Source
), PFS(PFS
)
368 void MIParser::lex(unsigned SkipChar
) {
369 CurrentSource
= lexMIToken(
370 CurrentSource
.data() + SkipChar
, Token
,
371 [this](StringRef::iterator Loc
, const Twine
&Msg
) { error(Loc
, Msg
); });
374 bool MIParser::error(const Twine
&Msg
) { return error(Token
.location(), Msg
); }
376 bool MIParser::error(StringRef::iterator Loc
, const Twine
&Msg
) {
377 const SourceMgr
&SM
= *PFS
.SM
;
378 assert(Loc
>= Source
.data() && Loc
<= (Source
.data() + Source
.size()));
379 const MemoryBuffer
&Buffer
= *SM
.getMemoryBuffer(SM
.getMainFileID());
380 if (Loc
>= Buffer
.getBufferStart() && Loc
<= Buffer
.getBufferEnd()) {
381 // Create an ordinary diagnostic when the source manager's buffer is the
383 Error
= SM
.GetMessage(SMLoc::getFromPointer(Loc
), SourceMgr::DK_Error
, Msg
);
386 // Create a diagnostic for a YAML string literal.
387 Error
= SMDiagnostic(SM
, SMLoc(), Buffer
.getBufferIdentifier(), 1,
388 Loc
- Source
.data(), SourceMgr::DK_Error
, Msg
.str(),
393 static const char *toString(MIToken::TokenKind TokenKind
) {
401 case MIToken::lparen
:
403 case MIToken::rparen
:
406 return "<unknown token>";
410 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind
) {
411 if (Token
.isNot(TokenKind
))
412 return error(Twine("expected ") + toString(TokenKind
));
417 bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind
) {
418 if (Token
.isNot(TokenKind
))
424 bool MIParser::parseBasicBlockDefinition(
425 DenseMap
<unsigned, MachineBasicBlock
*> &MBBSlots
) {
426 assert(Token
.is(MIToken::MachineBasicBlockLabel
));
430 auto Loc
= Token
.location();
431 auto Name
= Token
.stringValue();
433 bool HasAddressTaken
= false;
434 bool IsLandingPad
= false;
435 unsigned Alignment
= 0;
436 BasicBlock
*BB
= nullptr;
437 if (consumeIfPresent(MIToken::lparen
)) {
439 // TODO: Report an error when multiple same attributes are specified.
440 switch (Token
.kind()) {
441 case MIToken::kw_address_taken
:
442 HasAddressTaken
= true;
445 case MIToken::kw_landing_pad
:
449 case MIToken::kw_align
:
450 if (parseAlignment(Alignment
))
453 case MIToken::IRBlock
:
454 // TODO: Report an error when both name and ir block are specified.
455 if (parseIRBlock(BB
, MF
.getFunction()))
462 } while (consumeIfPresent(MIToken::comma
));
463 if (expectAndConsume(MIToken::rparen
))
466 if (expectAndConsume(MIToken::colon
))
470 BB
= dyn_cast_or_null
<BasicBlock
>(
471 MF
.getFunction().getValueSymbolTable()->lookup(Name
));
473 return error(Loc
, Twine("basic block '") + Name
+
474 "' is not defined in the function '" +
477 auto *MBB
= MF
.CreateMachineBasicBlock(BB
);
478 MF
.insert(MF
.end(), MBB
);
479 bool WasInserted
= MBBSlots
.insert(std::make_pair(ID
, MBB
)).second
;
481 return error(Loc
, Twine("redefinition of machine basic block with id #") +
484 MBB
->setAlignment(Alignment
);
486 MBB
->setHasAddressTaken();
487 MBB
->setIsEHPad(IsLandingPad
);
491 bool MIParser::parseBasicBlockDefinitions(
492 DenseMap
<unsigned, MachineBasicBlock
*> &MBBSlots
) {
494 // Skip until the first machine basic block.
495 while (Token
.is(MIToken::Newline
))
497 if (Token
.isErrorOrEOF())
498 return Token
.isError();
499 if (Token
.isNot(MIToken::MachineBasicBlockLabel
))
500 return error("expected a basic block definition before instructions");
501 unsigned BraceDepth
= 0;
503 if (parseBasicBlockDefinition(MBBSlots
))
505 bool IsAfterNewline
= false;
506 // Skip until the next machine basic block.
508 if ((Token
.is(MIToken::MachineBasicBlockLabel
) && IsAfterNewline
) ||
509 Token
.isErrorOrEOF())
511 else if (Token
.is(MIToken::MachineBasicBlockLabel
))
512 return error("basic block definition should be located at the start of "
514 else if (consumeIfPresent(MIToken::Newline
)) {
515 IsAfterNewline
= true;
518 IsAfterNewline
= false;
519 if (Token
.is(MIToken::lbrace
))
521 if (Token
.is(MIToken::rbrace
)) {
523 return error("extraneous closing brace ('}')");
528 // Verify that we closed all of the '{' at the end of a file or a block.
529 if (!Token
.isError() && BraceDepth
)
530 return error("expected '}'"); // FIXME: Report a note that shows '{'.
531 } while (!Token
.isErrorOrEOF());
532 return Token
.isError();
535 bool MIParser::parseBasicBlockLiveins(MachineBasicBlock
&MBB
) {
536 assert(Token
.is(MIToken::kw_liveins
));
538 if (expectAndConsume(MIToken::colon
))
540 if (Token
.isNewlineOrEOF()) // Allow an empty list of liveins.
543 if (Token
.isNot(MIToken::NamedRegister
))
544 return error("expected a named register");
546 if (parseNamedRegister(Reg
))
549 LaneBitmask Mask
= LaneBitmask::getAll();
550 if (consumeIfPresent(MIToken::colon
)) {
552 if (Token
.isNot(MIToken::IntegerLiteral
) &&
553 Token
.isNot(MIToken::HexLiteral
))
554 return error("expected a lane mask");
555 static_assert(sizeof(LaneBitmask::Type
) == sizeof(unsigned),
556 "Use correct get-function for lane mask");
559 return error("invalid lane mask value");
560 Mask
= LaneBitmask(V
);
563 MBB
.addLiveIn(Reg
, Mask
);
564 } while (consumeIfPresent(MIToken::comma
));
568 bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock
&MBB
) {
569 assert(Token
.is(MIToken::kw_successors
));
571 if (expectAndConsume(MIToken::colon
))
573 if (Token
.isNewlineOrEOF()) // Allow an empty list of successors.
576 if (Token
.isNot(MIToken::MachineBasicBlock
))
577 return error("expected a machine basic block reference");
578 MachineBasicBlock
*SuccMBB
= nullptr;
579 if (parseMBBReference(SuccMBB
))
583 if (consumeIfPresent(MIToken::lparen
)) {
584 if (Token
.isNot(MIToken::IntegerLiteral
) &&
585 Token
.isNot(MIToken::HexLiteral
))
586 return error("expected an integer literal after '('");
587 if (getUnsigned(Weight
))
590 if (expectAndConsume(MIToken::rparen
))
593 MBB
.addSuccessor(SuccMBB
, BranchProbability::getRaw(Weight
));
594 } while (consumeIfPresent(MIToken::comma
));
595 MBB
.normalizeSuccProbs();
599 bool MIParser::parseBasicBlock(MachineBasicBlock
&MBB
,
600 MachineBasicBlock
*&AddFalthroughFrom
) {
601 // Skip the definition.
602 assert(Token
.is(MIToken::MachineBasicBlockLabel
));
604 if (consumeIfPresent(MIToken::lparen
)) {
605 while (Token
.isNot(MIToken::rparen
) && !Token
.isErrorOrEOF())
607 consumeIfPresent(MIToken::rparen
);
609 consumeIfPresent(MIToken::colon
);
611 // Parse the liveins and successors.
612 // N.B: Multiple lists of successors and liveins are allowed and they're
619 // liveins: %edi, %esi
620 bool ExplicitSuccessors
= false;
622 if (Token
.is(MIToken::kw_successors
)) {
623 if (parseBasicBlockSuccessors(MBB
))
625 ExplicitSuccessors
= true;
626 } else if (Token
.is(MIToken::kw_liveins
)) {
627 if (parseBasicBlockLiveins(MBB
))
629 } else if (consumeIfPresent(MIToken::Newline
)) {
633 if (!Token
.isNewlineOrEOF())
634 return error("expected line break at the end of a list");
638 // Parse the instructions.
639 bool IsInBundle
= false;
640 MachineInstr
*PrevMI
= nullptr;
641 while (!Token
.is(MIToken::MachineBasicBlockLabel
) &&
642 !Token
.is(MIToken::Eof
)) {
643 if (consumeIfPresent(MIToken::Newline
))
645 if (consumeIfPresent(MIToken::rbrace
)) {
646 // The first parsing pass should verify that all closing '}' have an
652 MachineInstr
*MI
= nullptr;
655 MBB
.insert(MBB
.end(), MI
);
657 PrevMI
->setFlag(MachineInstr::BundledSucc
);
658 MI
->setFlag(MachineInstr::BundledPred
);
661 if (Token
.is(MIToken::lbrace
)) {
663 return error("nested instruction bundles are not allowed");
665 // This instruction is the start of the bundle.
666 MI
->setFlag(MachineInstr::BundledSucc
);
668 if (!Token
.is(MIToken::Newline
))
669 // The next instruction can be on the same line.
672 assert(Token
.isNewlineOrEOF() && "MI is not fully parsed");
676 // Construct successor list by searching for basic block machine operands.
677 if (!ExplicitSuccessors
) {
678 SmallVector
<MachineBasicBlock
*,4> Successors
;
680 guessSuccessors(MBB
, Successors
, IsFallthrough
);
681 for (MachineBasicBlock
*Succ
: Successors
)
682 MBB
.addSuccessor(Succ
);
685 AddFalthroughFrom
= &MBB
;
687 MBB
.normalizeSuccProbs();
694 bool MIParser::parseBasicBlocks() {
696 // Skip until the first machine basic block.
697 while (Token
.is(MIToken::Newline
))
699 if (Token
.isErrorOrEOF())
700 return Token
.isError();
701 // The first parsing pass should have verified that this token is a MBB label
702 // in the 'parseBasicBlockDefinitions' method.
703 assert(Token
.is(MIToken::MachineBasicBlockLabel
));
704 MachineBasicBlock
*AddFalthroughFrom
= nullptr;
706 MachineBasicBlock
*MBB
= nullptr;
707 if (parseMBBReference(MBB
))
709 if (AddFalthroughFrom
) {
710 if (!AddFalthroughFrom
->isSuccessor(MBB
))
711 AddFalthroughFrom
->addSuccessor(MBB
);
712 AddFalthroughFrom
->normalizeSuccProbs();
713 AddFalthroughFrom
= nullptr;
715 if (parseBasicBlock(*MBB
, AddFalthroughFrom
))
717 // The method 'parseBasicBlock' should parse the whole block until the next
718 // block or the end of file.
719 assert(Token
.is(MIToken::MachineBasicBlockLabel
) || Token
.is(MIToken::Eof
));
720 } while (Token
.isNot(MIToken::Eof
));
724 bool MIParser::parse(MachineInstr
*&MI
) {
725 // Parse any register operands before '='
726 MachineOperand MO
= MachineOperand::CreateImm(0);
727 SmallVector
<ParsedMachineOperand
, 8> Operands
;
728 while (Token
.isRegister() || Token
.isRegisterFlag()) {
729 auto Loc
= Token
.location();
730 Optional
<unsigned> TiedDefIdx
;
731 if (parseRegisterOperand(MO
, TiedDefIdx
, /*IsDef=*/true))
734 ParsedMachineOperand(MO
, Loc
, Token
.location(), TiedDefIdx
));
735 if (Token
.isNot(MIToken::comma
))
739 if (!Operands
.empty() && expectAndConsume(MIToken::equal
))
742 unsigned OpCode
, Flags
= 0;
743 if (Token
.isError() || parseInstruction(OpCode
, Flags
))
746 // Parse the remaining machine operands.
747 while (!Token
.isNewlineOrEOF() && Token
.isNot(MIToken::kw_pre_instr_symbol
) &&
748 Token
.isNot(MIToken::kw_post_instr_symbol
) &&
749 Token
.isNot(MIToken::kw_debug_location
) &&
750 Token
.isNot(MIToken::coloncolon
) && Token
.isNot(MIToken::lbrace
)) {
751 auto Loc
= Token
.location();
752 Optional
<unsigned> TiedDefIdx
;
753 if (parseMachineOperandAndTargetFlags(MO
, TiedDefIdx
))
755 if (OpCode
== TargetOpcode::DBG_VALUE
&& MO
.isReg())
758 ParsedMachineOperand(MO
, Loc
, Token
.location(), TiedDefIdx
));
759 if (Token
.isNewlineOrEOF() || Token
.is(MIToken::coloncolon
) ||
760 Token
.is(MIToken::lbrace
))
762 if (Token
.isNot(MIToken::comma
))
763 return error("expected ',' before the next machine operand");
767 MCSymbol
*PreInstrSymbol
= nullptr;
768 if (Token
.is(MIToken::kw_pre_instr_symbol
))
769 if (parsePreOrPostInstrSymbol(PreInstrSymbol
))
771 MCSymbol
*PostInstrSymbol
= nullptr;
772 if (Token
.is(MIToken::kw_post_instr_symbol
))
773 if (parsePreOrPostInstrSymbol(PostInstrSymbol
))
776 DebugLoc DebugLocation
;
777 if (Token
.is(MIToken::kw_debug_location
)) {
779 MDNode
*Node
= nullptr;
780 if (Token
.is(MIToken::exclaim
)) {
781 if (parseMDNode(Node
))
783 } else if (Token
.is(MIToken::md_dilocation
)) {
784 if (parseDILocation(Node
))
787 return error("expected a metadata node after 'debug-location'");
788 if (!isa
<DILocation
>(Node
))
789 return error("referenced metadata is not a DILocation");
790 DebugLocation
= DebugLoc(Node
);
793 // Parse the machine memory operands.
794 SmallVector
<MachineMemOperand
*, 2> MemOperands
;
795 if (Token
.is(MIToken::coloncolon
)) {
797 while (!Token
.isNewlineOrEOF()) {
798 MachineMemOperand
*MemOp
= nullptr;
799 if (parseMachineMemoryOperand(MemOp
))
801 MemOperands
.push_back(MemOp
);
802 if (Token
.isNewlineOrEOF())
804 if (Token
.isNot(MIToken::comma
))
805 return error("expected ',' before the next machine memory operand");
810 const auto &MCID
= MF
.getSubtarget().getInstrInfo()->get(OpCode
);
811 if (!MCID
.isVariadic()) {
812 // FIXME: Move the implicit operand verification to the machine verifier.
813 if (verifyImplicitOperands(Operands
, MCID
))
817 // TODO: Check for extraneous machine operands.
818 MI
= MF
.CreateMachineInstr(MCID
, DebugLocation
, /*NoImplicit=*/true);
820 for (const auto &Operand
: Operands
)
821 MI
->addOperand(MF
, Operand
.Operand
);
822 if (assignRegisterTies(*MI
, Operands
))
825 MI
->setPreInstrSymbol(MF
, PreInstrSymbol
);
827 MI
->setPostInstrSymbol(MF
, PostInstrSymbol
);
828 if (!MemOperands
.empty())
829 MI
->setMemRefs(MF
, MemOperands
);
833 bool MIParser::parseStandaloneMBB(MachineBasicBlock
*&MBB
) {
835 if (Token
.isNot(MIToken::MachineBasicBlock
))
836 return error("expected a machine basic block reference");
837 if (parseMBBReference(MBB
))
840 if (Token
.isNot(MIToken::Eof
))
842 "expected end of string after the machine basic block reference");
846 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg
) {
848 if (Token
.isNot(MIToken::NamedRegister
))
849 return error("expected a named register");
850 if (parseNamedRegister(Reg
))
853 if (Token
.isNot(MIToken::Eof
))
854 return error("expected end of string after the register reference");
858 bool MIParser::parseStandaloneVirtualRegister(VRegInfo
*&Info
) {
860 if (Token
.isNot(MIToken::VirtualRegister
))
861 return error("expected a virtual register");
862 if (parseVirtualRegister(Info
))
865 if (Token
.isNot(MIToken::Eof
))
866 return error("expected end of string after the register reference");
870 bool MIParser::parseStandaloneRegister(unsigned &Reg
) {
872 if (Token
.isNot(MIToken::NamedRegister
) &&
873 Token
.isNot(MIToken::VirtualRegister
))
874 return error("expected either a named or virtual register");
877 if (parseRegister(Reg
, Info
))
881 if (Token
.isNot(MIToken::Eof
))
882 return error("expected end of string after the register reference");
886 bool MIParser::parseStandaloneStackObject(int &FI
) {
888 if (Token
.isNot(MIToken::StackObject
))
889 return error("expected a stack object");
890 if (parseStackFrameIndex(FI
))
892 if (Token
.isNot(MIToken::Eof
))
893 return error("expected end of string after the stack object reference");
897 bool MIParser::parseStandaloneMDNode(MDNode
*&Node
) {
899 if (Token
.is(MIToken::exclaim
)) {
900 if (parseMDNode(Node
))
902 } else if (Token
.is(MIToken::md_diexpr
)) {
903 if (parseDIExpression(Node
))
905 } else if (Token
.is(MIToken::md_dilocation
)) {
906 if (parseDILocation(Node
))
909 return error("expected a metadata node");
910 if (Token
.isNot(MIToken::Eof
))
911 return error("expected end of string after the metadata node");
915 static const char *printImplicitRegisterFlag(const MachineOperand
&MO
) {
916 assert(MO
.isImplicit());
917 return MO
.isDef() ? "implicit-def" : "implicit";
920 static std::string
getRegisterName(const TargetRegisterInfo
*TRI
,
922 assert(TargetRegisterInfo::isPhysicalRegister(Reg
) && "expected phys reg");
923 return StringRef(TRI
->getName(Reg
)).lower();
926 /// Return true if the parsed machine operands contain a given machine operand.
927 static bool isImplicitOperandIn(const MachineOperand
&ImplicitOperand
,
928 ArrayRef
<ParsedMachineOperand
> Operands
) {
929 for (const auto &I
: Operands
) {
930 if (ImplicitOperand
.isIdenticalTo(I
.Operand
))
936 bool MIParser::verifyImplicitOperands(ArrayRef
<ParsedMachineOperand
> Operands
,
937 const MCInstrDesc
&MCID
) {
939 // We can't verify call instructions as they can contain arbitrary implicit
940 // register and register mask operands.
943 // Gather all the expected implicit operands.
944 SmallVector
<MachineOperand
, 4> ImplicitOperands
;
945 if (MCID
.ImplicitDefs
)
946 for (const MCPhysReg
*ImpDefs
= MCID
.getImplicitDefs(); *ImpDefs
; ++ImpDefs
)
947 ImplicitOperands
.push_back(
948 MachineOperand::CreateReg(*ImpDefs
, true, true));
949 if (MCID
.ImplicitUses
)
950 for (const MCPhysReg
*ImpUses
= MCID
.getImplicitUses(); *ImpUses
; ++ImpUses
)
951 ImplicitOperands
.push_back(
952 MachineOperand::CreateReg(*ImpUses
, false, true));
954 const auto *TRI
= MF
.getSubtarget().getRegisterInfo();
955 assert(TRI
&& "Expected target register info");
956 for (const auto &I
: ImplicitOperands
) {
957 if (isImplicitOperandIn(I
, Operands
))
959 return error(Operands
.empty() ? Token
.location() : Operands
.back().End
,
960 Twine("missing implicit register operand '") +
961 printImplicitRegisterFlag(I
) + " $" +
962 getRegisterName(TRI
, I
.getReg()) + "'");
967 bool MIParser::parseInstruction(unsigned &OpCode
, unsigned &Flags
) {
968 // Allow frame and fast math flags for OPCODE
969 while (Token
.is(MIToken::kw_frame_setup
) ||
970 Token
.is(MIToken::kw_frame_destroy
) ||
971 Token
.is(MIToken::kw_nnan
) ||
972 Token
.is(MIToken::kw_ninf
) ||
973 Token
.is(MIToken::kw_nsz
) ||
974 Token
.is(MIToken::kw_arcp
) ||
975 Token
.is(MIToken::kw_contract
) ||
976 Token
.is(MIToken::kw_afn
) ||
977 Token
.is(MIToken::kw_reassoc
) ||
978 Token
.is(MIToken::kw_nuw
) ||
979 Token
.is(MIToken::kw_nsw
) ||
980 Token
.is(MIToken::kw_exact
)) {
981 // Mine frame and fast math flags
982 if (Token
.is(MIToken::kw_frame_setup
))
983 Flags
|= MachineInstr::FrameSetup
;
984 if (Token
.is(MIToken::kw_frame_destroy
))
985 Flags
|= MachineInstr::FrameDestroy
;
986 if (Token
.is(MIToken::kw_nnan
))
987 Flags
|= MachineInstr::FmNoNans
;
988 if (Token
.is(MIToken::kw_ninf
))
989 Flags
|= MachineInstr::FmNoInfs
;
990 if (Token
.is(MIToken::kw_nsz
))
991 Flags
|= MachineInstr::FmNsz
;
992 if (Token
.is(MIToken::kw_arcp
))
993 Flags
|= MachineInstr::FmArcp
;
994 if (Token
.is(MIToken::kw_contract
))
995 Flags
|= MachineInstr::FmContract
;
996 if (Token
.is(MIToken::kw_afn
))
997 Flags
|= MachineInstr::FmAfn
;
998 if (Token
.is(MIToken::kw_reassoc
))
999 Flags
|= MachineInstr::FmReassoc
;
1000 if (Token
.is(MIToken::kw_nuw
))
1001 Flags
|= MachineInstr::NoUWrap
;
1002 if (Token
.is(MIToken::kw_nsw
))
1003 Flags
|= MachineInstr::NoSWrap
;
1004 if (Token
.is(MIToken::kw_exact
))
1005 Flags
|= MachineInstr::IsExact
;
1009 if (Token
.isNot(MIToken::Identifier
))
1010 return error("expected a machine instruction");
1011 StringRef InstrName
= Token
.stringValue();
1012 if (parseInstrName(InstrName
, OpCode
))
1013 return error(Twine("unknown machine instruction name '") + InstrName
+ "'");
1018 bool MIParser::parseNamedRegister(unsigned &Reg
) {
1019 assert(Token
.is(MIToken::NamedRegister
) && "Needs NamedRegister token");
1020 StringRef Name
= Token
.stringValue();
1021 if (getRegisterByName(Name
, Reg
))
1022 return error(Twine("unknown register name '") + Name
+ "'");
1026 bool MIParser::parseNamedVirtualRegister(VRegInfo
*&Info
) {
1027 assert(Token
.is(MIToken::NamedVirtualRegister
) && "Expected NamedVReg token");
1028 StringRef Name
= Token
.stringValue();
1029 // TODO: Check that the VReg name is not the same as a physical register name.
1030 // If it is, then print a warning (when warnings are implemented).
1031 Info
= &PFS
.getVRegInfoNamed(Name
);
1035 bool MIParser::parseVirtualRegister(VRegInfo
*&Info
) {
1036 if (Token
.is(MIToken::NamedVirtualRegister
))
1037 return parseNamedVirtualRegister(Info
);
1038 assert(Token
.is(MIToken::VirtualRegister
) && "Needs VirtualRegister token");
1040 if (getUnsigned(ID
))
1042 Info
= &PFS
.getVRegInfo(ID
);
1046 bool MIParser::parseRegister(unsigned &Reg
, VRegInfo
*&Info
) {
1047 switch (Token
.kind()) {
1048 case MIToken::underscore
:
1051 case MIToken::NamedRegister
:
1052 return parseNamedRegister(Reg
);
1053 case MIToken::NamedVirtualRegister
:
1054 case MIToken::VirtualRegister
:
1055 if (parseVirtualRegister(Info
))
1059 // TODO: Parse other register kinds.
1061 llvm_unreachable("The current token should be a register");
1065 bool MIParser::parseRegisterClassOrBank(VRegInfo
&RegInfo
) {
1066 if (Token
.isNot(MIToken::Identifier
) && Token
.isNot(MIToken::underscore
))
1067 return error("expected '_', register class, or register bank name");
1068 StringRef::iterator Loc
= Token
.location();
1069 StringRef Name
= Token
.stringValue();
1071 // Was it a register class?
1072 auto RCNameI
= PFS
.Names2RegClasses
.find(Name
);
1073 if (RCNameI
!= PFS
.Names2RegClasses
.end()) {
1075 const TargetRegisterClass
&RC
= *RCNameI
->getValue();
1077 switch (RegInfo
.Kind
) {
1078 case VRegInfo::UNKNOWN
:
1079 case VRegInfo::NORMAL
:
1080 RegInfo
.Kind
= VRegInfo::NORMAL
;
1081 if (RegInfo
.Explicit
&& RegInfo
.D
.RC
!= &RC
) {
1082 const TargetRegisterInfo
&TRI
= *MF
.getSubtarget().getRegisterInfo();
1083 return error(Loc
, Twine("conflicting register classes, previously: ") +
1084 Twine(TRI
.getRegClassName(RegInfo
.D
.RC
)));
1087 RegInfo
.Explicit
= true;
1090 case VRegInfo::GENERIC
:
1091 case VRegInfo::REGBANK
:
1092 return error(Loc
, "register class specification on generic register");
1094 llvm_unreachable("Unexpected register kind");
1097 // Should be a register bank or a generic register.
1098 const RegisterBank
*RegBank
= nullptr;
1100 auto RBNameI
= PFS
.Names2RegBanks
.find(Name
);
1101 if (RBNameI
== PFS
.Names2RegBanks
.end())
1102 return error(Loc
, "expected '_', register class, or register bank name");
1103 RegBank
= RBNameI
->getValue();
1108 switch (RegInfo
.Kind
) {
1109 case VRegInfo::UNKNOWN
:
1110 case VRegInfo::GENERIC
:
1111 case VRegInfo::REGBANK
:
1112 RegInfo
.Kind
= RegBank
? VRegInfo::REGBANK
: VRegInfo::GENERIC
;
1113 if (RegInfo
.Explicit
&& RegInfo
.D
.RegBank
!= RegBank
)
1114 return error(Loc
, "conflicting generic register banks");
1115 RegInfo
.D
.RegBank
= RegBank
;
1116 RegInfo
.Explicit
= true;
1119 case VRegInfo::NORMAL
:
1120 return error(Loc
, "register bank specification on normal register");
1122 llvm_unreachable("Unexpected register kind");
1125 bool MIParser::parseRegisterFlag(unsigned &Flags
) {
1126 const unsigned OldFlags
= Flags
;
1127 switch (Token
.kind()) {
1128 case MIToken::kw_implicit
:
1129 Flags
|= RegState::Implicit
;
1131 case MIToken::kw_implicit_define
:
1132 Flags
|= RegState::ImplicitDefine
;
1134 case MIToken::kw_def
:
1135 Flags
|= RegState::Define
;
1137 case MIToken::kw_dead
:
1138 Flags
|= RegState::Dead
;
1140 case MIToken::kw_killed
:
1141 Flags
|= RegState::Kill
;
1143 case MIToken::kw_undef
:
1144 Flags
|= RegState::Undef
;
1146 case MIToken::kw_internal
:
1147 Flags
|= RegState::InternalRead
;
1149 case MIToken::kw_early_clobber
:
1150 Flags
|= RegState::EarlyClobber
;
1152 case MIToken::kw_debug_use
:
1153 Flags
|= RegState::Debug
;
1155 case MIToken::kw_renamable
:
1156 Flags
|= RegState::Renamable
;
1159 llvm_unreachable("The current token should be a register flag");
1161 if (OldFlags
== Flags
)
1162 // We know that the same flag is specified more than once when the flags
1163 // weren't modified.
1164 return error("duplicate '" + Token
.stringValue() + "' register flag");
1169 bool MIParser::parseSubRegisterIndex(unsigned &SubReg
) {
1170 assert(Token
.is(MIToken::dot
));
1172 if (Token
.isNot(MIToken::Identifier
))
1173 return error("expected a subregister index after '.'");
1174 auto Name
= Token
.stringValue();
1175 SubReg
= getSubRegIndex(Name
);
1177 return error(Twine("use of unknown subregister index '") + Name
+ "'");
1182 bool MIParser::parseRegisterTiedDefIndex(unsigned &TiedDefIdx
) {
1183 if (!consumeIfPresent(MIToken::kw_tied_def
))
1185 if (Token
.isNot(MIToken::IntegerLiteral
))
1186 return error("expected an integer literal after 'tied-def'");
1187 if (getUnsigned(TiedDefIdx
))
1190 if (expectAndConsume(MIToken::rparen
))
1195 bool MIParser::assignRegisterTies(MachineInstr
&MI
,
1196 ArrayRef
<ParsedMachineOperand
> Operands
) {
1197 SmallVector
<std::pair
<unsigned, unsigned>, 4> TiedRegisterPairs
;
1198 for (unsigned I
= 0, E
= Operands
.size(); I
!= E
; ++I
) {
1199 if (!Operands
[I
].TiedDefIdx
)
1201 // The parser ensures that this operand is a register use, so we just have
1202 // to check the tied-def operand.
1203 unsigned DefIdx
= Operands
[I
].TiedDefIdx
.getValue();
1205 return error(Operands
[I
].Begin
,
1206 Twine("use of invalid tied-def operand index '" +
1207 Twine(DefIdx
) + "'; instruction has only ") +
1208 Twine(E
) + " operands");
1209 const auto &DefOperand
= Operands
[DefIdx
].Operand
;
1210 if (!DefOperand
.isReg() || !DefOperand
.isDef())
1211 // FIXME: add note with the def operand.
1212 return error(Operands
[I
].Begin
,
1213 Twine("use of invalid tied-def operand index '") +
1214 Twine(DefIdx
) + "'; the operand #" + Twine(DefIdx
) +
1215 " isn't a defined register");
1216 // Check that the tied-def operand wasn't tied elsewhere.
1217 for (const auto &TiedPair
: TiedRegisterPairs
) {
1218 if (TiedPair
.first
== DefIdx
)
1219 return error(Operands
[I
].Begin
,
1220 Twine("the tied-def operand #") + Twine(DefIdx
) +
1221 " is already tied with another register operand");
1223 TiedRegisterPairs
.push_back(std::make_pair(DefIdx
, I
));
1225 // FIXME: Verify that for non INLINEASM instructions, the def and use tied
1226 // indices must be less than tied max.
1227 for (const auto &TiedPair
: TiedRegisterPairs
)
1228 MI
.tieOperands(TiedPair
.first
, TiedPair
.second
);
1232 bool MIParser::parseRegisterOperand(MachineOperand
&Dest
,
1233 Optional
<unsigned> &TiedDefIdx
,
1235 unsigned Flags
= IsDef
? RegState::Define
: 0;
1236 while (Token
.isRegisterFlag()) {
1237 if (parseRegisterFlag(Flags
))
1240 if (!Token
.isRegister())
1241 return error("expected a register after register flags");
1244 if (parseRegister(Reg
, RegInfo
))
1247 unsigned SubReg
= 0;
1248 if (Token
.is(MIToken::dot
)) {
1249 if (parseSubRegisterIndex(SubReg
))
1251 if (!TargetRegisterInfo::isVirtualRegister(Reg
))
1252 return error("subregister index expects a virtual register");
1254 if (Token
.is(MIToken::colon
)) {
1255 if (!TargetRegisterInfo::isVirtualRegister(Reg
))
1256 return error("register class specification expects a virtual register");
1258 if (parseRegisterClassOrBank(*RegInfo
))
1261 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
1262 if ((Flags
& RegState::Define
) == 0) {
1263 if (consumeIfPresent(MIToken::lparen
)) {
1265 if (!parseRegisterTiedDefIndex(Idx
))
1268 // Try a redundant low-level type.
1270 if (parseLowLevelType(Token
.location(), Ty
))
1271 return error("expected tied-def or low-level type after '('");
1273 if (expectAndConsume(MIToken::rparen
))
1276 if (MRI
.getType(Reg
).isValid() && MRI
.getType(Reg
) != Ty
)
1277 return error("inconsistent type for generic virtual register");
1279 MRI
.setType(Reg
, Ty
);
1282 } else if (consumeIfPresent(MIToken::lparen
)) {
1283 // Virtual registers may have a tpe with GlobalISel.
1284 if (!TargetRegisterInfo::isVirtualRegister(Reg
))
1285 return error("unexpected type on physical register");
1288 if (parseLowLevelType(Token
.location(), Ty
))
1291 if (expectAndConsume(MIToken::rparen
))
1294 if (MRI
.getType(Reg
).isValid() && MRI
.getType(Reg
) != Ty
)
1295 return error("inconsistent type for generic virtual register");
1297 MRI
.setType(Reg
, Ty
);
1298 } else if (TargetRegisterInfo::isVirtualRegister(Reg
)) {
1299 // Generic virtual registers must have a type.
1300 // If we end up here this means the type hasn't been specified and
1302 if (RegInfo
->Kind
== VRegInfo::GENERIC
||
1303 RegInfo
->Kind
== VRegInfo::REGBANK
)
1304 return error("generic virtual registers must have a type");
1306 Dest
= MachineOperand::CreateReg(
1307 Reg
, Flags
& RegState::Define
, Flags
& RegState::Implicit
,
1308 Flags
& RegState::Kill
, Flags
& RegState::Dead
, Flags
& RegState::Undef
,
1309 Flags
& RegState::EarlyClobber
, SubReg
, Flags
& RegState::Debug
,
1310 Flags
& RegState::InternalRead
, Flags
& RegState::Renamable
);
1315 bool MIParser::parseImmediateOperand(MachineOperand
&Dest
) {
1316 assert(Token
.is(MIToken::IntegerLiteral
));
1317 const APSInt
&Int
= Token
.integerValue();
1318 if (Int
.getMinSignedBits() > 64)
1319 return error("integer literal is too large to be an immediate operand");
1320 Dest
= MachineOperand::CreateImm(Int
.getExtValue());
1325 bool MIParser::parseIRConstant(StringRef::iterator Loc
, StringRef StringValue
,
1326 const Constant
*&C
) {
1327 auto Source
= StringValue
.str(); // The source has to be null terminated.
1329 C
= parseConstantValue(Source
, Err
, *MF
.getFunction().getParent(),
1332 return error(Loc
+ Err
.getColumnNo(), Err
.getMessage());
1336 bool MIParser::parseIRConstant(StringRef::iterator Loc
, const Constant
*&C
) {
1337 if (parseIRConstant(Loc
, StringRef(Loc
, Token
.range().end() - Loc
), C
))
1343 // See LLT implemntation for bit size limits.
1344 static bool verifyScalarSize(uint64_t Size
) {
1345 return Size
!= 0 && isUInt
<16>(Size
);
1348 static bool verifyVectorElementCount(uint64_t NumElts
) {
1349 return NumElts
!= 0 && isUInt
<16>(NumElts
);
1352 static bool verifyAddrSpace(uint64_t AddrSpace
) {
1353 return isUInt
<24>(AddrSpace
);
1356 bool MIParser::parseLowLevelType(StringRef::iterator Loc
, LLT
&Ty
) {
1357 if (Token
.range().front() == 's' || Token
.range().front() == 'p') {
1358 StringRef SizeStr
= Token
.range().drop_front();
1359 if (SizeStr
.size() == 0 || !llvm::all_of(SizeStr
, isdigit
))
1360 return error("expected integers after 's'/'p' type character");
1363 if (Token
.range().front() == 's') {
1364 auto ScalarSize
= APSInt(Token
.range().drop_front()).getZExtValue();
1365 if (!verifyScalarSize(ScalarSize
))
1366 return error("invalid size for scalar type");
1368 Ty
= LLT::scalar(ScalarSize
);
1371 } else if (Token
.range().front() == 'p') {
1372 const DataLayout
&DL
= MF
.getDataLayout();
1373 uint64_t AS
= APSInt(Token
.range().drop_front()).getZExtValue();
1374 if (!verifyAddrSpace(AS
))
1375 return error("invalid address space number");
1377 Ty
= LLT::pointer(AS
, DL
.getPointerSizeInBits(AS
));
1382 // Now we're looking for a vector.
1383 if (Token
.isNot(MIToken::less
))
1385 "expected sN, pA, <M x sN>, or <M x pA> for GlobalISel type");
1388 if (Token
.isNot(MIToken::IntegerLiteral
))
1389 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1390 uint64_t NumElements
= Token
.integerValue().getZExtValue();
1391 if (!verifyVectorElementCount(NumElements
))
1392 return error("invalid number of vector elements");
1396 if (Token
.isNot(MIToken::Identifier
) || Token
.stringValue() != "x")
1397 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1400 if (Token
.range().front() != 's' && Token
.range().front() != 'p')
1401 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1402 StringRef SizeStr
= Token
.range().drop_front();
1403 if (SizeStr
.size() == 0 || !llvm::all_of(SizeStr
, isdigit
))
1404 return error("expected integers after 's'/'p' type character");
1406 if (Token
.range().front() == 's') {
1407 auto ScalarSize
= APSInt(Token
.range().drop_front()).getZExtValue();
1408 if (!verifyScalarSize(ScalarSize
))
1409 return error("invalid size for scalar type");
1410 Ty
= LLT::scalar(ScalarSize
);
1411 } else if (Token
.range().front() == 'p') {
1412 const DataLayout
&DL
= MF
.getDataLayout();
1413 uint64_t AS
= APSInt(Token
.range().drop_front()).getZExtValue();
1414 if (!verifyAddrSpace(AS
))
1415 return error("invalid address space number");
1417 Ty
= LLT::pointer(AS
, DL
.getPointerSizeInBits(AS
));
1419 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1422 if (Token
.isNot(MIToken::greater
))
1423 return error(Loc
, "expected <M x sN> or <M x pA> for vector type");
1426 Ty
= LLT::vector(NumElements
, Ty
);
1430 bool MIParser::parseTypedImmediateOperand(MachineOperand
&Dest
) {
1431 assert(Token
.is(MIToken::Identifier
));
1432 StringRef TypeStr
= Token
.range();
1433 if (TypeStr
.front() != 'i' && TypeStr
.front() != 's' &&
1434 TypeStr
.front() != 'p')
1436 "a typed immediate operand should start with one of 'i', 's', or 'p'");
1437 StringRef SizeStr
= Token
.range().drop_front();
1438 if (SizeStr
.size() == 0 || !llvm::all_of(SizeStr
, isdigit
))
1439 return error("expected integers after 'i'/'s'/'p' type character");
1441 auto Loc
= Token
.location();
1443 if (Token
.isNot(MIToken::IntegerLiteral
)) {
1444 if (Token
.isNot(MIToken::Identifier
) ||
1445 !(Token
.range() == "true" || Token
.range() == "false"))
1446 return error("expected an integer literal");
1448 const Constant
*C
= nullptr;
1449 if (parseIRConstant(Loc
, C
))
1451 Dest
= MachineOperand::CreateCImm(cast
<ConstantInt
>(C
));
1455 bool MIParser::parseFPImmediateOperand(MachineOperand
&Dest
) {
1456 auto Loc
= Token
.location();
1458 if (Token
.isNot(MIToken::FloatingPointLiteral
) &&
1459 Token
.isNot(MIToken::HexLiteral
))
1460 return error("expected a floating point literal");
1461 const Constant
*C
= nullptr;
1462 if (parseIRConstant(Loc
, C
))
1464 Dest
= MachineOperand::CreateFPImm(cast
<ConstantFP
>(C
));
1468 bool MIParser::getUnsigned(unsigned &Result
) {
1469 if (Token
.hasIntegerValue()) {
1470 const uint64_t Limit
= uint64_t(std::numeric_limits
<unsigned>::max()) + 1;
1471 uint64_t Val64
= Token
.integerValue().getLimitedValue(Limit
);
1473 return error("expected 32-bit integer (too large)");
1477 if (Token
.is(MIToken::HexLiteral
)) {
1481 if (A
.getBitWidth() > 32)
1482 return error("expected 32-bit integer (too large)");
1483 Result
= A
.getZExtValue();
1489 bool MIParser::parseMBBReference(MachineBasicBlock
*&MBB
) {
1490 assert(Token
.is(MIToken::MachineBasicBlock
) ||
1491 Token
.is(MIToken::MachineBasicBlockLabel
));
1493 if (getUnsigned(Number
))
1495 auto MBBInfo
= PFS
.MBBSlots
.find(Number
);
1496 if (MBBInfo
== PFS
.MBBSlots
.end())
1497 return error(Twine("use of undefined machine basic block #") +
1499 MBB
= MBBInfo
->second
;
1500 // TODO: Only parse the name if it's a MachineBasicBlockLabel. Deprecate once
1501 // we drop the <irname> from the bb.<id>.<irname> format.
1502 if (!Token
.stringValue().empty() && Token
.stringValue() != MBB
->getName())
1503 return error(Twine("the name of machine basic block #") + Twine(Number
) +
1504 " isn't '" + Token
.stringValue() + "'");
1508 bool MIParser::parseMBBOperand(MachineOperand
&Dest
) {
1509 MachineBasicBlock
*MBB
;
1510 if (parseMBBReference(MBB
))
1512 Dest
= MachineOperand::CreateMBB(MBB
);
1517 bool MIParser::parseStackFrameIndex(int &FI
) {
1518 assert(Token
.is(MIToken::StackObject
));
1520 if (getUnsigned(ID
))
1522 auto ObjectInfo
= PFS
.StackObjectSlots
.find(ID
);
1523 if (ObjectInfo
== PFS
.StackObjectSlots
.end())
1524 return error(Twine("use of undefined stack object '%stack.") + Twine(ID
) +
1527 if (const auto *Alloca
=
1528 MF
.getFrameInfo().getObjectAllocation(ObjectInfo
->second
))
1529 Name
= Alloca
->getName();
1530 if (!Token
.stringValue().empty() && Token
.stringValue() != Name
)
1531 return error(Twine("the name of the stack object '%stack.") + Twine(ID
) +
1532 "' isn't '" + Token
.stringValue() + "'");
1534 FI
= ObjectInfo
->second
;
1538 bool MIParser::parseStackObjectOperand(MachineOperand
&Dest
) {
1540 if (parseStackFrameIndex(FI
))
1542 Dest
= MachineOperand::CreateFI(FI
);
1546 bool MIParser::parseFixedStackFrameIndex(int &FI
) {
1547 assert(Token
.is(MIToken::FixedStackObject
));
1549 if (getUnsigned(ID
))
1551 auto ObjectInfo
= PFS
.FixedStackObjectSlots
.find(ID
);
1552 if (ObjectInfo
== PFS
.FixedStackObjectSlots
.end())
1553 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
1556 FI
= ObjectInfo
->second
;
1560 bool MIParser::parseFixedStackObjectOperand(MachineOperand
&Dest
) {
1562 if (parseFixedStackFrameIndex(FI
))
1564 Dest
= MachineOperand::CreateFI(FI
);
1568 bool MIParser::parseGlobalValue(GlobalValue
*&GV
) {
1569 switch (Token
.kind()) {
1570 case MIToken::NamedGlobalValue
: {
1571 const Module
*M
= MF
.getFunction().getParent();
1572 GV
= M
->getNamedValue(Token
.stringValue());
1574 return error(Twine("use of undefined global value '") + Token
.range() +
1578 case MIToken::GlobalValue
: {
1580 if (getUnsigned(GVIdx
))
1582 if (GVIdx
>= PFS
.IRSlots
.GlobalValues
.size())
1583 return error(Twine("use of undefined global value '@") + Twine(GVIdx
) +
1585 GV
= PFS
.IRSlots
.GlobalValues
[GVIdx
];
1589 llvm_unreachable("The current token should be a global value");
1594 bool MIParser::parseGlobalAddressOperand(MachineOperand
&Dest
) {
1595 GlobalValue
*GV
= nullptr;
1596 if (parseGlobalValue(GV
))
1599 Dest
= MachineOperand::CreateGA(GV
, /*Offset=*/0);
1600 if (parseOperandsOffset(Dest
))
1605 bool MIParser::parseConstantPoolIndexOperand(MachineOperand
&Dest
) {
1606 assert(Token
.is(MIToken::ConstantPoolItem
));
1608 if (getUnsigned(ID
))
1610 auto ConstantInfo
= PFS
.ConstantPoolSlots
.find(ID
);
1611 if (ConstantInfo
== PFS
.ConstantPoolSlots
.end())
1612 return error("use of undefined constant '%const." + Twine(ID
) + "'");
1614 Dest
= MachineOperand::CreateCPI(ID
, /*Offset=*/0);
1615 if (parseOperandsOffset(Dest
))
1620 bool MIParser::parseJumpTableIndexOperand(MachineOperand
&Dest
) {
1621 assert(Token
.is(MIToken::JumpTableIndex
));
1623 if (getUnsigned(ID
))
1625 auto JumpTableEntryInfo
= PFS
.JumpTableSlots
.find(ID
);
1626 if (JumpTableEntryInfo
== PFS
.JumpTableSlots
.end())
1627 return error("use of undefined jump table '%jump-table." + Twine(ID
) + "'");
1629 Dest
= MachineOperand::CreateJTI(JumpTableEntryInfo
->second
);
1633 bool MIParser::parseExternalSymbolOperand(MachineOperand
&Dest
) {
1634 assert(Token
.is(MIToken::ExternalSymbol
));
1635 const char *Symbol
= MF
.createExternalSymbolName(Token
.stringValue());
1637 Dest
= MachineOperand::CreateES(Symbol
);
1638 if (parseOperandsOffset(Dest
))
1643 bool MIParser::parseMCSymbolOperand(MachineOperand
&Dest
) {
1644 assert(Token
.is(MIToken::MCSymbol
));
1645 MCSymbol
*Symbol
= getOrCreateMCSymbol(Token
.stringValue());
1647 Dest
= MachineOperand::CreateMCSymbol(Symbol
);
1648 if (parseOperandsOffset(Dest
))
1653 bool MIParser::parseSubRegisterIndexOperand(MachineOperand
&Dest
) {
1654 assert(Token
.is(MIToken::SubRegisterIndex
));
1655 StringRef Name
= Token
.stringValue();
1656 unsigned SubRegIndex
= getSubRegIndex(Token
.stringValue());
1657 if (SubRegIndex
== 0)
1658 return error(Twine("unknown subregister index '") + Name
+ "'");
1660 Dest
= MachineOperand::CreateImm(SubRegIndex
);
1664 bool MIParser::parseMDNode(MDNode
*&Node
) {
1665 assert(Token
.is(MIToken::exclaim
));
1667 auto Loc
= Token
.location();
1669 if (Token
.isNot(MIToken::IntegerLiteral
) || Token
.integerValue().isSigned())
1670 return error("expected metadata id after '!'");
1672 if (getUnsigned(ID
))
1674 auto NodeInfo
= PFS
.IRSlots
.MetadataNodes
.find(ID
);
1675 if (NodeInfo
== PFS
.IRSlots
.MetadataNodes
.end())
1676 return error(Loc
, "use of undefined metadata '!" + Twine(ID
) + "'");
1678 Node
= NodeInfo
->second
.get();
1682 bool MIParser::parseDIExpression(MDNode
*&Expr
) {
1683 assert(Token
.is(MIToken::md_diexpr
));
1686 // FIXME: Share this parsing with the IL parser.
1687 SmallVector
<uint64_t, 8> Elements
;
1689 if (expectAndConsume(MIToken::lparen
))
1692 if (Token
.isNot(MIToken::rparen
)) {
1694 if (Token
.is(MIToken::Identifier
)) {
1695 if (unsigned Op
= dwarf::getOperationEncoding(Token
.stringValue())) {
1697 Elements
.push_back(Op
);
1700 return error(Twine("invalid DWARF op '") + Token
.stringValue() + "'");
1703 if (Token
.isNot(MIToken::IntegerLiteral
) ||
1704 Token
.integerValue().isSigned())
1705 return error("expected unsigned integer");
1707 auto &U
= Token
.integerValue();
1708 if (U
.ugt(UINT64_MAX
))
1709 return error("element too large, limit is " + Twine(UINT64_MAX
));
1710 Elements
.push_back(U
.getZExtValue());
1713 } while (consumeIfPresent(MIToken::comma
));
1716 if (expectAndConsume(MIToken::rparen
))
1719 Expr
= DIExpression::get(MF
.getFunction().getContext(), Elements
);
1723 bool MIParser::parseDILocation(MDNode
*&Loc
) {
1724 assert(Token
.is(MIToken::md_dilocation
));
1727 bool HaveLine
= false;
1729 unsigned Column
= 0;
1730 MDNode
*Scope
= nullptr;
1731 MDNode
*InlinedAt
= nullptr;
1732 bool ImplicitCode
= false;
1734 if (expectAndConsume(MIToken::lparen
))
1737 if (Token
.isNot(MIToken::rparen
)) {
1739 if (Token
.is(MIToken::Identifier
)) {
1740 if (Token
.stringValue() == "line") {
1742 if (expectAndConsume(MIToken::colon
))
1744 if (Token
.isNot(MIToken::IntegerLiteral
) ||
1745 Token
.integerValue().isSigned())
1746 return error("expected unsigned integer");
1747 Line
= Token
.integerValue().getZExtValue();
1752 if (Token
.stringValue() == "column") {
1754 if (expectAndConsume(MIToken::colon
))
1756 if (Token
.isNot(MIToken::IntegerLiteral
) ||
1757 Token
.integerValue().isSigned())
1758 return error("expected unsigned integer");
1759 Column
= Token
.integerValue().getZExtValue();
1763 if (Token
.stringValue() == "scope") {
1765 if (expectAndConsume(MIToken::colon
))
1767 if (parseMDNode(Scope
))
1768 return error("expected metadata node");
1769 if (!isa
<DIScope
>(Scope
))
1770 return error("expected DIScope node");
1773 if (Token
.stringValue() == "inlinedAt") {
1775 if (expectAndConsume(MIToken::colon
))
1777 if (Token
.is(MIToken::exclaim
)) {
1778 if (parseMDNode(InlinedAt
))
1780 } else if (Token
.is(MIToken::md_dilocation
)) {
1781 if (parseDILocation(InlinedAt
))
1784 return error("expected metadata node");
1785 if (!isa
<DILocation
>(InlinedAt
))
1786 return error("expected DILocation node");
1789 if (Token
.stringValue() == "isImplicitCode") {
1791 if (expectAndConsume(MIToken::colon
))
1793 if (!Token
.is(MIToken::Identifier
))
1794 return error("expected true/false");
1795 // As far as I can see, we don't have any existing need for parsing
1796 // true/false in MIR yet. Do it ad-hoc until there's something else
1798 if (Token
.stringValue() == "true")
1799 ImplicitCode
= true;
1800 else if (Token
.stringValue() == "false")
1801 ImplicitCode
= false;
1803 return error("expected true/false");
1808 return error(Twine("invalid DILocation argument '") +
1809 Token
.stringValue() + "'");
1810 } while (consumeIfPresent(MIToken::comma
));
1813 if (expectAndConsume(MIToken::rparen
))
1817 return error("DILocation requires line number");
1819 return error("DILocation requires a scope");
1821 Loc
= DILocation::get(MF
.getFunction().getContext(), Line
, Column
, Scope
,
1822 InlinedAt
, ImplicitCode
);
1826 bool MIParser::parseMetadataOperand(MachineOperand
&Dest
) {
1827 MDNode
*Node
= nullptr;
1828 if (Token
.is(MIToken::exclaim
)) {
1829 if (parseMDNode(Node
))
1831 } else if (Token
.is(MIToken::md_diexpr
)) {
1832 if (parseDIExpression(Node
))
1835 Dest
= MachineOperand::CreateMetadata(Node
);
1839 bool MIParser::parseCFIOffset(int &Offset
) {
1840 if (Token
.isNot(MIToken::IntegerLiteral
))
1841 return error("expected a cfi offset");
1842 if (Token
.integerValue().getMinSignedBits() > 32)
1843 return error("expected a 32 bit integer (the cfi offset is too large)");
1844 Offset
= (int)Token
.integerValue().getExtValue();
1849 bool MIParser::parseCFIRegister(unsigned &Reg
) {
1850 if (Token
.isNot(MIToken::NamedRegister
))
1851 return error("expected a cfi register");
1853 if (parseNamedRegister(LLVMReg
))
1855 const auto *TRI
= MF
.getSubtarget().getRegisterInfo();
1856 assert(TRI
&& "Expected target register info");
1857 int DwarfReg
= TRI
->getDwarfRegNum(LLVMReg
, true);
1859 return error("invalid DWARF register");
1860 Reg
= (unsigned)DwarfReg
;
1865 bool MIParser::parseCFIEscapeValues(std::string
&Values
) {
1867 if (Token
.isNot(MIToken::HexLiteral
))
1868 return error("expected a hexadecimal literal");
1870 if (getUnsigned(Value
))
1872 if (Value
> UINT8_MAX
)
1873 return error("expected a 8-bit integer (too large)");
1874 Values
.push_back(static_cast<uint8_t>(Value
));
1876 } while (consumeIfPresent(MIToken::comma
));
1880 bool MIParser::parseCFIOperand(MachineOperand
&Dest
) {
1881 auto Kind
= Token
.kind();
1887 case MIToken::kw_cfi_same_value
:
1888 if (parseCFIRegister(Reg
))
1890 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg
));
1892 case MIToken::kw_cfi_offset
:
1893 if (parseCFIRegister(Reg
) || expectAndConsume(MIToken::comma
) ||
1894 parseCFIOffset(Offset
))
1897 MF
.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg
, Offset
));
1899 case MIToken::kw_cfi_rel_offset
:
1900 if (parseCFIRegister(Reg
) || expectAndConsume(MIToken::comma
) ||
1901 parseCFIOffset(Offset
))
1903 CFIIndex
= MF
.addFrameInst(
1904 MCCFIInstruction::createRelOffset(nullptr, Reg
, Offset
));
1906 case MIToken::kw_cfi_def_cfa_register
:
1907 if (parseCFIRegister(Reg
))
1910 MF
.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg
));
1912 case MIToken::kw_cfi_def_cfa_offset
:
1913 if (parseCFIOffset(Offset
))
1915 // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
1916 CFIIndex
= MF
.addFrameInst(
1917 MCCFIInstruction::createDefCfaOffset(nullptr, -Offset
));
1919 case MIToken::kw_cfi_adjust_cfa_offset
:
1920 if (parseCFIOffset(Offset
))
1922 CFIIndex
= MF
.addFrameInst(
1923 MCCFIInstruction::createAdjustCfaOffset(nullptr, Offset
));
1925 case MIToken::kw_cfi_def_cfa
:
1926 if (parseCFIRegister(Reg
) || expectAndConsume(MIToken::comma
) ||
1927 parseCFIOffset(Offset
))
1929 // NB: MCCFIInstruction::createDefCfa negates the offset.
1931 MF
.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg
, -Offset
));
1933 case MIToken::kw_cfi_remember_state
:
1934 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createRememberState(nullptr));
1936 case MIToken::kw_cfi_restore
:
1937 if (parseCFIRegister(Reg
))
1939 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createRestore(nullptr, Reg
));
1941 case MIToken::kw_cfi_restore_state
:
1942 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createRestoreState(nullptr));
1944 case MIToken::kw_cfi_undefined
:
1945 if (parseCFIRegister(Reg
))
1947 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createUndefined(nullptr, Reg
));
1949 case MIToken::kw_cfi_register
: {
1951 if (parseCFIRegister(Reg
) || expectAndConsume(MIToken::comma
) ||
1952 parseCFIRegister(Reg2
))
1956 MF
.addFrameInst(MCCFIInstruction::createRegister(nullptr, Reg
, Reg2
));
1959 case MIToken::kw_cfi_window_save
:
1960 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createWindowSave(nullptr));
1962 case MIToken::kw_cfi_aarch64_negate_ra_sign_state
:
1963 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
1965 case MIToken::kw_cfi_escape
: {
1967 if (parseCFIEscapeValues(Values
))
1969 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createEscape(nullptr, Values
));
1973 // TODO: Parse the other CFI operands.
1974 llvm_unreachable("The current token should be a cfi operand");
1976 Dest
= MachineOperand::CreateCFIIndex(CFIIndex
);
1980 bool MIParser::parseIRBlock(BasicBlock
*&BB
, const Function
&F
) {
1981 switch (Token
.kind()) {
1982 case MIToken::NamedIRBlock
: {
1983 BB
= dyn_cast_or_null
<BasicBlock
>(
1984 F
.getValueSymbolTable()->lookup(Token
.stringValue()));
1986 return error(Twine("use of undefined IR block '") + Token
.range() + "'");
1989 case MIToken::IRBlock
: {
1990 unsigned SlotNumber
= 0;
1991 if (getUnsigned(SlotNumber
))
1993 BB
= const_cast<BasicBlock
*>(getIRBlock(SlotNumber
, F
));
1995 return error(Twine("use of undefined IR block '%ir-block.") +
1996 Twine(SlotNumber
) + "'");
2000 llvm_unreachable("The current token should be an IR block reference");
2005 bool MIParser::parseBlockAddressOperand(MachineOperand
&Dest
) {
2006 assert(Token
.is(MIToken::kw_blockaddress
));
2008 if (expectAndConsume(MIToken::lparen
))
2010 if (Token
.isNot(MIToken::GlobalValue
) &&
2011 Token
.isNot(MIToken::NamedGlobalValue
))
2012 return error("expected a global value");
2013 GlobalValue
*GV
= nullptr;
2014 if (parseGlobalValue(GV
))
2016 auto *F
= dyn_cast
<Function
>(GV
);
2018 return error("expected an IR function reference");
2020 if (expectAndConsume(MIToken::comma
))
2022 BasicBlock
*BB
= nullptr;
2023 if (Token
.isNot(MIToken::IRBlock
) && Token
.isNot(MIToken::NamedIRBlock
))
2024 return error("expected an IR block reference");
2025 if (parseIRBlock(BB
, *F
))
2028 if (expectAndConsume(MIToken::rparen
))
2030 Dest
= MachineOperand::CreateBA(BlockAddress::get(F
, BB
), /*Offset=*/0);
2031 if (parseOperandsOffset(Dest
))
2036 bool MIParser::parseIntrinsicOperand(MachineOperand
&Dest
) {
2037 assert(Token
.is(MIToken::kw_intrinsic
));
2039 if (expectAndConsume(MIToken::lparen
))
2040 return error("expected syntax intrinsic(@llvm.whatever)");
2042 if (Token
.isNot(MIToken::NamedGlobalValue
))
2043 return error("expected syntax intrinsic(@llvm.whatever)");
2045 std::string Name
= Token
.stringValue();
2048 if (expectAndConsume(MIToken::rparen
))
2049 return error("expected ')' to terminate intrinsic name");
2051 // Find out what intrinsic we're dealing with, first try the global namespace
2052 // and then the target's private intrinsics if that fails.
2053 const TargetIntrinsicInfo
*TII
= MF
.getTarget().getIntrinsicInfo();
2054 Intrinsic::ID ID
= Function::lookupIntrinsicID(Name
);
2055 if (ID
== Intrinsic::not_intrinsic
&& TII
)
2056 ID
= static_cast<Intrinsic::ID
>(TII
->lookupName(Name
));
2058 if (ID
== Intrinsic::not_intrinsic
)
2059 return error("unknown intrinsic name");
2060 Dest
= MachineOperand::CreateIntrinsicID(ID
);
2065 bool MIParser::parsePredicateOperand(MachineOperand
&Dest
) {
2066 assert(Token
.is(MIToken::kw_intpred
) || Token
.is(MIToken::kw_floatpred
));
2067 bool IsFloat
= Token
.is(MIToken::kw_floatpred
);
2070 if (expectAndConsume(MIToken::lparen
))
2071 return error("expected syntax intpred(whatever) or floatpred(whatever");
2073 if (Token
.isNot(MIToken::Identifier
))
2074 return error("whatever");
2076 CmpInst::Predicate Pred
;
2078 Pred
= StringSwitch
<CmpInst::Predicate
>(Token
.stringValue())
2079 .Case("false", CmpInst::FCMP_FALSE
)
2080 .Case("oeq", CmpInst::FCMP_OEQ
)
2081 .Case("ogt", CmpInst::FCMP_OGT
)
2082 .Case("oge", CmpInst::FCMP_OGE
)
2083 .Case("olt", CmpInst::FCMP_OLT
)
2084 .Case("ole", CmpInst::FCMP_OLE
)
2085 .Case("one", CmpInst::FCMP_ONE
)
2086 .Case("ord", CmpInst::FCMP_ORD
)
2087 .Case("uno", CmpInst::FCMP_UNO
)
2088 .Case("ueq", CmpInst::FCMP_UEQ
)
2089 .Case("ugt", CmpInst::FCMP_UGT
)
2090 .Case("uge", CmpInst::FCMP_UGE
)
2091 .Case("ult", CmpInst::FCMP_ULT
)
2092 .Case("ule", CmpInst::FCMP_ULE
)
2093 .Case("une", CmpInst::FCMP_UNE
)
2094 .Case("true", CmpInst::FCMP_TRUE
)
2095 .Default(CmpInst::BAD_FCMP_PREDICATE
);
2096 if (!CmpInst::isFPPredicate(Pred
))
2097 return error("invalid floating-point predicate");
2099 Pred
= StringSwitch
<CmpInst::Predicate
>(Token
.stringValue())
2100 .Case("eq", CmpInst::ICMP_EQ
)
2101 .Case("ne", CmpInst::ICMP_NE
)
2102 .Case("sgt", CmpInst::ICMP_SGT
)
2103 .Case("sge", CmpInst::ICMP_SGE
)
2104 .Case("slt", CmpInst::ICMP_SLT
)
2105 .Case("sle", CmpInst::ICMP_SLE
)
2106 .Case("ugt", CmpInst::ICMP_UGT
)
2107 .Case("uge", CmpInst::ICMP_UGE
)
2108 .Case("ult", CmpInst::ICMP_ULT
)
2109 .Case("ule", CmpInst::ICMP_ULE
)
2110 .Default(CmpInst::BAD_ICMP_PREDICATE
);
2111 if (!CmpInst::isIntPredicate(Pred
))
2112 return error("invalid integer predicate");
2116 Dest
= MachineOperand::CreatePredicate(Pred
);
2117 if (expectAndConsume(MIToken::rparen
))
2118 return error("predicate should be terminated by ')'.");
2123 bool MIParser::parseTargetIndexOperand(MachineOperand
&Dest
) {
2124 assert(Token
.is(MIToken::kw_target_index
));
2126 if (expectAndConsume(MIToken::lparen
))
2128 if (Token
.isNot(MIToken::Identifier
))
2129 return error("expected the name of the target index");
2131 if (getTargetIndex(Token
.stringValue(), Index
))
2132 return error("use of undefined target index '" + Token
.stringValue() + "'");
2134 if (expectAndConsume(MIToken::rparen
))
2136 Dest
= MachineOperand::CreateTargetIndex(unsigned(Index
), /*Offset=*/0);
2137 if (parseOperandsOffset(Dest
))
2142 bool MIParser::parseCustomRegisterMaskOperand(MachineOperand
&Dest
) {
2143 assert(Token
.stringValue() == "CustomRegMask" && "Expected a custom RegMask");
2145 if (expectAndConsume(MIToken::lparen
))
2148 uint32_t *Mask
= MF
.allocateRegMask();
2150 if (Token
.isNot(MIToken::NamedRegister
))
2151 return error("expected a named register");
2153 if (parseNamedRegister(Reg
))
2156 Mask
[Reg
/ 32] |= 1U << (Reg
% 32);
2157 // TODO: Report an error if the same register is used more than once.
2158 if (Token
.isNot(MIToken::comma
))
2163 if (expectAndConsume(MIToken::rparen
))
2165 Dest
= MachineOperand::CreateRegMask(Mask
);
2169 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand
&Dest
) {
2170 assert(Token
.is(MIToken::kw_liveout
));
2171 uint32_t *Mask
= MF
.allocateRegMask();
2173 if (expectAndConsume(MIToken::lparen
))
2176 if (Token
.isNot(MIToken::NamedRegister
))
2177 return error("expected a named register");
2179 if (parseNamedRegister(Reg
))
2182 Mask
[Reg
/ 32] |= 1U << (Reg
% 32);
2183 // TODO: Report an error if the same register is used more than once.
2184 if (Token
.isNot(MIToken::comma
))
2188 if (expectAndConsume(MIToken::rparen
))
2190 Dest
= MachineOperand::CreateRegLiveOut(Mask
);
2194 bool MIParser::parseMachineOperand(MachineOperand
&Dest
,
2195 Optional
<unsigned> &TiedDefIdx
) {
2196 switch (Token
.kind()) {
2197 case MIToken::kw_implicit
:
2198 case MIToken::kw_implicit_define
:
2199 case MIToken::kw_def
:
2200 case MIToken::kw_dead
:
2201 case MIToken::kw_killed
:
2202 case MIToken::kw_undef
:
2203 case MIToken::kw_internal
:
2204 case MIToken::kw_early_clobber
:
2205 case MIToken::kw_debug_use
:
2206 case MIToken::kw_renamable
:
2207 case MIToken::underscore
:
2208 case MIToken::NamedRegister
:
2209 case MIToken::VirtualRegister
:
2210 case MIToken::NamedVirtualRegister
:
2211 return parseRegisterOperand(Dest
, TiedDefIdx
);
2212 case MIToken::IntegerLiteral
:
2213 return parseImmediateOperand(Dest
);
2214 case MIToken::kw_half
:
2215 case MIToken::kw_float
:
2216 case MIToken::kw_double
:
2217 case MIToken::kw_x86_fp80
:
2218 case MIToken::kw_fp128
:
2219 case MIToken::kw_ppc_fp128
:
2220 return parseFPImmediateOperand(Dest
);
2221 case MIToken::MachineBasicBlock
:
2222 return parseMBBOperand(Dest
);
2223 case MIToken::StackObject
:
2224 return parseStackObjectOperand(Dest
);
2225 case MIToken::FixedStackObject
:
2226 return parseFixedStackObjectOperand(Dest
);
2227 case MIToken::GlobalValue
:
2228 case MIToken::NamedGlobalValue
:
2229 return parseGlobalAddressOperand(Dest
);
2230 case MIToken::ConstantPoolItem
:
2231 return parseConstantPoolIndexOperand(Dest
);
2232 case MIToken::JumpTableIndex
:
2233 return parseJumpTableIndexOperand(Dest
);
2234 case MIToken::ExternalSymbol
:
2235 return parseExternalSymbolOperand(Dest
);
2236 case MIToken::MCSymbol
:
2237 return parseMCSymbolOperand(Dest
);
2238 case MIToken::SubRegisterIndex
:
2239 return parseSubRegisterIndexOperand(Dest
);
2240 case MIToken::md_diexpr
:
2241 case MIToken::exclaim
:
2242 return parseMetadataOperand(Dest
);
2243 case MIToken::kw_cfi_same_value
:
2244 case MIToken::kw_cfi_offset
:
2245 case MIToken::kw_cfi_rel_offset
:
2246 case MIToken::kw_cfi_def_cfa_register
:
2247 case MIToken::kw_cfi_def_cfa_offset
:
2248 case MIToken::kw_cfi_adjust_cfa_offset
:
2249 case MIToken::kw_cfi_escape
:
2250 case MIToken::kw_cfi_def_cfa
:
2251 case MIToken::kw_cfi_register
:
2252 case MIToken::kw_cfi_remember_state
:
2253 case MIToken::kw_cfi_restore
:
2254 case MIToken::kw_cfi_restore_state
:
2255 case MIToken::kw_cfi_undefined
:
2256 case MIToken::kw_cfi_window_save
:
2257 case MIToken::kw_cfi_aarch64_negate_ra_sign_state
:
2258 return parseCFIOperand(Dest
);
2259 case MIToken::kw_blockaddress
:
2260 return parseBlockAddressOperand(Dest
);
2261 case MIToken::kw_intrinsic
:
2262 return parseIntrinsicOperand(Dest
);
2263 case MIToken::kw_target_index
:
2264 return parseTargetIndexOperand(Dest
);
2265 case MIToken::kw_liveout
:
2266 return parseLiveoutRegisterMaskOperand(Dest
);
2267 case MIToken::kw_floatpred
:
2268 case MIToken::kw_intpred
:
2269 return parsePredicateOperand(Dest
);
2270 case MIToken::Error
:
2272 case MIToken::Identifier
:
2273 if (const auto *RegMask
= getRegMask(Token
.stringValue())) {
2274 Dest
= MachineOperand::CreateRegMask(RegMask
);
2277 } else if (Token
.stringValue() == "CustomRegMask") {
2278 return parseCustomRegisterMaskOperand(Dest
);
2280 return parseTypedImmediateOperand(Dest
);
2282 // FIXME: Parse the MCSymbol machine operand.
2283 return error("expected a machine operand");
2288 bool MIParser::parseMachineOperandAndTargetFlags(
2289 MachineOperand
&Dest
, Optional
<unsigned> &TiedDefIdx
) {
2291 bool HasTargetFlags
= false;
2292 if (Token
.is(MIToken::kw_target_flags
)) {
2293 HasTargetFlags
= true;
2295 if (expectAndConsume(MIToken::lparen
))
2297 if (Token
.isNot(MIToken::Identifier
))
2298 return error("expected the name of the target flag");
2299 if (getDirectTargetFlag(Token
.stringValue(), TF
)) {
2300 if (getBitmaskTargetFlag(Token
.stringValue(), TF
))
2301 return error("use of undefined target flag '" + Token
.stringValue() +
2305 while (Token
.is(MIToken::comma
)) {
2307 if (Token
.isNot(MIToken::Identifier
))
2308 return error("expected the name of the target flag");
2309 unsigned BitFlag
= 0;
2310 if (getBitmaskTargetFlag(Token
.stringValue(), BitFlag
))
2311 return error("use of undefined target flag '" + Token
.stringValue() +
2313 // TODO: Report an error when using a duplicate bit target flag.
2317 if (expectAndConsume(MIToken::rparen
))
2320 auto Loc
= Token
.location();
2321 if (parseMachineOperand(Dest
, TiedDefIdx
))
2323 if (!HasTargetFlags
)
2326 return error(Loc
, "register operands can't have target flags");
2327 Dest
.setTargetFlags(TF
);
2331 bool MIParser::parseOffset(int64_t &Offset
) {
2332 if (Token
.isNot(MIToken::plus
) && Token
.isNot(MIToken::minus
))
2334 StringRef Sign
= Token
.range();
2335 bool IsNegative
= Token
.is(MIToken::minus
);
2337 if (Token
.isNot(MIToken::IntegerLiteral
))
2338 return error("expected an integer literal after '" + Sign
+ "'");
2339 if (Token
.integerValue().getMinSignedBits() > 64)
2340 return error("expected 64-bit integer (too large)");
2341 Offset
= Token
.integerValue().getExtValue();
2348 bool MIParser::parseAlignment(unsigned &Alignment
) {
2349 assert(Token
.is(MIToken::kw_align
));
2351 if (Token
.isNot(MIToken::IntegerLiteral
) || Token
.integerValue().isSigned())
2352 return error("expected an integer literal after 'align'");
2353 if (getUnsigned(Alignment
))
2357 if (!isPowerOf2_32(Alignment
))
2358 return error("expected a power-of-2 literal after 'align'");
2363 bool MIParser::parseAddrspace(unsigned &Addrspace
) {
2364 assert(Token
.is(MIToken::kw_addrspace
));
2366 if (Token
.isNot(MIToken::IntegerLiteral
) || Token
.integerValue().isSigned())
2367 return error("expected an integer literal after 'addrspace'");
2368 if (getUnsigned(Addrspace
))
2374 bool MIParser::parseOperandsOffset(MachineOperand
&Op
) {
2376 if (parseOffset(Offset
))
2378 Op
.setOffset(Offset
);
2382 bool MIParser::parseIRValue(const Value
*&V
) {
2383 switch (Token
.kind()) {
2384 case MIToken::NamedIRValue
: {
2385 V
= MF
.getFunction().getValueSymbolTable()->lookup(Token
.stringValue());
2388 case MIToken::IRValue
: {
2389 unsigned SlotNumber
= 0;
2390 if (getUnsigned(SlotNumber
))
2392 V
= getIRValue(SlotNumber
);
2395 case MIToken::NamedGlobalValue
:
2396 case MIToken::GlobalValue
: {
2397 GlobalValue
*GV
= nullptr;
2398 if (parseGlobalValue(GV
))
2403 case MIToken::QuotedIRValue
: {
2404 const Constant
*C
= nullptr;
2405 if (parseIRConstant(Token
.location(), Token
.stringValue(), C
))
2411 llvm_unreachable("The current token should be an IR block reference");
2414 return error(Twine("use of undefined IR value '") + Token
.range() + "'");
2418 bool MIParser::getUint64(uint64_t &Result
) {
2419 if (Token
.hasIntegerValue()) {
2420 if (Token
.integerValue().getActiveBits() > 64)
2421 return error("expected 64-bit integer (too large)");
2422 Result
= Token
.integerValue().getZExtValue();
2425 if (Token
.is(MIToken::HexLiteral
)) {
2429 if (A
.getBitWidth() > 64)
2430 return error("expected 64-bit integer (too large)");
2431 Result
= A
.getZExtValue();
2437 bool MIParser::getHexUint(APInt
&Result
) {
2438 assert(Token
.is(MIToken::HexLiteral
));
2439 StringRef S
= Token
.range();
2440 assert(S
[0] == '0' && tolower(S
[1]) == 'x');
2441 // This could be a floating point literal with a special prefix.
2442 if (!isxdigit(S
[2]))
2444 StringRef V
= S
.substr(2);
2445 APInt
A(V
.size()*4, V
, 16);
2447 // If A is 0, then A.getActiveBits() is 0. This isn't a valid bitwidth. Make
2448 // sure it isn't the case before constructing result.
2449 unsigned NumBits
= (A
== 0) ? 32 : A
.getActiveBits();
2450 Result
= APInt(NumBits
, ArrayRef
<uint64_t>(A
.getRawData(), A
.getNumWords()));
2454 bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags
&Flags
) {
2455 const auto OldFlags
= Flags
;
2456 switch (Token
.kind()) {
2457 case MIToken::kw_volatile
:
2458 Flags
|= MachineMemOperand::MOVolatile
;
2460 case MIToken::kw_non_temporal
:
2461 Flags
|= MachineMemOperand::MONonTemporal
;
2463 case MIToken::kw_dereferenceable
:
2464 Flags
|= MachineMemOperand::MODereferenceable
;
2466 case MIToken::kw_invariant
:
2467 Flags
|= MachineMemOperand::MOInvariant
;
2469 case MIToken::StringConstant
: {
2470 MachineMemOperand::Flags TF
;
2471 if (getMMOTargetFlag(Token
.stringValue(), TF
))
2472 return error("use of undefined target MMO flag '" + Token
.stringValue() +
2478 llvm_unreachable("The current token should be a memory operand flag");
2480 if (OldFlags
== Flags
)
2481 // We know that the same flag is specified more than once when the flags
2482 // weren't modified.
2483 return error("duplicate '" + Token
.stringValue() + "' memory operand flag");
2488 bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue
*&PSV
) {
2489 switch (Token
.kind()) {
2490 case MIToken::kw_stack
:
2491 PSV
= MF
.getPSVManager().getStack();
2493 case MIToken::kw_got
:
2494 PSV
= MF
.getPSVManager().getGOT();
2496 case MIToken::kw_jump_table
:
2497 PSV
= MF
.getPSVManager().getJumpTable();
2499 case MIToken::kw_constant_pool
:
2500 PSV
= MF
.getPSVManager().getConstantPool();
2502 case MIToken::FixedStackObject
: {
2504 if (parseFixedStackFrameIndex(FI
))
2506 PSV
= MF
.getPSVManager().getFixedStack(FI
);
2507 // The token was already consumed, so use return here instead of break.
2510 case MIToken::StackObject
: {
2512 if (parseStackFrameIndex(FI
))
2514 PSV
= MF
.getPSVManager().getFixedStack(FI
);
2515 // The token was already consumed, so use return here instead of break.
2518 case MIToken::kw_call_entry
:
2520 switch (Token
.kind()) {
2521 case MIToken::GlobalValue
:
2522 case MIToken::NamedGlobalValue
: {
2523 GlobalValue
*GV
= nullptr;
2524 if (parseGlobalValue(GV
))
2526 PSV
= MF
.getPSVManager().getGlobalValueCallEntry(GV
);
2529 case MIToken::ExternalSymbol
:
2530 PSV
= MF
.getPSVManager().getExternalSymbolCallEntry(
2531 MF
.createExternalSymbolName(Token
.stringValue()));
2535 "expected a global value or an external symbol after 'call-entry'");
2539 llvm_unreachable("The current token should be pseudo source value");
2545 bool MIParser::parseMachinePointerInfo(MachinePointerInfo
&Dest
) {
2546 if (Token
.is(MIToken::kw_constant_pool
) || Token
.is(MIToken::kw_stack
) ||
2547 Token
.is(MIToken::kw_got
) || Token
.is(MIToken::kw_jump_table
) ||
2548 Token
.is(MIToken::FixedStackObject
) || Token
.is(MIToken::StackObject
) ||
2549 Token
.is(MIToken::kw_call_entry
)) {
2550 const PseudoSourceValue
*PSV
= nullptr;
2551 if (parseMemoryPseudoSourceValue(PSV
))
2554 if (parseOffset(Offset
))
2556 Dest
= MachinePointerInfo(PSV
, Offset
);
2559 if (Token
.isNot(MIToken::NamedIRValue
) && Token
.isNot(MIToken::IRValue
) &&
2560 Token
.isNot(MIToken::GlobalValue
) &&
2561 Token
.isNot(MIToken::NamedGlobalValue
) &&
2562 Token
.isNot(MIToken::QuotedIRValue
))
2563 return error("expected an IR value reference");
2564 const Value
*V
= nullptr;
2565 if (parseIRValue(V
))
2567 if (!V
->getType()->isPointerTy())
2568 return error("expected a pointer IR value");
2571 if (parseOffset(Offset
))
2573 Dest
= MachinePointerInfo(V
, Offset
);
2577 bool MIParser::parseOptionalScope(LLVMContext
&Context
,
2578 SyncScope::ID
&SSID
) {
2579 SSID
= SyncScope::System
;
2580 if (Token
.is(MIToken::Identifier
) && Token
.stringValue() == "syncscope") {
2582 if (expectAndConsume(MIToken::lparen
))
2583 return error("expected '(' in syncscope");
2586 if (parseStringConstant(SSN
))
2589 SSID
= Context
.getOrInsertSyncScopeID(SSN
);
2590 if (expectAndConsume(MIToken::rparen
))
2591 return error("expected ')' in syncscope");
2597 bool MIParser::parseOptionalAtomicOrdering(AtomicOrdering
&Order
) {
2598 Order
= AtomicOrdering::NotAtomic
;
2599 if (Token
.isNot(MIToken::Identifier
))
2602 Order
= StringSwitch
<AtomicOrdering
>(Token
.stringValue())
2603 .Case("unordered", AtomicOrdering::Unordered
)
2604 .Case("monotonic", AtomicOrdering::Monotonic
)
2605 .Case("acquire", AtomicOrdering::Acquire
)
2606 .Case("release", AtomicOrdering::Release
)
2607 .Case("acq_rel", AtomicOrdering::AcquireRelease
)
2608 .Case("seq_cst", AtomicOrdering::SequentiallyConsistent
)
2609 .Default(AtomicOrdering::NotAtomic
);
2611 if (Order
!= AtomicOrdering::NotAtomic
) {
2616 return error("expected an atomic scope, ordering or a size specification");
2619 bool MIParser::parseMachineMemoryOperand(MachineMemOperand
*&Dest
) {
2620 if (expectAndConsume(MIToken::lparen
))
2622 MachineMemOperand::Flags Flags
= MachineMemOperand::MONone
;
2623 while (Token
.isMemoryOperandFlag()) {
2624 if (parseMemoryOperandFlag(Flags
))
2627 if (Token
.isNot(MIToken::Identifier
) ||
2628 (Token
.stringValue() != "load" && Token
.stringValue() != "store"))
2629 return error("expected 'load' or 'store' memory operation");
2630 if (Token
.stringValue() == "load")
2631 Flags
|= MachineMemOperand::MOLoad
;
2633 Flags
|= MachineMemOperand::MOStore
;
2636 // Optional 'store' for operands that both load and store.
2637 if (Token
.is(MIToken::Identifier
) && Token
.stringValue() == "store") {
2638 Flags
|= MachineMemOperand::MOStore
;
2642 // Optional synchronization scope.
2644 if (parseOptionalScope(MF
.getFunction().getContext(), SSID
))
2647 // Up to two atomic orderings (cmpxchg provides guarantees on failure).
2648 AtomicOrdering Order
, FailureOrder
;
2649 if (parseOptionalAtomicOrdering(Order
))
2652 if (parseOptionalAtomicOrdering(FailureOrder
))
2655 if (Token
.isNot(MIToken::IntegerLiteral
) &&
2656 Token
.isNot(MIToken::kw_unknown_size
))
2657 return error("expected the size integer literal or 'unknown-size' after "
2658 "memory operation");
2660 if (Token
.is(MIToken::IntegerLiteral
)) {
2661 if (getUint64(Size
))
2663 } else if (Token
.is(MIToken::kw_unknown_size
)) {
2664 Size
= MemoryLocation::UnknownSize
;
2668 MachinePointerInfo Ptr
= MachinePointerInfo();
2669 if (Token
.is(MIToken::Identifier
)) {
2671 ((Flags
& MachineMemOperand::MOLoad
) &&
2672 (Flags
& MachineMemOperand::MOStore
))
2674 : Flags
& MachineMemOperand::MOLoad
? "from" : "into";
2675 if (Token
.stringValue() != Word
)
2676 return error(Twine("expected '") + Word
+ "'");
2679 if (parseMachinePointerInfo(Ptr
))
2682 unsigned BaseAlignment
= (Size
!= MemoryLocation::UnknownSize
? Size
: 1);
2684 MDNode
*Range
= nullptr;
2685 while (consumeIfPresent(MIToken::comma
)) {
2686 switch (Token
.kind()) {
2687 case MIToken::kw_align
:
2688 if (parseAlignment(BaseAlignment
))
2691 case MIToken::kw_addrspace
:
2692 if (parseAddrspace(Ptr
.AddrSpace
))
2695 case MIToken::md_tbaa
:
2697 if (parseMDNode(AAInfo
.TBAA
))
2700 case MIToken::md_alias_scope
:
2702 if (parseMDNode(AAInfo
.Scope
))
2705 case MIToken::md_noalias
:
2707 if (parseMDNode(AAInfo
.NoAlias
))
2710 case MIToken::md_range
:
2712 if (parseMDNode(Range
))
2715 // TODO: Report an error on duplicate metadata nodes.
2717 return error("expected 'align' or '!tbaa' or '!alias.scope' or "
2718 "'!noalias' or '!range'");
2721 if (expectAndConsume(MIToken::rparen
))
2723 Dest
= MF
.getMachineMemOperand(Ptr
, Flags
, Size
, BaseAlignment
, AAInfo
, Range
,
2724 SSID
, Order
, FailureOrder
);
2728 bool MIParser::parsePreOrPostInstrSymbol(MCSymbol
*&Symbol
) {
2729 assert((Token
.is(MIToken::kw_pre_instr_symbol
) ||
2730 Token
.is(MIToken::kw_post_instr_symbol
)) &&
2731 "Invalid token for a pre- post-instruction symbol!");
2733 if (Token
.isNot(MIToken::MCSymbol
))
2734 return error("expected a symbol after 'pre-instr-symbol'");
2735 Symbol
= getOrCreateMCSymbol(Token
.stringValue());
2737 if (Token
.isNewlineOrEOF() || Token
.is(MIToken::coloncolon
) ||
2738 Token
.is(MIToken::lbrace
))
2740 if (Token
.isNot(MIToken::comma
))
2741 return error("expected ',' before the next machine operand");
2746 void MIParser::initNames2InstrOpCodes() {
2747 if (!Names2InstrOpCodes
.empty())
2749 const auto *TII
= MF
.getSubtarget().getInstrInfo();
2750 assert(TII
&& "Expected target instruction info");
2751 for (unsigned I
= 0, E
= TII
->getNumOpcodes(); I
< E
; ++I
)
2752 Names2InstrOpCodes
.insert(std::make_pair(StringRef(TII
->getName(I
)), I
));
2755 bool MIParser::parseInstrName(StringRef InstrName
, unsigned &OpCode
) {
2756 initNames2InstrOpCodes();
2757 auto InstrInfo
= Names2InstrOpCodes
.find(InstrName
);
2758 if (InstrInfo
== Names2InstrOpCodes
.end())
2760 OpCode
= InstrInfo
->getValue();
2764 void MIParser::initNames2Regs() {
2765 if (!Names2Regs
.empty())
2767 // The '%noreg' register is the register 0.
2768 Names2Regs
.insert(std::make_pair("noreg", 0));
2769 const auto *TRI
= MF
.getSubtarget().getRegisterInfo();
2770 assert(TRI
&& "Expected target register info");
2771 for (unsigned I
= 0, E
= TRI
->getNumRegs(); I
< E
; ++I
) {
2773 Names2Regs
.insert(std::make_pair(StringRef(TRI
->getName(I
)).lower(), I
))
2776 assert(WasInserted
&& "Expected registers to be unique case-insensitively");
2780 bool MIParser::getRegisterByName(StringRef RegName
, unsigned &Reg
) {
2782 auto RegInfo
= Names2Regs
.find(RegName
);
2783 if (RegInfo
== Names2Regs
.end())
2785 Reg
= RegInfo
->getValue();
2789 void MIParser::initNames2RegMasks() {
2790 if (!Names2RegMasks
.empty())
2792 const auto *TRI
= MF
.getSubtarget().getRegisterInfo();
2793 assert(TRI
&& "Expected target register info");
2794 ArrayRef
<const uint32_t *> RegMasks
= TRI
->getRegMasks();
2795 ArrayRef
<const char *> RegMaskNames
= TRI
->getRegMaskNames();
2796 assert(RegMasks
.size() == RegMaskNames
.size());
2797 for (size_t I
= 0, E
= RegMasks
.size(); I
< E
; ++I
)
2798 Names2RegMasks
.insert(
2799 std::make_pair(StringRef(RegMaskNames
[I
]).lower(), RegMasks
[I
]));
2802 const uint32_t *MIParser::getRegMask(StringRef Identifier
) {
2803 initNames2RegMasks();
2804 auto RegMaskInfo
= Names2RegMasks
.find(Identifier
);
2805 if (RegMaskInfo
== Names2RegMasks
.end())
2807 return RegMaskInfo
->getValue();
2810 void MIParser::initNames2SubRegIndices() {
2811 if (!Names2SubRegIndices
.empty())
2813 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
2814 for (unsigned I
= 1, E
= TRI
->getNumSubRegIndices(); I
< E
; ++I
)
2815 Names2SubRegIndices
.insert(
2816 std::make_pair(StringRef(TRI
->getSubRegIndexName(I
)).lower(), I
));
2819 unsigned MIParser::getSubRegIndex(StringRef Name
) {
2820 initNames2SubRegIndices();
2821 auto SubRegInfo
= Names2SubRegIndices
.find(Name
);
2822 if (SubRegInfo
== Names2SubRegIndices
.end())
2824 return SubRegInfo
->getValue();
2827 static void initSlots2BasicBlocks(
2829 DenseMap
<unsigned, const BasicBlock
*> &Slots2BasicBlocks
) {
2830 ModuleSlotTracker
MST(F
.getParent(), /*ShouldInitializeAllMetadata=*/false);
2831 MST
.incorporateFunction(F
);
2832 for (auto &BB
: F
) {
2835 int Slot
= MST
.getLocalSlot(&BB
);
2838 Slots2BasicBlocks
.insert(std::make_pair(unsigned(Slot
), &BB
));
2842 static const BasicBlock
*getIRBlockFromSlot(
2844 const DenseMap
<unsigned, const BasicBlock
*> &Slots2BasicBlocks
) {
2845 auto BlockInfo
= Slots2BasicBlocks
.find(Slot
);
2846 if (BlockInfo
== Slots2BasicBlocks
.end())
2848 return BlockInfo
->second
;
2851 const BasicBlock
*MIParser::getIRBlock(unsigned Slot
) {
2852 if (Slots2BasicBlocks
.empty())
2853 initSlots2BasicBlocks(MF
.getFunction(), Slots2BasicBlocks
);
2854 return getIRBlockFromSlot(Slot
, Slots2BasicBlocks
);
2857 const BasicBlock
*MIParser::getIRBlock(unsigned Slot
, const Function
&F
) {
2858 if (&F
== &MF
.getFunction())
2859 return getIRBlock(Slot
);
2860 DenseMap
<unsigned, const BasicBlock
*> CustomSlots2BasicBlocks
;
2861 initSlots2BasicBlocks(F
, CustomSlots2BasicBlocks
);
2862 return getIRBlockFromSlot(Slot
, CustomSlots2BasicBlocks
);
2865 static void mapValueToSlot(const Value
*V
, ModuleSlotTracker
&MST
,
2866 DenseMap
<unsigned, const Value
*> &Slots2Values
) {
2867 int Slot
= MST
.getLocalSlot(V
);
2870 Slots2Values
.insert(std::make_pair(unsigned(Slot
), V
));
2873 /// Creates the mapping from slot numbers to function's unnamed IR values.
2874 static void initSlots2Values(const Function
&F
,
2875 DenseMap
<unsigned, const Value
*> &Slots2Values
) {
2876 ModuleSlotTracker
MST(F
.getParent(), /*ShouldInitializeAllMetadata=*/false);
2877 MST
.incorporateFunction(F
);
2878 for (const auto &Arg
: F
.args())
2879 mapValueToSlot(&Arg
, MST
, Slots2Values
);
2880 for (const auto &BB
: F
) {
2881 mapValueToSlot(&BB
, MST
, Slots2Values
);
2882 for (const auto &I
: BB
)
2883 mapValueToSlot(&I
, MST
, Slots2Values
);
2887 const Value
*MIParser::getIRValue(unsigned Slot
) {
2888 if (Slots2Values
.empty())
2889 initSlots2Values(MF
.getFunction(), Slots2Values
);
2890 auto ValueInfo
= Slots2Values
.find(Slot
);
2891 if (ValueInfo
== Slots2Values
.end())
2893 return ValueInfo
->second
;
2896 void MIParser::initNames2TargetIndices() {
2897 if (!Names2TargetIndices
.empty())
2899 const auto *TII
= MF
.getSubtarget().getInstrInfo();
2900 assert(TII
&& "Expected target instruction info");
2901 auto Indices
= TII
->getSerializableTargetIndices();
2902 for (const auto &I
: Indices
)
2903 Names2TargetIndices
.insert(std::make_pair(StringRef(I
.second
), I
.first
));
2906 bool MIParser::getTargetIndex(StringRef Name
, int &Index
) {
2907 initNames2TargetIndices();
2908 auto IndexInfo
= Names2TargetIndices
.find(Name
);
2909 if (IndexInfo
== Names2TargetIndices
.end())
2911 Index
= IndexInfo
->second
;
2915 void MIParser::initNames2DirectTargetFlags() {
2916 if (!Names2DirectTargetFlags
.empty())
2918 const auto *TII
= MF
.getSubtarget().getInstrInfo();
2919 assert(TII
&& "Expected target instruction info");
2920 auto Flags
= TII
->getSerializableDirectMachineOperandTargetFlags();
2921 for (const auto &I
: Flags
)
2922 Names2DirectTargetFlags
.insert(
2923 std::make_pair(StringRef(I
.second
), I
.first
));
2926 bool MIParser::getDirectTargetFlag(StringRef Name
, unsigned &Flag
) {
2927 initNames2DirectTargetFlags();
2928 auto FlagInfo
= Names2DirectTargetFlags
.find(Name
);
2929 if (FlagInfo
== Names2DirectTargetFlags
.end())
2931 Flag
= FlagInfo
->second
;
2935 void MIParser::initNames2BitmaskTargetFlags() {
2936 if (!Names2BitmaskTargetFlags
.empty())
2938 const auto *TII
= MF
.getSubtarget().getInstrInfo();
2939 assert(TII
&& "Expected target instruction info");
2940 auto Flags
= TII
->getSerializableBitmaskMachineOperandTargetFlags();
2941 for (const auto &I
: Flags
)
2942 Names2BitmaskTargetFlags
.insert(
2943 std::make_pair(StringRef(I
.second
), I
.first
));
2946 bool MIParser::getBitmaskTargetFlag(StringRef Name
, unsigned &Flag
) {
2947 initNames2BitmaskTargetFlags();
2948 auto FlagInfo
= Names2BitmaskTargetFlags
.find(Name
);
2949 if (FlagInfo
== Names2BitmaskTargetFlags
.end())
2951 Flag
= FlagInfo
->second
;
2955 void MIParser::initNames2MMOTargetFlags() {
2956 if (!Names2MMOTargetFlags
.empty())
2958 const auto *TII
= MF
.getSubtarget().getInstrInfo();
2959 assert(TII
&& "Expected target instruction info");
2960 auto Flags
= TII
->getSerializableMachineMemOperandTargetFlags();
2961 for (const auto &I
: Flags
)
2962 Names2MMOTargetFlags
.insert(
2963 std::make_pair(StringRef(I
.second
), I
.first
));
2966 bool MIParser::getMMOTargetFlag(StringRef Name
,
2967 MachineMemOperand::Flags
&Flag
) {
2968 initNames2MMOTargetFlags();
2969 auto FlagInfo
= Names2MMOTargetFlags
.find(Name
);
2970 if (FlagInfo
== Names2MMOTargetFlags
.end())
2972 Flag
= FlagInfo
->second
;
2976 MCSymbol
*MIParser::getOrCreateMCSymbol(StringRef Name
) {
2977 // FIXME: Currently we can't recognize temporary or local symbols and call all
2978 // of the appropriate forms to create them. However, this handles basic cases
2979 // well as most of the special aspects are recognized by a prefix on their
2980 // name, and the input names should already be unique. For test cases, keeping
2981 // the symbol name out of the symbol table isn't terribly important.
2982 return MF
.getContext().getOrCreateSymbol(Name
);
2985 bool MIParser::parseStringConstant(std::string
&Result
) {
2986 if (Token
.isNot(MIToken::StringConstant
))
2987 return error("expected string constant");
2988 Result
= Token
.stringValue();
2993 bool llvm::parseMachineBasicBlockDefinitions(PerFunctionMIParsingState
&PFS
,
2995 SMDiagnostic
&Error
) {
2996 return MIParser(PFS
, Error
, Src
).parseBasicBlockDefinitions(PFS
.MBBSlots
);
2999 bool llvm::parseMachineInstructions(PerFunctionMIParsingState
&PFS
,
3000 StringRef Src
, SMDiagnostic
&Error
) {
3001 return MIParser(PFS
, Error
, Src
).parseBasicBlocks();
3004 bool llvm::parseMBBReference(PerFunctionMIParsingState
&PFS
,
3005 MachineBasicBlock
*&MBB
, StringRef Src
,
3006 SMDiagnostic
&Error
) {
3007 return MIParser(PFS
, Error
, Src
).parseStandaloneMBB(MBB
);
3010 bool llvm::parseRegisterReference(PerFunctionMIParsingState
&PFS
,
3011 unsigned &Reg
, StringRef Src
,
3012 SMDiagnostic
&Error
) {
3013 return MIParser(PFS
, Error
, Src
).parseStandaloneRegister(Reg
);
3016 bool llvm::parseNamedRegisterReference(PerFunctionMIParsingState
&PFS
,
3017 unsigned &Reg
, StringRef Src
,
3018 SMDiagnostic
&Error
) {
3019 return MIParser(PFS
, Error
, Src
).parseStandaloneNamedRegister(Reg
);
3022 bool llvm::parseVirtualRegisterReference(PerFunctionMIParsingState
&PFS
,
3023 VRegInfo
*&Info
, StringRef Src
,
3024 SMDiagnostic
&Error
) {
3025 return MIParser(PFS
, Error
, Src
).parseStandaloneVirtualRegister(Info
);
3028 bool llvm::parseStackObjectReference(PerFunctionMIParsingState
&PFS
,
3029 int &FI
, StringRef Src
,
3030 SMDiagnostic
&Error
) {
3031 return MIParser(PFS
, Error
, Src
).parseStandaloneStackObject(FI
);
3034 bool llvm::parseMDNode(PerFunctionMIParsingState
&PFS
,
3035 MDNode
*&Node
, StringRef Src
, SMDiagnostic
&Error
) {
3036 return MIParser(PFS
, Error
, Src
).parseStandaloneMDNode(Node
);