LLVM  8.0.1
MIParser.cpp
Go to the documentation of this file.
1 //===- MIParser.cpp - Machine instructions parser implementation ----------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the parsing of machine instructions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MIParser.h"
15 #include "MILexer.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/Twine.h"
28 #include "llvm/AsmParser/Parser.h"
42 #include "llvm/IR/BasicBlock.h"
43 #include "llvm/IR/Constants.h"
44 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DebugLoc.h"
47 #include "llvm/IR/Function.h"
48 #include "llvm/IR/InstrTypes.h"
49 #include "llvm/IR/Instructions.h"
50 #include "llvm/IR/Intrinsics.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/Module.h"
54 #include "llvm/IR/Type.h"
55 #include "llvm/IR/Value.h"
57 #include "llvm/MC/LaneBitmask.h"
58 #include "llvm/MC/MCContext.h"
59 #include "llvm/MC/MCDwarf.h"
60 #include "llvm/MC/MCInstrDesc.h"
61 #include "llvm/MC/MCRegisterInfo.h"
64 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/SMLoc.h"
69 #include "llvm/Support/SourceMgr.h"
73 #include <algorithm>
74 #include <cassert>
75 #include <cctype>
76 #include <cstddef>
77 #include <cstdint>
78 #include <limits>
79 #include <string>
80 #include <utility>
81 
82 using namespace llvm;
83 
85  SourceMgr &SM, const SlotMapping &IRSlots,
86  const Name2RegClassMap &Names2RegClasses,
87  const Name2RegBankMap &Names2RegBanks)
88  : MF(MF), SM(&SM), IRSlots(IRSlots), Names2RegClasses(Names2RegClasses),
89  Names2RegBanks(Names2RegBanks) {
90 }
91 
93  auto I = VRegInfos.insert(std::make_pair(Num, nullptr));
94  if (I.second) {
98  I.first->second = Info;
99  }
100  return *I.first->second;
101 }
102 
104  assert(RegName != "" && "Expected named reg.");
105 
106  auto I = VRegInfosNamed.insert(std::make_pair(RegName.str(), nullptr));
107  if (I.second) {
108  VRegInfo *Info = new (Allocator) VRegInfo;
110  I.first->second = Info;
111  }
112  return *I.first->second;
113 }
114 
115 namespace {
116 
117 /// A wrapper struct around the 'MachineOperand' struct that includes a source
118 /// range and other attributes.
119 struct ParsedMachineOperand {
120  MachineOperand Operand;
121  StringRef::iterator Begin;
123  Optional<unsigned> TiedDefIdx;
124 
125  ParsedMachineOperand(const MachineOperand &Operand, StringRef::iterator Begin,
126  StringRef::iterator End, Optional<unsigned> &TiedDefIdx)
127  : Operand(Operand), Begin(Begin), End(End), TiedDefIdx(TiedDefIdx) {
128  if (TiedDefIdx)
129  assert(Operand.isReg() && Operand.isUse() &&
130  "Only used register operands can be tied");
131  }
132 };
133 
134 class MIParser {
137  StringRef Source, CurrentSource;
138  MIToken Token;
140  /// Maps from instruction names to op codes.
141  StringMap<unsigned> Names2InstrOpCodes;
142  /// Maps from register names to registers.
143  StringMap<unsigned> Names2Regs;
144  /// Maps from register mask names to register masks.
145  StringMap<const uint32_t *> Names2RegMasks;
146  /// Maps from subregister names to subregister indices.
147  StringMap<unsigned> Names2SubRegIndices;
148  /// Maps from slot numbers to function's unnamed basic blocks.
149  DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks;
150  /// Maps from slot numbers to function's unnamed values.
152  /// Maps from target index names to target indices.
153  StringMap<int> Names2TargetIndices;
154  /// Maps from direct target flag names to the direct target flag values.
155  StringMap<unsigned> Names2DirectTargetFlags;
156  /// Maps from direct target flag names to the bitmask target flag values.
157  StringMap<unsigned> Names2BitmaskTargetFlags;
158  /// Maps from MMO target flag names to MMO target flag values.
159  StringMap<MachineMemOperand::Flags> Names2MMOTargetFlags;
160 
161 public:
162  MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
163  StringRef Source);
164 
165  /// \p SkipChar gives the number of characters to skip before looking
166  /// for the next token.
167  void lex(unsigned SkipChar = 0);
168 
169  /// Report an error at the current location with the given message.
170  ///
171  /// This function always return true.
172  bool error(const Twine &Msg);
173 
174  /// Report an error at the given location with the given message.
175  ///
176  /// This function always return true.
177  bool error(StringRef::iterator Loc, const Twine &Msg);
178 
179  bool
180  parseBasicBlockDefinitions(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
181  bool parseBasicBlocks();
182  bool parse(MachineInstr *&MI);
183  bool parseStandaloneMBB(MachineBasicBlock *&MBB);
184  bool parseStandaloneNamedRegister(unsigned &Reg);
185  bool parseStandaloneVirtualRegister(VRegInfo *&Info);
186  bool parseStandaloneRegister(unsigned &Reg);
187  bool parseStandaloneStackObject(int &FI);
188  bool parseStandaloneMDNode(MDNode *&Node);
189 
190  bool
191  parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
192  bool parseBasicBlock(MachineBasicBlock &MBB,
193  MachineBasicBlock *&AddFalthroughFrom);
194  bool parseBasicBlockLiveins(MachineBasicBlock &MBB);
195  bool parseBasicBlockSuccessors(MachineBasicBlock &MBB);
196 
197  bool parseNamedRegister(unsigned &Reg);
198  bool parseVirtualRegister(VRegInfo *&Info);
199  bool parseNamedVirtualRegister(VRegInfo *&Info);
200  bool parseRegister(unsigned &Reg, VRegInfo *&VRegInfo);
201  bool parseRegisterFlag(unsigned &Flags);
202  bool parseRegisterClassOrBank(VRegInfo &RegInfo);
203  bool parseSubRegisterIndex(unsigned &SubReg);
204  bool parseRegisterTiedDefIndex(unsigned &TiedDefIdx);
205  bool parseRegisterOperand(MachineOperand &Dest,
206  Optional<unsigned> &TiedDefIdx, bool IsDef = false);
207  bool parseImmediateOperand(MachineOperand &Dest);
208  bool parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
209  const Constant *&C);
210  bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
211  bool parseLowLevelType(StringRef::iterator Loc, LLT &Ty);
212  bool parseTypedImmediateOperand(MachineOperand &Dest);
213  bool parseFPImmediateOperand(MachineOperand &Dest);
215  bool parseMBBOperand(MachineOperand &Dest);
216  bool parseStackFrameIndex(int &FI);
217  bool parseStackObjectOperand(MachineOperand &Dest);
218  bool parseFixedStackFrameIndex(int &FI);
219  bool parseFixedStackObjectOperand(MachineOperand &Dest);
220  bool parseGlobalValue(GlobalValue *&GV);
221  bool parseGlobalAddressOperand(MachineOperand &Dest);
222  bool parseConstantPoolIndexOperand(MachineOperand &Dest);
223  bool parseSubRegisterIndexOperand(MachineOperand &Dest);
224  bool parseJumpTableIndexOperand(MachineOperand &Dest);
225  bool parseExternalSymbolOperand(MachineOperand &Dest);
226  bool parseMCSymbolOperand(MachineOperand &Dest);
227  bool parseMDNode(MDNode *&Node);
228  bool parseDIExpression(MDNode *&Expr);
229  bool parseDILocation(MDNode *&Expr);
230  bool parseMetadataOperand(MachineOperand &Dest);
231  bool parseCFIOffset(int &Offset);
232  bool parseCFIRegister(unsigned &Reg);
233  bool parseCFIEscapeValues(std::string& Values);
234  bool parseCFIOperand(MachineOperand &Dest);
235  bool parseIRBlock(BasicBlock *&BB, const Function &F);
236  bool parseBlockAddressOperand(MachineOperand &Dest);
237  bool parseIntrinsicOperand(MachineOperand &Dest);
238  bool parsePredicateOperand(MachineOperand &Dest);
239  bool parseTargetIndexOperand(MachineOperand &Dest);
240  bool parseCustomRegisterMaskOperand(MachineOperand &Dest);
241  bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
242  bool parseMachineOperand(MachineOperand &Dest,
243  Optional<unsigned> &TiedDefIdx);
244  bool parseMachineOperandAndTargetFlags(MachineOperand &Dest,
245  Optional<unsigned> &TiedDefIdx);
246  bool parseOffset(int64_t &Offset);
247  bool parseAlignment(unsigned &Alignment);
248  bool parseAddrspace(unsigned &Addrspace);
249  bool parseOperandsOffset(MachineOperand &Op);
250  bool parseIRValue(const Value *&V);
251  bool parseMemoryOperandFlag(MachineMemOperand::Flags &Flags);
252  bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
253  bool parseMachinePointerInfo(MachinePointerInfo &Dest);
254  bool parseOptionalScope(LLVMContext &Context, SyncScope::ID &SSID);
255  bool parseOptionalAtomicOrdering(AtomicOrdering &Order);
256  bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
257  bool parsePreOrPostInstrSymbol(MCSymbol *&Symbol);
258 
259 private:
260  /// Convert the integer literal in the current token into an unsigned integer.
261  ///
262  /// Return true if an error occurred.
263  bool getUnsigned(unsigned &Result);
264 
265  /// Convert the integer literal in the current token into an uint64.
266  ///
267  /// Return true if an error occurred.
268  bool getUint64(uint64_t &Result);
269 
270  /// Convert the hexadecimal literal in the current token into an unsigned
271  /// APInt with a minimum bitwidth required to represent the value.
272  ///
273  /// Return true if the literal does not represent an integer value.
274  bool getHexUint(APInt &Result);
275 
276  /// If the current token is of the given kind, consume it and return false.
277  /// Otherwise report an error and return true.
278  bool expectAndConsume(MIToken::TokenKind TokenKind);
279 
280  /// If the current token is of the given kind, consume it and return true.
281  /// Otherwise return false.
282  bool consumeIfPresent(MIToken::TokenKind TokenKind);
283 
284  void initNames2InstrOpCodes();
285 
286  /// Try to convert an instruction name to an opcode. Return true if the
287  /// instruction name is invalid.
288  bool parseInstrName(StringRef InstrName, unsigned &OpCode);
289 
290  bool parseInstruction(unsigned &OpCode, unsigned &Flags);
291 
292  bool assignRegisterTies(MachineInstr &MI,
294 
295  bool verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
296  const MCInstrDesc &MCID);
297 
298  void initNames2Regs();
299 
300  /// Try to convert a register name to a register number. Return true if the
301  /// register name is invalid.
302  bool getRegisterByName(StringRef RegName, unsigned &Reg);
303 
304  void initNames2RegMasks();
305 
306  /// Check if the given identifier is a name of a register mask.
307  ///
308  /// Return null if the identifier isn't a register mask.
309  const uint32_t *getRegMask(StringRef Identifier);
310 
311  void initNames2SubRegIndices();
312 
313  /// Check if the given identifier is a name of a subregister index.
314  ///
315  /// Return 0 if the name isn't a subregister index class.
316  unsigned getSubRegIndex(StringRef Name);
317 
318  const BasicBlock *getIRBlock(unsigned Slot);
319  const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
320 
321  const Value *getIRValue(unsigned Slot);
322 
323  void initNames2TargetIndices();
324 
325  /// Try to convert a name of target index to the corresponding target index.
326  ///
327  /// Return true if the name isn't a name of a target index.
328  bool getTargetIndex(StringRef Name, int &Index);
329 
330  void initNames2DirectTargetFlags();
331 
332  /// Try to convert a name of a direct target flag to the corresponding
333  /// target flag.
334  ///
335  /// Return true if the name isn't a name of a direct flag.
336  bool getDirectTargetFlag(StringRef Name, unsigned &Flag);
337 
338  void initNames2BitmaskTargetFlags();
339 
340  /// Try to convert a name of a bitmask target flag to the corresponding
341  /// target flag.
342  ///
343  /// Return true if the name isn't a name of a bitmask target flag.
344  bool getBitmaskTargetFlag(StringRef Name, unsigned &Flag);
345 
346  void initNames2MMOTargetFlags();
347 
348  /// Try to convert a name of a MachineMemOperand target flag to the
349  /// corresponding target flag.
350  ///
351  /// Return true if the name isn't a name of a target MMO flag.
352  bool getMMOTargetFlag(StringRef Name, MachineMemOperand::Flags &Flag);
353 
354  /// Get or create an MCSymbol for a given name.
355  MCSymbol *getOrCreateMCSymbol(StringRef Name);
356 
357  /// parseStringConstant
358  /// ::= StringConstant
359  bool parseStringConstant(std::string &Result);
360 };
361 
362 } // end anonymous namespace
363 
364 MIParser::MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
366  : MF(PFS.MF), Error(Error), Source(Source), CurrentSource(Source), PFS(PFS)
367 {}
368 
369 void MIParser::lex(unsigned SkipChar) {
370  CurrentSource = lexMIToken(
371  CurrentSource.data() + SkipChar, Token,
372  [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
373 }
374 
375 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
376 
377 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
378  const SourceMgr &SM = *PFS.SM;
379  assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
380  const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
381  if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
382  // Create an ordinary diagnostic when the source manager's buffer is the
383  // source string.
385  return true;
386  }
387  // Create a diagnostic for a YAML string literal.
388  Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
389  Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
390  Source, None, None);
391  return true;
392 }
393 
394 static const char *toString(MIToken::TokenKind TokenKind) {
395  switch (TokenKind) {
396  case MIToken::comma:
397  return "','";
398  case MIToken::equal:
399  return "'='";
400  case MIToken::colon:
401  return "':'";
402  case MIToken::lparen:
403  return "'('";
404  case MIToken::rparen:
405  return "')'";
406  default:
407  return "<unknown token>";
408  }
409 }
410 
411 bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
412  if (Token.isNot(TokenKind))
413  return error(Twine("expected ") + toString(TokenKind));
414  lex();
415  return false;
416 }
417 
418 bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
419  if (Token.isNot(TokenKind))
420  return false;
421  lex();
422  return true;
423 }
424 
425 bool MIParser::parseBasicBlockDefinition(
428  unsigned ID = 0;
429  if (getUnsigned(ID))
430  return true;
431  auto Loc = Token.location();
432  auto Name = Token.stringValue();
433  lex();
434  bool HasAddressTaken = false;
435  bool IsLandingPad = false;
436  unsigned Alignment = 0;
437  BasicBlock *BB = nullptr;
438  if (consumeIfPresent(MIToken::lparen)) {
439  do {
440  // TODO: Report an error when multiple same attributes are specified.
441  switch (Token.kind()) {
443  HasAddressTaken = true;
444  lex();
445  break;
447  IsLandingPad = true;
448  lex();
449  break;
450  case MIToken::kw_align:
451  if (parseAlignment(Alignment))
452  return true;
453  break;
454  case MIToken::IRBlock:
455  // TODO: Report an error when both name and ir block are specified.
456  if (parseIRBlock(BB, MF.getFunction()))
457  return true;
458  lex();
459  break;
460  default:
461  break;
462  }
463  } while (consumeIfPresent(MIToken::comma));
464  if (expectAndConsume(MIToken::rparen))
465  return true;
466  }
467  if (expectAndConsume(MIToken::colon))
468  return true;
469 
470  if (!Name.empty()) {
471  BB = dyn_cast_or_null<BasicBlock>(
473  if (!BB)
474  return error(Loc, Twine("basic block '") + Name +
475  "' is not defined in the function '" +
476  MF.getName() + "'");
477  }
478  auto *MBB = MF.CreateMachineBasicBlock(BB);
479  MF.insert(MF.end(), MBB);
480  bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
481  if (!WasInserted)
482  return error(Loc, Twine("redefinition of machine basic block with id #") +
483  Twine(ID));
484  if (Alignment)
485  MBB->setAlignment(Alignment);
486  if (HasAddressTaken)
487  MBB->setHasAddressTaken();
488  MBB->setIsEHPad(IsLandingPad);
489  return false;
490 }
491 
492 bool MIParser::parseBasicBlockDefinitions(
494  lex();
495  // Skip until the first machine basic block.
496  while (Token.is(MIToken::Newline))
497  lex();
498  if (Token.isErrorOrEOF())
499  return Token.isError();
500  if (Token.isNot(MIToken::MachineBasicBlockLabel))
501  return error("expected a basic block definition before instructions");
502  unsigned BraceDepth = 0;
503  do {
504  if (parseBasicBlockDefinition(MBBSlots))
505  return true;
506  bool IsAfterNewline = false;
507  // Skip until the next machine basic block.
508  while (true) {
509  if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
510  Token.isErrorOrEOF())
511  break;
512  else if (Token.is(MIToken::MachineBasicBlockLabel))
513  return error("basic block definition should be located at the start of "
514  "the line");
515  else if (consumeIfPresent(MIToken::Newline)) {
516  IsAfterNewline = true;
517  continue;
518  }
519  IsAfterNewline = false;
520  if (Token.is(MIToken::lbrace))
521  ++BraceDepth;
522  if (Token.is(MIToken::rbrace)) {
523  if (!BraceDepth)
524  return error("extraneous closing brace ('}')");
525  --BraceDepth;
526  }
527  lex();
528  }
529  // Verify that we closed all of the '{' at the end of a file or a block.
530  if (!Token.isError() && BraceDepth)
531  return error("expected '}'"); // FIXME: Report a note that shows '{'.
532  } while (!Token.isErrorOrEOF());
533  return Token.isError();
534 }
535 
536 bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
537  assert(Token.is(MIToken::kw_liveins));
538  lex();
539  if (expectAndConsume(MIToken::colon))
540  return true;
541  if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
542  return false;
543  do {
544  if (Token.isNot(MIToken::NamedRegister))
545  return error("expected a named register");
546  unsigned Reg = 0;
547  if (parseNamedRegister(Reg))
548  return true;
549  lex();
551  if (consumeIfPresent(MIToken::colon)) {
552  // Parse lane mask.
553  if (Token.isNot(MIToken::IntegerLiteral) &&
554  Token.isNot(MIToken::HexLiteral))
555  return error("expected a lane mask");
556  static_assert(sizeof(LaneBitmask::Type) == sizeof(unsigned),
557  "Use correct get-function for lane mask");
559  if (getUnsigned(V))
560  return error("invalid lane mask value");
561  Mask = LaneBitmask(V);
562  lex();
563  }
564  MBB.addLiveIn(Reg, Mask);
565  } while (consumeIfPresent(MIToken::comma));
566  return false;
567 }
568 
569 bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
570  assert(Token.is(MIToken::kw_successors));
571  lex();
572  if (expectAndConsume(MIToken::colon))
573  return true;
574  if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
575  return false;
576  do {
577  if (Token.isNot(MIToken::MachineBasicBlock))
578  return error("expected a machine basic block reference");
579  MachineBasicBlock *SuccMBB = nullptr;
580  if (parseMBBReference(SuccMBB))
581  return true;
582  lex();
583  unsigned Weight = 0;
584  if (consumeIfPresent(MIToken::lparen)) {
585  if (Token.isNot(MIToken::IntegerLiteral) &&
586  Token.isNot(MIToken::HexLiteral))
587  return error("expected an integer literal after '('");
588  if (getUnsigned(Weight))
589  return true;
590  lex();
591  if (expectAndConsume(MIToken::rparen))
592  return true;
593  }
594  MBB.addSuccessor(SuccMBB, BranchProbability::getRaw(Weight));
595  } while (consumeIfPresent(MIToken::comma));
596  MBB.normalizeSuccProbs();
597  return false;
598 }
599 
600 bool MIParser::parseBasicBlock(MachineBasicBlock &MBB,
601  MachineBasicBlock *&AddFalthroughFrom) {
602  // Skip the definition.
604  lex();
605  if (consumeIfPresent(MIToken::lparen)) {
606  while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
607  lex();
608  consumeIfPresent(MIToken::rparen);
609  }
610  consumeIfPresent(MIToken::colon);
611 
612  // Parse the liveins and successors.
613  // N.B: Multiple lists of successors and liveins are allowed and they're
614  // merged into one.
615  // Example:
616  // liveins: %edi
617  // liveins: %esi
618  //
619  // is equivalent to
620  // liveins: %edi, %esi
621  bool ExplicitSuccessors = false;
622  while (true) {
623  if (Token.is(MIToken::kw_successors)) {
624  if (parseBasicBlockSuccessors(MBB))
625  return true;
626  ExplicitSuccessors = true;
627  } else if (Token.is(MIToken::kw_liveins)) {
628  if (parseBasicBlockLiveins(MBB))
629  return true;
630  } else if (consumeIfPresent(MIToken::Newline)) {
631  continue;
632  } else
633  break;
634  if (!Token.isNewlineOrEOF())
635  return error("expected line break at the end of a list");
636  lex();
637  }
638 
639  // Parse the instructions.
640  bool IsInBundle = false;
641  MachineInstr *PrevMI = nullptr;
642  while (!Token.is(MIToken::MachineBasicBlockLabel) &&
643  !Token.is(MIToken::Eof)) {
644  if (consumeIfPresent(MIToken::Newline))
645  continue;
646  if (consumeIfPresent(MIToken::rbrace)) {
647  // The first parsing pass should verify that all closing '}' have an
648  // opening '{'.
649  assert(IsInBundle);
650  IsInBundle = false;
651  continue;
652  }
653  MachineInstr *MI = nullptr;
654  if (parse(MI))
655  return true;
656  MBB.insert(MBB.end(), MI);
657  if (IsInBundle) {
660  }
661  PrevMI = MI;
662  if (Token.is(MIToken::lbrace)) {
663  if (IsInBundle)
664  return error("nested instruction bundles are not allowed");
665  lex();
666  // This instruction is the start of the bundle.
668  IsInBundle = true;
669  if (!Token.is(MIToken::Newline))
670  // The next instruction can be on the same line.
671  continue;
672  }
673  assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
674  lex();
675  }
676 
677  // Construct successor list by searching for basic block machine operands.
678  if (!ExplicitSuccessors) {
680  bool IsFallthrough;
681  guessSuccessors(MBB, Successors, IsFallthrough);
682  for (MachineBasicBlock *Succ : Successors)
683  MBB.addSuccessor(Succ);
684 
685  if (IsFallthrough) {
686  AddFalthroughFrom = &MBB;
687  } else {
688  MBB.normalizeSuccProbs();
689  }
690  }
691 
692  return false;
693 }
694 
695 bool MIParser::parseBasicBlocks() {
696  lex();
697  // Skip until the first machine basic block.
698  while (Token.is(MIToken::Newline))
699  lex();
700  if (Token.isErrorOrEOF())
701  return Token.isError();
702  // The first parsing pass should have verified that this token is a MBB label
703  // in the 'parseBasicBlockDefinitions' method.
705  MachineBasicBlock *AddFalthroughFrom = nullptr;
706  do {
707  MachineBasicBlock *MBB = nullptr;
708  if (parseMBBReference(MBB))
709  return true;
710  if (AddFalthroughFrom) {
711  if (!AddFalthroughFrom->isSuccessor(MBB))
712  AddFalthroughFrom->addSuccessor(MBB);
713  AddFalthroughFrom->normalizeSuccProbs();
714  AddFalthroughFrom = nullptr;
715  }
716  if (parseBasicBlock(*MBB, AddFalthroughFrom))
717  return true;
718  // The method 'parseBasicBlock' should parse the whole block until the next
719  // block or the end of file.
720  assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
721  } while (Token.isNot(MIToken::Eof));
722  return false;
723 }
724 
726  // Parse any register operands before '='
729  while (Token.isRegister() || Token.isRegisterFlag()) {
730  auto Loc = Token.location();
731  Optional<unsigned> TiedDefIdx;
732  if (parseRegisterOperand(MO, TiedDefIdx, /*IsDef=*/true))
733  return true;
734  Operands.push_back(
735  ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
736  if (Token.isNot(MIToken::comma))
737  break;
738  lex();
739  }
740  if (!Operands.empty() && expectAndConsume(MIToken::equal))
741  return true;
742 
743  unsigned OpCode, Flags = 0;
744  if (Token.isError() || parseInstruction(OpCode, Flags))
745  return true;
746 
747  // Parse the remaining machine operands.
748  while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_pre_instr_symbol) &&
749  Token.isNot(MIToken::kw_post_instr_symbol) &&
750  Token.isNot(MIToken::kw_debug_location) &&
751  Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) {
752  auto Loc = Token.location();
753  Optional<unsigned> TiedDefIdx;
754  if (parseMachineOperandAndTargetFlags(MO, TiedDefIdx))
755  return true;
756  if (OpCode == TargetOpcode::DBG_VALUE && MO.isReg())
757  MO.setIsDebug();
758  Operands.push_back(
759  ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
760  if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
761  Token.is(MIToken::lbrace))
762  break;
763  if (Token.isNot(MIToken::comma))
764  return error("expected ',' before the next machine operand");
765  lex();
766  }
767 
768  MCSymbol *PreInstrSymbol = nullptr;
769  if (Token.is(MIToken::kw_pre_instr_symbol))
770  if (parsePreOrPostInstrSymbol(PreInstrSymbol))
771  return true;
772  MCSymbol *PostInstrSymbol = nullptr;
773  if (Token.is(MIToken::kw_post_instr_symbol))
774  if (parsePreOrPostInstrSymbol(PostInstrSymbol))
775  return true;
776 
777  DebugLoc DebugLocation;
778  if (Token.is(MIToken::kw_debug_location)) {
779  lex();
780  MDNode *Node = nullptr;
781  if (Token.is(MIToken::exclaim)) {
782  if (parseMDNode(Node))
783  return true;
784  } else if (Token.is(MIToken::md_dilocation)) {
785  if (parseDILocation(Node))
786  return true;
787  } else
788  return error("expected a metadata node after 'debug-location'");
789  if (!isa<DILocation>(Node))
790  return error("referenced metadata is not a DILocation");
791  DebugLocation = DebugLoc(Node);
792  }
793 
794  // Parse the machine memory operands.
796  if (Token.is(MIToken::coloncolon)) {
797  lex();
798  while (!Token.isNewlineOrEOF()) {
799  MachineMemOperand *MemOp = nullptr;
800  if (parseMachineMemoryOperand(MemOp))
801  return true;
802  MemOperands.push_back(MemOp);
803  if (Token.isNewlineOrEOF())
804  break;
805  if (Token.isNot(MIToken::comma))
806  return error("expected ',' before the next machine memory operand");
807  lex();
808  }
809  }
810 
811  const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
812  if (!MCID.isVariadic()) {
813  // FIXME: Move the implicit operand verification to the machine verifier.
814  if (verifyImplicitOperands(Operands, MCID))
815  return true;
816  }
817 
818  // TODO: Check for extraneous machine operands.
819  MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
820  MI->setFlags(Flags);
821  for (const auto &Operand : Operands)
822  MI->addOperand(MF, Operand.Operand);
823  if (assignRegisterTies(*MI, Operands))
824  return true;
825  if (PreInstrSymbol)
826  MI->setPreInstrSymbol(MF, PreInstrSymbol);
827  if (PostInstrSymbol)
828  MI->setPostInstrSymbol(MF, PostInstrSymbol);
829  if (!MemOperands.empty())
830  MI->setMemRefs(MF, MemOperands);
831  return false;
832 }
833 
834 bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
835  lex();
836  if (Token.isNot(MIToken::MachineBasicBlock))
837  return error("expected a machine basic block reference");
838  if (parseMBBReference(MBB))
839  return true;
840  lex();
841  if (Token.isNot(MIToken::Eof))
842  return error(
843  "expected end of string after the machine basic block reference");
844  return false;
845 }
846 
847 bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
848  lex();
849  if (Token.isNot(MIToken::NamedRegister))
850  return error("expected a named register");
851  if (parseNamedRegister(Reg))
852  return true;
853  lex();
854  if (Token.isNot(MIToken::Eof))
855  return error("expected end of string after the register reference");
856  return false;
857 }
858 
859 bool MIParser::parseStandaloneVirtualRegister(VRegInfo *&Info) {
860  lex();
861  if (Token.isNot(MIToken::VirtualRegister))
862  return error("expected a virtual register");
863  if (parseVirtualRegister(Info))
864  return true;
865  lex();
866  if (Token.isNot(MIToken::Eof))
867  return error("expected end of string after the register reference");
868  return false;
869 }
870 
871 bool MIParser::parseStandaloneRegister(unsigned &Reg) {
872  lex();
873  if (Token.isNot(MIToken::NamedRegister) &&
874  Token.isNot(MIToken::VirtualRegister))
875  return error("expected either a named or virtual register");
876 
877  VRegInfo *Info;
878  if (parseRegister(Reg, Info))
879  return true;
880 
881  lex();
882  if (Token.isNot(MIToken::Eof))
883  return error("expected end of string after the register reference");
884  return false;
885 }
886 
887 bool MIParser::parseStandaloneStackObject(int &FI) {
888  lex();
889  if (Token.isNot(MIToken::StackObject))
890  return error("expected a stack object");
891  if (parseStackFrameIndex(FI))
892  return true;
893  if (Token.isNot(MIToken::Eof))
894  return error("expected end of string after the stack object reference");
895  return false;
896 }
897 
898 bool MIParser::parseStandaloneMDNode(MDNode *&Node) {
899  lex();
900  if (Token.is(MIToken::exclaim)) {
901  if (parseMDNode(Node))
902  return true;
903  } else if (Token.is(MIToken::md_diexpr)) {
904  if (parseDIExpression(Node))
905  return true;
906  } else if (Token.is(MIToken::md_dilocation)) {
907  if (parseDILocation(Node))
908  return true;
909  } else
910  return error("expected a metadata node");
911  if (Token.isNot(MIToken::Eof))
912  return error("expected end of string after the metadata node");
913  return false;
914 }
915 
916 static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
917  assert(MO.isImplicit());
918  return MO.isDef() ? "implicit-def" : "implicit";
919 }
920 
921 static std::string getRegisterName(const TargetRegisterInfo *TRI,
922  unsigned Reg) {
923  assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
924  return StringRef(TRI->getName(Reg)).lower();
925 }
926 
927 /// Return true if the parsed machine operands contain a given machine operand.
928 static bool isImplicitOperandIn(const MachineOperand &ImplicitOperand,
930  for (const auto &I : Operands) {
931  if (ImplicitOperand.isIdenticalTo(I.Operand))
932  return true;
933  }
934  return false;
935 }
936 
937 bool MIParser::verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
938  const MCInstrDesc &MCID) {
939  if (MCID.isCall())
940  // We can't verify call instructions as they can contain arbitrary implicit
941  // register and register mask operands.
942  return false;
943 
944  // Gather all the expected implicit operands.
945  SmallVector<MachineOperand, 4> ImplicitOperands;
946  if (MCID.ImplicitDefs)
947  for (const MCPhysReg *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
948  ImplicitOperands.push_back(
949  MachineOperand::CreateReg(*ImpDefs, true, true));
950  if (MCID.ImplicitUses)
951  for (const MCPhysReg *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
952  ImplicitOperands.push_back(
953  MachineOperand::CreateReg(*ImpUses, false, true));
954 
955  const auto *TRI = MF.getSubtarget().getRegisterInfo();
956  assert(TRI && "Expected target register info");
957  for (const auto &I : ImplicitOperands) {
958  if (isImplicitOperandIn(I, Operands))
959  continue;
960  return error(Operands.empty() ? Token.location() : Operands.back().End,
961  Twine("missing implicit register operand '") +
962  printImplicitRegisterFlag(I) + " $" +
963  getRegisterName(TRI, I.getReg()) + "'");
964  }
965  return false;
966 }
967 
968 bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
969  // Allow frame and fast math flags for OPCODE
970  while (Token.is(MIToken::kw_frame_setup) ||
971  Token.is(MIToken::kw_frame_destroy) ||
972  Token.is(MIToken::kw_nnan) ||
973  Token.is(MIToken::kw_ninf) ||
974  Token.is(MIToken::kw_nsz) ||
975  Token.is(MIToken::kw_arcp) ||
976  Token.is(MIToken::kw_contract) ||
977  Token.is(MIToken::kw_afn) ||
978  Token.is(MIToken::kw_reassoc) ||
979  Token.is(MIToken::kw_nuw) ||
980  Token.is(MIToken::kw_nsw) ||
981  Token.is(MIToken::kw_exact)) {
982  // Mine frame and fast math flags
983  if (Token.is(MIToken::kw_frame_setup))
984  Flags |= MachineInstr::FrameSetup;
985  if (Token.is(MIToken::kw_frame_destroy))
987  if (Token.is(MIToken::kw_nnan))
988  Flags |= MachineInstr::FmNoNans;
989  if (Token.is(MIToken::kw_ninf))
990  Flags |= MachineInstr::FmNoInfs;
991  if (Token.is(MIToken::kw_nsz))
992  Flags |= MachineInstr::FmNsz;
993  if (Token.is(MIToken::kw_arcp))
994  Flags |= MachineInstr::FmArcp;
995  if (Token.is(MIToken::kw_contract))
996  Flags |= MachineInstr::FmContract;
997  if (Token.is(MIToken::kw_afn))
998  Flags |= MachineInstr::FmAfn;
999  if (Token.is(MIToken::kw_reassoc))
1000  Flags |= MachineInstr::FmReassoc;
1001  if (Token.is(MIToken::kw_nuw))
1002  Flags |= MachineInstr::NoUWrap;
1003  if (Token.is(MIToken::kw_nsw))
1004  Flags |= MachineInstr::NoSWrap;
1005  if (Token.is(MIToken::kw_exact))
1006  Flags |= MachineInstr::IsExact;
1007 
1008  lex();
1009  }
1010  if (Token.isNot(MIToken::Identifier))
1011  return error("expected a machine instruction");
1012  StringRef InstrName = Token.stringValue();
1013  if (parseInstrName(InstrName, OpCode))
1014  return error(Twine("unknown machine instruction name '") + InstrName + "'");
1015  lex();
1016  return false;
1017 }
1018 
1019 bool MIParser::parseNamedRegister(unsigned &Reg) {
1020  assert(Token.is(MIToken::NamedRegister) && "Needs NamedRegister token");
1021  StringRef Name = Token.stringValue();
1022  if (getRegisterByName(Name, Reg))
1023  return error(Twine("unknown register name '") + Name + "'");
1024  return false;
1025 }
1026 
1027 bool MIParser::parseNamedVirtualRegister(VRegInfo *&Info) {
1028  assert(Token.is(MIToken::NamedVirtualRegister) && "Expected NamedVReg token");
1029  StringRef Name = Token.stringValue();
1030  // TODO: Check that the VReg name is not the same as a physical register name.
1031  // If it is, then print a warning (when warnings are implemented).
1032  Info = &PFS.getVRegInfoNamed(Name);
1033  return false;
1034 }
1035 
1036 bool MIParser::parseVirtualRegister(VRegInfo *&Info) {
1037  if (Token.is(MIToken::NamedVirtualRegister))
1038  return parseNamedVirtualRegister(Info);
1039  assert(Token.is(MIToken::VirtualRegister) && "Needs VirtualRegister token");
1040  unsigned ID;
1041  if (getUnsigned(ID))
1042  return true;
1043  Info = &PFS.getVRegInfo(ID);
1044  return false;
1045 }
1046 
1047 bool MIParser::parseRegister(unsigned &Reg, VRegInfo *&Info) {
1048  switch (Token.kind()) {
1049  case MIToken::underscore:
1050  Reg = 0;
1051  return false;
1053  return parseNamedRegister(Reg);
1056  if (parseVirtualRegister(Info))
1057  return true;
1058  Reg = Info->VReg;
1059  return false;
1060  // TODO: Parse other register kinds.
1061  default:
1062  llvm_unreachable("The current token should be a register");
1063  }
1064 }
1065 
1066 bool MIParser::parseRegisterClassOrBank(VRegInfo &RegInfo) {
1067  if (Token.isNot(MIToken::Identifier) && Token.isNot(MIToken::underscore))
1068  return error("expected '_', register class, or register bank name");
1069  StringRef::iterator Loc = Token.location();
1070  StringRef Name = Token.stringValue();
1071 
1072  // Was it a register class?
1073  auto RCNameI = PFS.Names2RegClasses.find(Name);
1074  if (RCNameI != PFS.Names2RegClasses.end()) {
1075  lex();
1076  const TargetRegisterClass &RC = *RCNameI->getValue();
1077 
1078  switch (RegInfo.Kind) {
1079  case VRegInfo::UNKNOWN:
1080  case VRegInfo::NORMAL:
1081  RegInfo.Kind = VRegInfo::NORMAL;
1082  if (RegInfo.Explicit && RegInfo.D.RC != &RC) {
1084  return error(Loc, Twine("conflicting register classes, previously: ") +
1085  Twine(TRI.getRegClassName(RegInfo.D.RC)));
1086  }
1087  RegInfo.D.RC = &RC;
1088  RegInfo.Explicit = true;
1089  return false;
1090 
1091  case VRegInfo::GENERIC:
1092  case VRegInfo::REGBANK:
1093  return error(Loc, "register class specification on generic register");
1094  }
1095  llvm_unreachable("Unexpected register kind");
1096  }
1097 
1098  // Should be a register bank or a generic register.
1099  const RegisterBank *RegBank = nullptr;
1100  if (Name != "_") {
1101  auto RBNameI = PFS.Names2RegBanks.find(Name);
1102  if (RBNameI == PFS.Names2RegBanks.end())
1103  return error(Loc, "expected '_', register class, or register bank name");
1104  RegBank = RBNameI->getValue();
1105  }
1106 
1107  lex();
1108 
1109  switch (RegInfo.Kind) {
1110  case VRegInfo::UNKNOWN:
1111  case VRegInfo::GENERIC:
1112  case VRegInfo::REGBANK:
1113  RegInfo.Kind = RegBank ? VRegInfo::REGBANK : VRegInfo::GENERIC;
1114  if (RegInfo.Explicit && RegInfo.D.RegBank != RegBank)
1115  return error(Loc, "conflicting generic register banks");
1116  RegInfo.D.RegBank = RegBank;
1117  RegInfo.Explicit = true;
1118  return false;
1119 
1120  case VRegInfo::NORMAL:
1121  return error(Loc, "register bank specification on normal register");
1122  }
1123  llvm_unreachable("Unexpected register kind");
1124 }
1125 
1126 bool MIParser::parseRegisterFlag(unsigned &Flags) {
1127  const unsigned OldFlags = Flags;
1128  switch (Token.kind()) {
1129  case MIToken::kw_implicit:
1130  Flags |= RegState::Implicit;
1131  break;
1133  Flags |= RegState::ImplicitDefine;
1134  break;
1135  case MIToken::kw_def:
1136  Flags |= RegState::Define;
1137  break;
1138  case MIToken::kw_dead:
1139  Flags |= RegState::Dead;
1140  break;
1141  case MIToken::kw_killed:
1142  Flags |= RegState::Kill;
1143  break;
1144  case MIToken::kw_undef:
1145  Flags |= RegState::Undef;
1146  break;
1147  case MIToken::kw_internal:
1148  Flags |= RegState::InternalRead;
1149  break;
1151  Flags |= RegState::EarlyClobber;
1152  break;
1153  case MIToken::kw_debug_use:
1154  Flags |= RegState::Debug;
1155  break;
1156  case MIToken::kw_renamable:
1157  Flags |= RegState::Renamable;
1158  break;
1159  default:
1160  llvm_unreachable("The current token should be a register flag");
1161  }
1162  if (OldFlags == Flags)
1163  // We know that the same flag is specified more than once when the flags
1164  // weren't modified.
1165  return error("duplicate '" + Token.stringValue() + "' register flag");
1166  lex();
1167  return false;
1168 }
1169 
1170 bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
1171  assert(Token.is(MIToken::dot));
1172  lex();
1173  if (Token.isNot(MIToken::Identifier))
1174  return error("expected a subregister index after '.'");
1175  auto Name = Token.stringValue();
1176  SubReg = getSubRegIndex(Name);
1177  if (!SubReg)
1178  return error(Twine("use of unknown subregister index '") + Name + "'");
1179  lex();
1180  return false;
1181 }
1182 
1183 bool MIParser::parseRegisterTiedDefIndex(unsigned &TiedDefIdx) {
1184  if (!consumeIfPresent(MIToken::kw_tied_def))
1185  return true;
1186  if (Token.isNot(MIToken::IntegerLiteral))
1187  return error("expected an integer literal after 'tied-def'");
1188  if (getUnsigned(TiedDefIdx))
1189  return true;
1190  lex();
1191  if (expectAndConsume(MIToken::rparen))
1192  return true;
1193  return false;
1194 }
1195 
1196 bool MIParser::assignRegisterTies(MachineInstr &MI,
1197  ArrayRef<ParsedMachineOperand> Operands) {
1198  SmallVector<std::pair<unsigned, unsigned>, 4> TiedRegisterPairs;
1199  for (unsigned I = 0, E = Operands.size(); I != E; ++I) {
1200  if (!Operands[I].TiedDefIdx)
1201  continue;
1202  // The parser ensures that this operand is a register use, so we just have
1203  // to check the tied-def operand.
1204  unsigned DefIdx = Operands[I].TiedDefIdx.getValue();
1205  if (DefIdx >= E)
1206  return error(Operands[I].Begin,
1207  Twine("use of invalid tied-def operand index '" +
1208  Twine(DefIdx) + "'; instruction has only ") +
1209  Twine(E) + " operands");
1210  const auto &DefOperand = Operands[DefIdx].Operand;
1211  if (!DefOperand.isReg() || !DefOperand.isDef())
1212  // FIXME: add note with the def operand.
1213  return error(Operands[I].Begin,
1214  Twine("use of invalid tied-def operand index '") +
1215  Twine(DefIdx) + "'; the operand #" + Twine(DefIdx) +
1216  " isn't a defined register");
1217  // Check that the tied-def operand wasn't tied elsewhere.
1218  for (const auto &TiedPair : TiedRegisterPairs) {
1219  if (TiedPair.first == DefIdx)
1220  return error(Operands[I].Begin,
1221  Twine("the tied-def operand #") + Twine(DefIdx) +
1222  " is already tied with another register operand");
1223  }
1224  TiedRegisterPairs.push_back(std::make_pair(DefIdx, I));
1225  }
1226  // FIXME: Verify that for non INLINEASM instructions, the def and use tied
1227  // indices must be less than tied max.
1228  for (const auto &TiedPair : TiedRegisterPairs)
1229  MI.tieOperands(TiedPair.first, TiedPair.second);
1230  return false;
1231 }
1232 
1233 bool MIParser::parseRegisterOperand(MachineOperand &Dest,
1234  Optional<unsigned> &TiedDefIdx,
1235  bool IsDef) {
1236  unsigned Flags = IsDef ? RegState::Define : 0;
1237  while (Token.isRegisterFlag()) {
1238  if (parseRegisterFlag(Flags))
1239  return true;
1240  }
1241  if (!Token.isRegister())
1242  return error("expected a register after register flags");
1243  unsigned Reg;
1244  VRegInfo *RegInfo;
1245  if (parseRegister(Reg, RegInfo))
1246  return true;
1247  lex();
1248  unsigned SubReg = 0;
1249  if (Token.is(MIToken::dot)) {
1250  if (parseSubRegisterIndex(SubReg))
1251  return true;
1253  return error("subregister index expects a virtual register");
1254  }
1255  if (Token.is(MIToken::colon)) {
1257  return error("register class specification expects a virtual register");
1258  lex();
1259  if (parseRegisterClassOrBank(*RegInfo))
1260  return true;
1261  }
1263  if ((Flags & RegState::Define) == 0) {
1264  if (consumeIfPresent(MIToken::lparen)) {
1265  unsigned Idx;
1266  if (!parseRegisterTiedDefIndex(Idx))
1267  TiedDefIdx = Idx;
1268  else {
1269  // Try a redundant low-level type.
1270  LLT Ty;
1271  if (parseLowLevelType(Token.location(), Ty))
1272  return error("expected tied-def or low-level type after '('");
1273 
1274  if (expectAndConsume(MIToken::rparen))
1275  return true;
1276 
1277  if (MRI.getType(Reg).isValid() && MRI.getType(Reg) != Ty)
1278  return error("inconsistent type for generic virtual register");
1279 
1280  MRI.setType(Reg, Ty);
1281  }
1282  }
1283  } else if (consumeIfPresent(MIToken::lparen)) {
1284  // Virtual registers may have a tpe with GlobalISel.
1286  return error("unexpected type on physical register");
1287 
1288  LLT Ty;
1289  if (parseLowLevelType(Token.location(), Ty))
1290  return true;
1291 
1292  if (expectAndConsume(MIToken::rparen))
1293  return true;
1294 
1295  if (MRI.getType(Reg).isValid() && MRI.getType(Reg) != Ty)
1296  return error("inconsistent type for generic virtual register");
1297 
1298  MRI.setType(Reg, Ty);
1299  } else if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1300  // Generic virtual registers must have a type.
1301  // If we end up here this means the type hasn't been specified and
1302  // this is bad!
1303  if (RegInfo->Kind == VRegInfo::GENERIC ||
1304  RegInfo->Kind == VRegInfo::REGBANK)
1305  return error("generic virtual registers must have a type");
1306  }
1308  Reg, Flags & RegState::Define, Flags & RegState::Implicit,
1309  Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
1310  Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug,
1311  Flags & RegState::InternalRead, Flags & RegState::Renamable);
1312 
1313  return false;
1314 }
1315 
1316 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
1317  assert(Token.is(MIToken::IntegerLiteral));
1318  const APSInt &Int = Token.integerValue();
1319  if (Int.getMinSignedBits() > 64)
1320  return error("integer literal is too large to be an immediate operand");
1321  Dest = MachineOperand::CreateImm(Int.getExtValue());
1322  lex();
1323  return false;
1324 }
1325 
1326 bool MIParser::parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
1327  const Constant *&C) {
1328  auto Source = StringValue.str(); // The source has to be null terminated.
1329  SMDiagnostic Err;
1330  C = parseConstantValue(Source, Err, *MF.getFunction().getParent(),
1331  &PFS.IRSlots);
1332  if (!C)
1333  return error(Loc + Err.getColumnNo(), Err.getMessage());
1334  return false;
1335 }
1336 
1337 bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
1338  if (parseIRConstant(Loc, StringRef(Loc, Token.range().end() - Loc), C))
1339  return true;
1340  lex();
1341  return false;
1342 }
1343 
1344 bool MIParser::parseLowLevelType(StringRef::iterator Loc, LLT &Ty) {
1345  if (Token.range().front() == 's' || Token.range().front() == 'p') {
1346  StringRef SizeStr = Token.range().drop_front();
1347  if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
1348  return error("expected integers after 's'/'p' type character");
1349  }
1350 
1351  if (Token.range().front() == 's') {
1352  Ty = LLT::scalar(APSInt(Token.range().drop_front()).getZExtValue());
1353  lex();
1354  return false;
1355  } else if (Token.range().front() == 'p') {
1356  const DataLayout &DL = MF.getDataLayout();
1357  unsigned AS = APSInt(Token.range().drop_front()).getZExtValue();
1358  Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
1359  lex();
1360  return false;
1361  }
1362 
1363  // Now we're looking for a vector.
1364  if (Token.isNot(MIToken::less))
1365  return error(Loc,
1366  "expected sN, pA, <M x sN>, or <M x pA> for GlobalISel type");
1367  lex();
1368 
1369  if (Token.isNot(MIToken::IntegerLiteral))
1370  return error(Loc, "expected <M x sN> or <M x pA> for vector type");
1371  uint64_t NumElements = Token.integerValue().getZExtValue();
1372  lex();
1373 
1374  if (Token.isNot(MIToken::Identifier) || Token.stringValue() != "x")
1375  return error(Loc, "expected <M x sN> or <M x pA> for vector type");
1376  lex();
1377 
1378  if (Token.range().front() != 's' && Token.range().front() != 'p')
1379  return error(Loc, "expected <M x sN> or <M x pA> for vector type");
1380  StringRef SizeStr = Token.range().drop_front();
1381  if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
1382  return error("expected integers after 's'/'p' type character");
1383 
1384  if (Token.range().front() == 's')
1385  Ty = LLT::scalar(APSInt(Token.range().drop_front()).getZExtValue());
1386  else if (Token.range().front() == 'p') {
1387  const DataLayout &DL = MF.getDataLayout();
1388  unsigned AS = APSInt(Token.range().drop_front()).getZExtValue();
1389  Ty = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
1390  } else
1391  return error(Loc, "expected <M x sN> or <M x pA> for vector type");
1392  lex();
1393 
1394  if (Token.isNot(MIToken::greater))
1395  return error(Loc, "expected <M x sN> or <M x pA> for vector type");
1396  lex();
1397 
1398  Ty = LLT::vector(NumElements, Ty);
1399  return false;
1400 }
1401 
1402 bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
1403  assert(Token.is(MIToken::Identifier));
1404  StringRef TypeStr = Token.range();
1405  if (TypeStr.front() != 'i' && TypeStr.front() != 's' &&
1406  TypeStr.front() != 'p')
1407  return error(
1408  "a typed immediate operand should start with one of 'i', 's', or 'p'");
1409  StringRef SizeStr = Token.range().drop_front();
1410  if (SizeStr.size() == 0 || !llvm::all_of(SizeStr, isdigit))
1411  return error("expected integers after 'i'/'s'/'p' type character");
1412 
1413  auto Loc = Token.location();
1414  lex();
1415  if (Token.isNot(MIToken::IntegerLiteral)) {
1416  if (Token.isNot(MIToken::Identifier) ||
1417  !(Token.range() == "true" || Token.range() == "false"))
1418  return error("expected an integer literal");
1419  }
1420  const Constant *C = nullptr;
1421  if (parseIRConstant(Loc, C))
1422  return true;
1423  Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C));
1424  return false;
1425 }
1426 
1427 bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
1428  auto Loc = Token.location();
1429  lex();
1430  if (Token.isNot(MIToken::FloatingPointLiteral) &&
1431  Token.isNot(MIToken::HexLiteral))
1432  return error("expected a floating point literal");
1433  const Constant *C = nullptr;
1434  if (parseIRConstant(Loc, C))
1435  return true;
1436  Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
1437  return false;
1438 }
1439 
1440 bool MIParser::getUnsigned(unsigned &Result) {
1441  if (Token.hasIntegerValue()) {
1442  const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
1443  uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
1444  if (Val64 == Limit)
1445  return error("expected 32-bit integer (too large)");
1446  Result = Val64;
1447  return false;
1448  }
1449  if (Token.is(MIToken::HexLiteral)) {
1450  APInt A;
1451  if (getHexUint(A))
1452  return true;
1453  if (A.getBitWidth() > 32)
1454  return error("expected 32-bit integer (too large)");
1455  Result = A.getZExtValue();
1456  return false;
1457  }
1458  return true;
1459 }
1460 
1462  assert(Token.is(MIToken::MachineBasicBlock) ||
1464  unsigned Number;
1465  if (getUnsigned(Number))
1466  return true;
1467  auto MBBInfo = PFS.MBBSlots.find(Number);
1468  if (MBBInfo == PFS.MBBSlots.end())
1469  return error(Twine("use of undefined machine basic block #") +
1470  Twine(Number));
1471  MBB = MBBInfo->second;
1472  // TODO: Only parse the name if it's a MachineBasicBlockLabel. Deprecate once
1473  // we drop the <irname> from the bb.<id>.<irname> format.
1474  if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
1475  return error(Twine("the name of machine basic block #") + Twine(Number) +
1476  " isn't '" + Token.stringValue() + "'");
1477  return false;
1478 }
1479 
1480 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
1481  MachineBasicBlock *MBB;
1482  if (parseMBBReference(MBB))
1483  return true;
1484  Dest = MachineOperand::CreateMBB(MBB);
1485  lex();
1486  return false;
1487 }
1488 
1489 bool MIParser::parseStackFrameIndex(int &FI) {
1490  assert(Token.is(MIToken::StackObject));
1491  unsigned ID;
1492  if (getUnsigned(ID))
1493  return true;
1494  auto ObjectInfo = PFS.StackObjectSlots.find(ID);
1495  if (ObjectInfo == PFS.StackObjectSlots.end())
1496  return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
1497  "'");
1498  StringRef Name;
1499  if (const auto *Alloca =
1500  MF.getFrameInfo().getObjectAllocation(ObjectInfo->second))
1501  Name = Alloca->getName();
1502  if (!Token.stringValue().empty() && Token.stringValue() != Name)
1503  return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
1504  "' isn't '" + Token.stringValue() + "'");
1505  lex();
1506  FI = ObjectInfo->second;
1507  return false;
1508 }
1509 
1510 bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
1511  int FI;
1512  if (parseStackFrameIndex(FI))
1513  return true;
1514  Dest = MachineOperand::CreateFI(FI);
1515  return false;
1516 }
1517 
1518 bool MIParser::parseFixedStackFrameIndex(int &FI) {
1519  assert(Token.is(MIToken::FixedStackObject));
1520  unsigned ID;
1521  if (getUnsigned(ID))
1522  return true;
1523  auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
1524  if (ObjectInfo == PFS.FixedStackObjectSlots.end())
1525  return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
1526  Twine(ID) + "'");
1527  lex();
1528  FI = ObjectInfo->second;
1529  return false;
1530 }
1531 
1532 bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
1533  int FI;
1534  if (parseFixedStackFrameIndex(FI))
1535  return true;
1536  Dest = MachineOperand::CreateFI(FI);
1537  return false;
1538 }
1539 
1540 bool MIParser::parseGlobalValue(GlobalValue *&GV) {
1541  switch (Token.kind()) {
1543  const Module *M = MF.getFunction().getParent();
1544  GV = M->getNamedValue(Token.stringValue());
1545  if (!GV)
1546  return error(Twine("use of undefined global value '") + Token.range() +
1547  "'");
1548  break;
1549  }
1550  case MIToken::GlobalValue: {
1551  unsigned GVIdx;
1552  if (getUnsigned(GVIdx))
1553  return true;
1554  if (GVIdx >= PFS.IRSlots.GlobalValues.size())
1555  return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
1556  "'");
1557  GV = PFS.IRSlots.GlobalValues[GVIdx];
1558  break;
1559  }
1560  default:
1561  llvm_unreachable("The current token should be a global value");
1562  }
1563  return false;
1564 }
1565 
1566 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
1567  GlobalValue *GV = nullptr;
1568  if (parseGlobalValue(GV))
1569  return true;
1570  lex();
1571  Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
1572  if (parseOperandsOffset(Dest))
1573  return true;
1574  return false;
1575 }
1576 
1577 bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
1578  assert(Token.is(MIToken::ConstantPoolItem));
1579  unsigned ID;
1580  if (getUnsigned(ID))
1581  return true;
1582  auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
1583  if (ConstantInfo == PFS.ConstantPoolSlots.end())
1584  return error("use of undefined constant '%const." + Twine(ID) + "'");
1585  lex();
1586  Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
1587  if (parseOperandsOffset(Dest))
1588  return true;
1589  return false;
1590 }
1591 
1592 bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
1593  assert(Token.is(MIToken::JumpTableIndex));
1594  unsigned ID;
1595  if (getUnsigned(ID))
1596  return true;
1597  auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
1598  if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
1599  return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
1600  lex();
1601  Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
1602  return false;
1603 }
1604 
1605 bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
1606  assert(Token.is(MIToken::ExternalSymbol));
1607  const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
1608  lex();
1609  Dest = MachineOperand::CreateES(Symbol);
1610  if (parseOperandsOffset(Dest))
1611  return true;
1612  return false;
1613 }
1614 
1615 bool MIParser::parseMCSymbolOperand(MachineOperand &Dest) {
1616  assert(Token.is(MIToken::MCSymbol));
1617  MCSymbol *Symbol = getOrCreateMCSymbol(Token.stringValue());
1618  lex();
1619  Dest = MachineOperand::CreateMCSymbol(Symbol);
1620  if (parseOperandsOffset(Dest))
1621  return true;
1622  return false;
1623 }
1624 
1625 bool MIParser::parseSubRegisterIndexOperand(MachineOperand &Dest) {
1626  assert(Token.is(MIToken::SubRegisterIndex));
1627  StringRef Name = Token.stringValue();
1628  unsigned SubRegIndex = getSubRegIndex(Token.stringValue());
1629  if (SubRegIndex == 0)
1630  return error(Twine("unknown subregister index '") + Name + "'");
1631  lex();
1632  Dest = MachineOperand::CreateImm(SubRegIndex);
1633  return false;
1634 }
1635 
1636 bool MIParser::parseMDNode(MDNode *&Node) {
1637  assert(Token.is(MIToken::exclaim));
1638 
1639  auto Loc = Token.location();
1640  lex();
1641  if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1642  return error("expected metadata id after '!'");
1643  unsigned ID;
1644  if (getUnsigned(ID))
1645  return true;
1646  auto NodeInfo = PFS.IRSlots.MetadataNodes.find(ID);
1647  if (NodeInfo == PFS.IRSlots.MetadataNodes.end())
1648  return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
1649  lex();
1650  Node = NodeInfo->second.get();
1651  return false;
1652 }
1653 
1654 bool MIParser::parseDIExpression(MDNode *&Expr) {
1655  assert(Token.is(MIToken::md_diexpr));
1656  lex();
1657 
1658  // FIXME: Share this parsing with the IL parser.
1659  SmallVector<uint64_t, 8> Elements;
1660 
1661  if (expectAndConsume(MIToken::lparen))
1662  return true;
1663 
1664  if (Token.isNot(MIToken::rparen)) {
1665  do {
1666  if (Token.is(MIToken::Identifier)) {
1667  if (unsigned Op = dwarf::getOperationEncoding(Token.stringValue())) {
1668  lex();
1669  Elements.push_back(Op);
1670  continue;
1671  }
1672  return error(Twine("invalid DWARF op '") + Token.stringValue() + "'");
1673  }
1674 
1675  if (Token.isNot(MIToken::IntegerLiteral) ||
1676  Token.integerValue().isSigned())
1677  return error("expected unsigned integer");
1678 
1679  auto &U = Token.integerValue();
1680  if (U.ugt(UINT64_MAX))
1681  return error("element too large, limit is " + Twine(UINT64_MAX));
1682  Elements.push_back(U.getZExtValue());
1683  lex();
1684 
1685  } while (consumeIfPresent(MIToken::comma));
1686  }
1687 
1688  if (expectAndConsume(MIToken::rparen))
1689  return true;
1690 
1691  Expr = DIExpression::get(MF.getFunction().getContext(), Elements);
1692  return false;
1693 }
1694 
1695 bool MIParser::parseDILocation(MDNode *&Loc) {
1696  assert(Token.is(MIToken::md_dilocation));
1697  lex();
1698 
1699  bool HaveLine = false;
1700  unsigned Line = 0;
1701  unsigned Column = 0;
1702  MDNode *Scope = nullptr;
1703  MDNode *InlinedAt = nullptr;
1704  bool ImplicitCode = false;
1705 
1706  if (expectAndConsume(MIToken::lparen))
1707  return true;
1708 
1709  if (Token.isNot(MIToken::rparen)) {
1710  do {
1711  if (Token.is(MIToken::Identifier)) {
1712  if (Token.stringValue() == "line") {
1713  lex();
1714  if (expectAndConsume(MIToken::colon))
1715  return true;
1716  if (Token.isNot(MIToken::IntegerLiteral) ||
1717  Token.integerValue().isSigned())
1718  return error("expected unsigned integer");
1719  Line = Token.integerValue().getZExtValue();
1720  HaveLine = true;
1721  lex();
1722  continue;
1723  }
1724  if (Token.stringValue() == "column") {
1725  lex();
1726  if (expectAndConsume(MIToken::colon))
1727  return true;
1728  if (Token.isNot(MIToken::IntegerLiteral) ||
1729  Token.integerValue().isSigned())
1730  return error("expected unsigned integer");
1731  Column = Token.integerValue().getZExtValue();
1732  lex();
1733  continue;
1734  }
1735  if (Token.stringValue() == "scope") {
1736  lex();
1737  if (expectAndConsume(MIToken::colon))
1738  return true;
1739  if (parseMDNode(Scope))
1740  return error("expected metadata node");
1741  if (!isa<DIScope>(Scope))
1742  return error("expected DIScope node");
1743  continue;
1744  }
1745  if (Token.stringValue() == "inlinedAt") {
1746  lex();
1747  if (expectAndConsume(MIToken::colon))
1748  return true;
1749  if (Token.is(MIToken::exclaim)) {
1750  if (parseMDNode(InlinedAt))
1751  return true;
1752  } else if (Token.is(MIToken::md_dilocation)) {
1753  if (parseDILocation(InlinedAt))
1754  return true;
1755  } else
1756  return error("expected metadata node");
1757  if (!isa<DILocation>(InlinedAt))
1758  return error("expected DILocation node");
1759  continue;
1760  }
1761  if (Token.stringValue() == "isImplicitCode") {
1762  lex();
1763  if (expectAndConsume(MIToken::colon))
1764  return true;
1765  if (!Token.is(MIToken::Identifier))
1766  return error("expected true/false");
1767  // As far as I can see, we don't have any existing need for parsing
1768  // true/false in MIR yet. Do it ad-hoc until there's something else
1769  // that needs it.
1770  if (Token.stringValue() == "true")
1771  ImplicitCode = true;
1772  else if (Token.stringValue() == "false")
1773  ImplicitCode = false;
1774  else
1775  return error("expected true/false");
1776  lex();
1777  continue;
1778  }
1779  }
1780  return error(Twine("invalid DILocation argument '") +
1781  Token.stringValue() + "'");
1782  } while (consumeIfPresent(MIToken::comma));
1783  }
1784 
1785  if (expectAndConsume(MIToken::rparen))
1786  return true;
1787 
1788  if (!HaveLine)
1789  return error("DILocation requires line number");
1790  if (!Scope)
1791  return error("DILocation requires a scope");
1792 
1793  Loc = DILocation::get(MF.getFunction().getContext(), Line, Column, Scope,
1794  InlinedAt, ImplicitCode);
1795  return false;
1796 }
1797 
1798 bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
1799  MDNode *Node = nullptr;
1800  if (Token.is(MIToken::exclaim)) {
1801  if (parseMDNode(Node))
1802  return true;
1803  } else if (Token.is(MIToken::md_diexpr)) {
1804  if (parseDIExpression(Node))
1805  return true;
1806  }
1807  Dest = MachineOperand::CreateMetadata(Node);
1808  return false;
1809 }
1810 
1811 bool MIParser::parseCFIOffset(int &Offset) {
1812  if (Token.isNot(MIToken::IntegerLiteral))
1813  return error("expected a cfi offset");
1814  if (Token.integerValue().getMinSignedBits() > 32)
1815  return error("expected a 32 bit integer (the cfi offset is too large)");
1816  Offset = (int)Token.integerValue().getExtValue();
1817  lex();
1818  return false;
1819 }
1820 
1821 bool MIParser::parseCFIRegister(unsigned &Reg) {
1822  if (Token.isNot(MIToken::NamedRegister))
1823  return error("expected a cfi register");
1824  unsigned LLVMReg;
1825  if (parseNamedRegister(LLVMReg))
1826  return true;
1827  const auto *TRI = MF.getSubtarget().getRegisterInfo();
1828  assert(TRI && "Expected target register info");
1829  int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
1830  if (DwarfReg < 0)
1831  return error("invalid DWARF register");
1832  Reg = (unsigned)DwarfReg;
1833  lex();
1834  return false;
1835 }
1836 
1837 bool MIParser::parseCFIEscapeValues(std::string &Values) {
1838  do {
1839  if (Token.isNot(MIToken::HexLiteral))
1840  return error("expected a hexadecimal literal");
1841  unsigned Value;
1842  if (getUnsigned(Value))
1843  return true;
1844  if (Value > UINT8_MAX)
1845  return error("expected a 8-bit integer (too large)");
1846  Values.push_back(static_cast<uint8_t>(Value));
1847  lex();
1848  } while (consumeIfPresent(MIToken::comma));
1849  return false;
1850 }
1851 
1852 bool MIParser::parseCFIOperand(MachineOperand &Dest) {
1853  auto Kind = Token.kind();
1854  lex();
1855  int Offset;
1856  unsigned Reg;
1857  unsigned CFIIndex;
1858  switch (Kind) {
1860  if (parseCFIRegister(Reg))
1861  return true;
1862  CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
1863  break;
1865  if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1866  parseCFIOffset(Offset))
1867  return true;
1868  CFIIndex =
1869  MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
1870  break;
1872  if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1873  parseCFIOffset(Offset))
1874  return true;
1875  CFIIndex = MF.addFrameInst(
1876  MCCFIInstruction::createRelOffset(nullptr, Reg, Offset));
1877  break;
1879  if (parseCFIRegister(Reg))
1880  return true;
1881  CFIIndex =
1883  break;
1885  if (parseCFIOffset(Offset))
1886  return true;
1887  // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
1888  CFIIndex = MF.addFrameInst(
1889  MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
1890  break;
1892  if (parseCFIOffset(Offset))
1893  return true;
1894  CFIIndex = MF.addFrameInst(
1895  MCCFIInstruction::createAdjustCfaOffset(nullptr, Offset));
1896  break;
1898  if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1899  parseCFIOffset(Offset))
1900  return true;
1901  // NB: MCCFIInstruction::createDefCfa negates the offset.
1902  CFIIndex =
1903  MF.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
1904  break;
1907  break;
1909  if (parseCFIRegister(Reg))
1910  return true;
1911  CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, Reg));
1912  break;
1915  break;
1917  if (parseCFIRegister(Reg))
1918  return true;
1919  CFIIndex = MF.addFrameInst(MCCFIInstruction::createUndefined(nullptr, Reg));
1920  break;
1921  case MIToken::kw_cfi_register: {
1922  unsigned Reg2;
1923  if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1924  parseCFIRegister(Reg2))
1925  return true;
1926 
1927  CFIIndex =
1928  MF.addFrameInst(MCCFIInstruction::createRegister(nullptr, Reg, Reg2));
1929  break;
1930  }
1932  CFIIndex = MF.addFrameInst(MCCFIInstruction::createWindowSave(nullptr));
1933  break;
1936  break;
1937  case MIToken::kw_cfi_escape: {
1938  std::string Values;
1939  if (parseCFIEscapeValues(Values))
1940  return true;
1941  CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(nullptr, Values));
1942  break;
1943  }
1944  default:
1945  // TODO: Parse the other CFI operands.
1946  llvm_unreachable("The current token should be a cfi operand");
1947  }
1948  Dest = MachineOperand::CreateCFIIndex(CFIIndex);
1949  return false;
1950 }
1951 
1952 bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
1953  switch (Token.kind()) {
1954  case MIToken::NamedIRBlock: {
1955  BB = dyn_cast_or_null<BasicBlock>(
1956  F.getValueSymbolTable()->lookup(Token.stringValue()));
1957  if (!BB)
1958  return error(Twine("use of undefined IR block '") + Token.range() + "'");
1959  break;
1960  }
1961  case MIToken::IRBlock: {
1962  unsigned SlotNumber = 0;
1963  if (getUnsigned(SlotNumber))
1964  return true;
1965  BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
1966  if (!BB)
1967  return error(Twine("use of undefined IR block '%ir-block.") +
1968  Twine(SlotNumber) + "'");
1969  break;
1970  }
1971  default:
1972  llvm_unreachable("The current token should be an IR block reference");
1973  }
1974  return false;
1975 }
1976 
1977 bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
1978  assert(Token.is(MIToken::kw_blockaddress));
1979  lex();
1980  if (expectAndConsume(MIToken::lparen))
1981  return true;
1982  if (Token.isNot(MIToken::GlobalValue) &&
1983  Token.isNot(MIToken::NamedGlobalValue))
1984  return error("expected a global value");
1985  GlobalValue *GV = nullptr;
1986  if (parseGlobalValue(GV))
1987  return true;
1988  auto *F = dyn_cast<Function>(GV);
1989  if (!F)
1990  return error("expected an IR function reference");
1991  lex();
1992  if (expectAndConsume(MIToken::comma))
1993  return true;
1994  BasicBlock *BB = nullptr;
1995  if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
1996  return error("expected an IR block reference");
1997  if (parseIRBlock(BB, *F))
1998  return true;
1999  lex();
2000  if (expectAndConsume(MIToken::rparen))
2001  return true;
2002  Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
2003  if (parseOperandsOffset(Dest))
2004  return true;
2005  return false;
2006 }
2007 
2008 bool MIParser::parseIntrinsicOperand(MachineOperand &Dest) {
2009  assert(Token.is(MIToken::kw_intrinsic));
2010  lex();
2011  if (expectAndConsume(MIToken::lparen))
2012  return error("expected syntax intrinsic(@llvm.whatever)");
2013 
2014  if (Token.isNot(MIToken::NamedGlobalValue))
2015  return error("expected syntax intrinsic(@llvm.whatever)");
2016 
2017  std::string Name = Token.stringValue();
2018  lex();
2019 
2020  if (expectAndConsume(MIToken::rparen))
2021  return error("expected ')' to terminate intrinsic name");
2022 
2023  // Find out what intrinsic we're dealing with, first try the global namespace
2024  // and then the target's private intrinsics if that fails.
2027  if (ID == Intrinsic::not_intrinsic && TII)
2028  ID = static_cast<Intrinsic::ID>(TII->lookupName(Name));
2029 
2030  if (ID == Intrinsic::not_intrinsic)
2031  return error("unknown intrinsic name");
2033 
2034  return false;
2035 }
2036 
2037 bool MIParser::parsePredicateOperand(MachineOperand &Dest) {
2038  assert(Token.is(MIToken::kw_intpred) || Token.is(MIToken::kw_floatpred));
2039  bool IsFloat = Token.is(MIToken::kw_floatpred);
2040  lex();
2041 
2042  if (expectAndConsume(MIToken::lparen))
2043  return error("expected syntax intpred(whatever) or floatpred(whatever");
2044 
2045  if (Token.isNot(MIToken::Identifier))
2046  return error("whatever");
2047 
2048  CmpInst::Predicate Pred;
2049  if (IsFloat) {
2050  Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2051  .Case("false", CmpInst::FCMP_FALSE)
2052  .Case("oeq", CmpInst::FCMP_OEQ)
2053  .Case("ogt", CmpInst::FCMP_OGT)
2054  .Case("oge", CmpInst::FCMP_OGE)
2055  .Case("olt", CmpInst::FCMP_OLT)
2056  .Case("ole", CmpInst::FCMP_OLE)
2057  .Case("one", CmpInst::FCMP_ONE)
2058  .Case("ord", CmpInst::FCMP_ORD)
2059  .Case("uno", CmpInst::FCMP_UNO)
2060  .Case("ueq", CmpInst::FCMP_UEQ)
2061  .Case("ugt", CmpInst::FCMP_UGT)
2062  .Case("uge", CmpInst::FCMP_UGE)
2063  .Case("ult", CmpInst::FCMP_ULT)
2064  .Case("ule", CmpInst::FCMP_ULE)
2065  .Case("une", CmpInst::FCMP_UNE)
2066  .Case("true", CmpInst::FCMP_TRUE)
2068  if (!CmpInst::isFPPredicate(Pred))
2069  return error("invalid floating-point predicate");
2070  } else {
2071  Pred = StringSwitch<CmpInst::Predicate>(Token.stringValue())
2072  .Case("eq", CmpInst::ICMP_EQ)
2073  .Case("ne", CmpInst::ICMP_NE)
2074  .Case("sgt", CmpInst::ICMP_SGT)
2075  .Case("sge", CmpInst::ICMP_SGE)
2076  .Case("slt", CmpInst::ICMP_SLT)
2077  .Case("sle", CmpInst::ICMP_SLE)
2078  .Case("ugt", CmpInst::ICMP_UGT)
2079  .Case("uge", CmpInst::ICMP_UGE)
2080  .Case("ult", CmpInst::ICMP_ULT)
2081  .Case("ule", CmpInst::ICMP_ULE)
2083  if (!CmpInst::isIntPredicate(Pred))
2084  return error("invalid integer predicate");
2085  }
2086 
2087  lex();
2088  Dest = MachineOperand::CreatePredicate(Pred);
2089  if (expectAndConsume(MIToken::rparen))
2090  return error("predicate should be terminated by ')'.");
2091 
2092  return false;
2093 }
2094 
2095 bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
2096  assert(Token.is(MIToken::kw_target_index));
2097  lex();
2098  if (expectAndConsume(MIToken::lparen))
2099  return true;
2100  if (Token.isNot(MIToken::Identifier))
2101  return error("expected the name of the target index");
2102  int Index = 0;
2103  if (getTargetIndex(Token.stringValue(), Index))
2104  return error("use of undefined target index '" + Token.stringValue() + "'");
2105  lex();
2106  if (expectAndConsume(MIToken::rparen))
2107  return true;
2108  Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
2109  if (parseOperandsOffset(Dest))
2110  return true;
2111  return false;
2112 }
2113 
2114 bool MIParser::parseCustomRegisterMaskOperand(MachineOperand &Dest) {
2115  assert(Token.stringValue() == "CustomRegMask" && "Expected a custom RegMask");
2116  lex();
2117  if (expectAndConsume(MIToken::lparen))
2118  return true;
2119 
2121  while (true) {
2122  if (Token.isNot(MIToken::NamedRegister))
2123  return error("expected a named register");
2124  unsigned Reg;
2125  if (parseNamedRegister(Reg))
2126  return true;
2127  lex();
2128  Mask[Reg / 32] |= 1U << (Reg % 32);
2129  // TODO: Report an error if the same register is used more than once.
2130  if (Token.isNot(MIToken::comma))
2131  break;
2132  lex();
2133  }
2134 
2135  if (expectAndConsume(MIToken::rparen))
2136  return true;
2137  Dest = MachineOperand::CreateRegMask(Mask);
2138  return false;
2139 }
2140 
2141 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
2142  assert(Token.is(MIToken::kw_liveout));
2144  lex();
2145  if (expectAndConsume(MIToken::lparen))
2146  return true;
2147  while (true) {
2148  if (Token.isNot(MIToken::NamedRegister))
2149  return error("expected a named register");
2150  unsigned Reg;
2151  if (parseNamedRegister(Reg))
2152  return true;
2153  lex();
2154  Mask[Reg / 32] |= 1U << (Reg % 32);
2155  // TODO: Report an error if the same register is used more than once.
2156  if (Token.isNot(MIToken::comma))
2157  break;
2158  lex();
2159  }
2160  if (expectAndConsume(MIToken::rparen))
2161  return true;
2162  Dest = MachineOperand::CreateRegLiveOut(Mask);
2163  return false;
2164 }
2165 
2166 bool MIParser::parseMachineOperand(MachineOperand &Dest,
2167  Optional<unsigned> &TiedDefIdx) {
2168  switch (Token.kind()) {
2169  case MIToken::kw_implicit:
2171  case MIToken::kw_def:
2172  case MIToken::kw_dead:
2173  case MIToken::kw_killed:
2174  case MIToken::kw_undef:
2175  case MIToken::kw_internal:
2177  case MIToken::kw_debug_use:
2178  case MIToken::kw_renamable:
2179  case MIToken::underscore:
2183  return parseRegisterOperand(Dest, TiedDefIdx);
2185  return parseImmediateOperand(Dest);
2186  case MIToken::kw_half:
2187  case MIToken::kw_float:
2188  case MIToken::kw_double:
2189  case MIToken::kw_x86_fp80:
2190  case MIToken::kw_fp128:
2191  case MIToken::kw_ppc_fp128:
2192  return parseFPImmediateOperand(Dest);
2194  return parseMBBOperand(Dest);
2195  case MIToken::StackObject:
2196  return parseStackObjectOperand(Dest);
2198  return parseFixedStackObjectOperand(Dest);
2199  case MIToken::GlobalValue:
2201  return parseGlobalAddressOperand(Dest);
2203  return parseConstantPoolIndexOperand(Dest);
2205  return parseJumpTableIndexOperand(Dest);
2207  return parseExternalSymbolOperand(Dest);
2208  case MIToken::MCSymbol:
2209  return parseMCSymbolOperand(Dest);
2211  return parseSubRegisterIndexOperand(Dest);
2212  case MIToken::md_diexpr:
2213  case MIToken::exclaim:
2214  return parseMetadataOperand(Dest);
2230  return parseCFIOperand(Dest);
2232  return parseBlockAddressOperand(Dest);
2233  case MIToken::kw_intrinsic:
2234  return parseIntrinsicOperand(Dest);
2236  return parseTargetIndexOperand(Dest);
2237  case MIToken::kw_liveout:
2238  return parseLiveoutRegisterMaskOperand(Dest);
2239  case MIToken::kw_floatpred:
2240  case MIToken::kw_intpred:
2241  return parsePredicateOperand(Dest);
2242  case MIToken::Error:
2243  return true;
2244  case MIToken::Identifier:
2245  if (const auto *RegMask = getRegMask(Token.stringValue())) {
2246  Dest = MachineOperand::CreateRegMask(RegMask);
2247  lex();
2248  break;
2249  } else if (Token.stringValue() == "CustomRegMask") {
2250  return parseCustomRegisterMaskOperand(Dest);
2251  } else
2252  return parseTypedImmediateOperand(Dest);
2253  default:
2254  // FIXME: Parse the MCSymbol machine operand.
2255  return error("expected a machine operand");
2256  }
2257  return false;
2258 }
2259 
2260 bool MIParser::parseMachineOperandAndTargetFlags(
2261  MachineOperand &Dest, Optional<unsigned> &TiedDefIdx) {
2262  unsigned TF = 0;
2263  bool HasTargetFlags = false;
2264  if (Token.is(MIToken::kw_target_flags)) {
2265  HasTargetFlags = true;
2266  lex();
2267  if (expectAndConsume(MIToken::lparen))
2268  return true;
2269  if (Token.isNot(MIToken::Identifier))
2270  return error("expected the name of the target flag");
2271  if (getDirectTargetFlag(Token.stringValue(), TF)) {
2272  if (getBitmaskTargetFlag(Token.stringValue(), TF))
2273  return error("use of undefined target flag '" + Token.stringValue() +
2274  "'");
2275  }
2276  lex();
2277  while (Token.is(MIToken::comma)) {
2278  lex();
2279  if (Token.isNot(MIToken::Identifier))
2280  return error("expected the name of the target flag");
2281  unsigned BitFlag = 0;
2282  if (getBitmaskTargetFlag(Token.stringValue(), BitFlag))
2283  return error("use of undefined target flag '" + Token.stringValue() +
2284  "'");
2285  // TODO: Report an error when using a duplicate bit target flag.
2286  TF |= BitFlag;
2287  lex();
2288  }
2289  if (expectAndConsume(MIToken::rparen))
2290  return true;
2291  }
2292  auto Loc = Token.location();
2293  if (parseMachineOperand(Dest, TiedDefIdx))
2294  return true;
2295  if (!HasTargetFlags)
2296  return false;
2297  if (Dest.isReg())
2298  return error(Loc, "register operands can't have target flags");
2299  Dest.setTargetFlags(TF);
2300  return false;
2301 }
2302 
2303 bool MIParser::parseOffset(int64_t &Offset) {
2304  if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
2305  return false;
2306  StringRef Sign = Token.range();
2307  bool IsNegative = Token.is(MIToken::minus);
2308  lex();
2309  if (Token.isNot(MIToken::IntegerLiteral))
2310  return error("expected an integer literal after '" + Sign + "'");
2311  if (Token.integerValue().getMinSignedBits() > 64)
2312  return error("expected 64-bit integer (too large)");
2313  Offset = Token.integerValue().getExtValue();
2314  if (IsNegative)
2315  Offset = -Offset;
2316  lex();
2317  return false;
2318 }
2319 
2320 bool MIParser::parseAlignment(unsigned &Alignment) {
2321  assert(Token.is(MIToken::kw_align));
2322  lex();
2323  if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
2324  return error("expected an integer literal after 'align'");
2325  if (getUnsigned(Alignment))
2326  return true;
2327  lex();
2328  return false;
2329 }
2330 
2331 bool MIParser::parseAddrspace(unsigned &Addrspace) {
2332  assert(Token.is(MIToken::kw_addrspace));
2333  lex();
2334  if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
2335  return error("expected an integer literal after 'addrspace'");
2336  if (getUnsigned(Addrspace))
2337  return true;
2338  lex();
2339  return false;
2340 }
2341 
2342 bool MIParser::parseOperandsOffset(MachineOperand &Op) {
2343  int64_t Offset = 0;
2344  if (parseOffset(Offset))
2345  return true;
2346  Op.setOffset(Offset);
2347  return false;
2348 }
2349 
2350 bool MIParser::parseIRValue(const Value *&V) {
2351  switch (Token.kind()) {
2352  case MIToken::NamedIRValue: {
2353  V = MF.getFunction().getValueSymbolTable()->lookup(Token.stringValue());
2354  break;
2355  }
2356  case MIToken::IRValue: {
2357  unsigned SlotNumber = 0;
2358  if (getUnsigned(SlotNumber))
2359  return true;
2360  V = getIRValue(SlotNumber);
2361  break;
2362  }
2364  case MIToken::GlobalValue: {
2365  GlobalValue *GV = nullptr;
2366  if (parseGlobalValue(GV))
2367  return true;
2368  V = GV;
2369  break;
2370  }
2371  case MIToken::QuotedIRValue: {
2372  const Constant *C = nullptr;
2373  if (parseIRConstant(Token.location(), Token.stringValue(), C))
2374  return true;
2375  V = C;
2376  break;
2377  }
2378  default:
2379  llvm_unreachable("The current token should be an IR block reference");
2380  }
2381  if (!V)
2382  return error(Twine("use of undefined IR value '") + Token.range() + "'");
2383  return false;
2384 }
2385 
2386 bool MIParser::getUint64(uint64_t &Result) {
2387  if (Token.hasIntegerValue()) {
2388  if (Token.integerValue().getActiveBits() > 64)
2389  return error("expected 64-bit integer (too large)");
2390  Result = Token.integerValue().getZExtValue();
2391  return false;
2392  }
2393  if (Token.is(MIToken::HexLiteral)) {
2394  APInt A;
2395  if (getHexUint(A))
2396  return true;
2397  if (A.getBitWidth() > 64)
2398  return error("expected 64-bit integer (too large)");
2399  Result = A.getZExtValue();
2400  return false;
2401  }
2402  return true;
2403 }
2404 
2405 bool MIParser::getHexUint(APInt &Result) {
2406  assert(Token.is(MIToken::HexLiteral));
2407  StringRef S = Token.range();
2408  assert(S[0] == '0' && tolower(S[1]) == 'x');
2409  // This could be a floating point literal with a special prefix.
2410  if (!isxdigit(S[2]))
2411  return true;
2412  StringRef V = S.substr(2);
2413  APInt A(V.size()*4, V, 16);
2414 
2415  // If A is 0, then A.getActiveBits() is 0. This isn't a valid bitwidth. Make
2416  // sure it isn't the case before constructing result.
2417  unsigned NumBits = (A == 0) ? 32 : A.getActiveBits();
2418  Result = APInt(NumBits, ArrayRef<uint64_t>(A.getRawData(), A.getNumWords()));
2419  return false;
2420 }
2421 
2422 bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags &Flags) {
2423  const auto OldFlags = Flags;
2424  switch (Token.kind()) {
2425  case MIToken::kw_volatile:
2427  break;
2430  break;
2433  break;
2434  case MIToken::kw_invariant:
2436  break;
2437  case MIToken::StringConstant: {
2439  if (getMMOTargetFlag(Token.stringValue(), TF))
2440  return error("use of undefined target MMO flag '" + Token.stringValue() +
2441  "'");
2442  Flags |= TF;
2443  break;
2444  }
2445  default:
2446  llvm_unreachable("The current token should be a memory operand flag");
2447  }
2448  if (OldFlags == Flags)
2449  // We know that the same flag is specified more than once when the flags
2450  // weren't modified.
2451  return error("duplicate '" + Token.stringValue() + "' memory operand flag");
2452  lex();
2453  return false;
2454 }
2455 
2456 bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
2457  switch (Token.kind()) {
2458  case MIToken::kw_stack:
2459  PSV = MF.getPSVManager().getStack();
2460  break;
2461  case MIToken::kw_got:
2462  PSV = MF.getPSVManager().getGOT();
2463  break;
2465  PSV = MF.getPSVManager().getJumpTable();
2466  break;
2468  PSV = MF.getPSVManager().getConstantPool();
2469  break;
2471  int FI;
2472  if (parseFixedStackFrameIndex(FI))
2473  return true;
2474  PSV = MF.getPSVManager().getFixedStack(FI);
2475  // The token was already consumed, so use return here instead of break.
2476  return false;
2477  }
2478  case MIToken::StackObject: {
2479  int FI;
2480  if (parseStackFrameIndex(FI))
2481  return true;
2482  PSV = MF.getPSVManager().getFixedStack(FI);
2483  // The token was already consumed, so use return here instead of break.
2484  return false;
2485  }
2487  lex();
2488  switch (Token.kind()) {
2489  case MIToken::GlobalValue:
2491  GlobalValue *GV = nullptr;
2492  if (parseGlobalValue(GV))
2493  return true;
2495  break;
2496  }
2499  MF.createExternalSymbolName(Token.stringValue()));
2500  break;
2501  default:
2502  return error(
2503  "expected a global value or an external symbol after 'call-entry'");
2504  }
2505  break;
2506  default:
2507  llvm_unreachable("The current token should be pseudo source value");
2508  }
2509  lex();
2510  return false;
2511 }
2512 
2513 bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
2514  if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
2515  Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
2516  Token.is(MIToken::FixedStackObject) || Token.is(MIToken::StackObject) ||
2517  Token.is(MIToken::kw_call_entry)) {
2518  const PseudoSourceValue *PSV = nullptr;
2519  if (parseMemoryPseudoSourceValue(PSV))
2520  return true;
2521  int64_t Offset = 0;
2522  if (parseOffset(Offset))
2523  return true;
2524  Dest = MachinePointerInfo(PSV, Offset);
2525  return false;
2526  }
2527  if (Token.isNot(MIToken::NamedIRValue) && Token.isNot(MIToken::IRValue) &&
2528  Token.isNot(MIToken::GlobalValue) &&
2529  Token.isNot(MIToken::NamedGlobalValue) &&
2530  Token.isNot(MIToken::QuotedIRValue))
2531  return error("expected an IR value reference");
2532  const Value *V = nullptr;
2533  if (parseIRValue(V))
2534  return true;
2535  if (!V->getType()->isPointerTy())
2536  return error("expected a pointer IR value");
2537  lex();
2538  int64_t Offset = 0;
2539  if (parseOffset(Offset))
2540  return true;
2541  Dest = MachinePointerInfo(V, Offset);
2542  return false;
2543 }
2544 
2545 bool MIParser::parseOptionalScope(LLVMContext &Context,
2546  SyncScope::ID &SSID) {
2547  SSID = SyncScope::System;
2548  if (Token.is(MIToken::Identifier) && Token.stringValue() == "syncscope") {
2549  lex();
2550  if (expectAndConsume(MIToken::lparen))
2551  return error("expected '(' in syncscope");
2552 
2553  std::string SSN;
2554  if (parseStringConstant(SSN))
2555  return true;
2556 
2557  SSID = Context.getOrInsertSyncScopeID(SSN);
2558  if (expectAndConsume(MIToken::rparen))
2559  return error("expected ')' in syncscope");
2560  }
2561 
2562  return false;
2563 }
2564 
2565 bool MIParser::parseOptionalAtomicOrdering(AtomicOrdering &Order) {
2566  Order = AtomicOrdering::NotAtomic;
2567  if (Token.isNot(MIToken::Identifier))
2568  return false;
2569 
2570  Order = StringSwitch<AtomicOrdering>(Token.stringValue())
2571  .Case("unordered", AtomicOrdering::Unordered)
2572  .Case("monotonic", AtomicOrdering::Monotonic)
2573  .Case("acquire", AtomicOrdering::Acquire)
2574  .Case("release", AtomicOrdering::Release)
2578 
2579  if (Order != AtomicOrdering::NotAtomic) {
2580  lex();
2581  return false;
2582  }
2583 
2584  return error("expected an atomic scope, ordering or a size specification");
2585 }
2586 
2587 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
2588  if (expectAndConsume(MIToken::lparen))
2589  return true;
2591  while (Token.isMemoryOperandFlag()) {
2592  if (parseMemoryOperandFlag(Flags))
2593  return true;
2594  }
2595  if (Token.isNot(MIToken::Identifier) ||
2596  (Token.stringValue() != "load" && Token.stringValue() != "store"))
2597  return error("expected 'load' or 'store' memory operation");
2598  if (Token.stringValue() == "load")
2599  Flags |= MachineMemOperand::MOLoad;
2600  else
2601  Flags |= MachineMemOperand::MOStore;
2602  lex();
2603 
2604  // Optional 'store' for operands that both load and store.
2605  if (Token.is(MIToken::Identifier) && Token.stringValue() == "store") {
2606  Flags |= MachineMemOperand::MOStore;
2607  lex();
2608  }
2609 
2610  // Optional synchronization scope.
2611  SyncScope::ID SSID;
2612  if (parseOptionalScope(MF.getFunction().getContext(), SSID))
2613  return true;
2614 
2615  // Up to two atomic orderings (cmpxchg provides guarantees on failure).
2616  AtomicOrdering Order, FailureOrder;
2617  if (parseOptionalAtomicOrdering(Order))
2618  return true;
2619 
2620  if (parseOptionalAtomicOrdering(FailureOrder))
2621  return true;
2622 
2623  if (Token.isNot(MIToken::IntegerLiteral) &&
2624  Token.isNot(MIToken::kw_unknown_size))
2625  return error("expected the size integer literal or 'unknown-size' after "
2626  "memory operation");
2627  uint64_t Size;
2628  if (Token.is(MIToken::IntegerLiteral)) {
2629  if (getUint64(Size))
2630  return true;
2631  } else if (Token.is(MIToken::kw_unknown_size)) {
2633  }
2634  lex();
2635 
2637  if (Token.is(MIToken::Identifier)) {
2638  const char *Word =
2639  ((Flags & MachineMemOperand::MOLoad) &&
2640  (Flags & MachineMemOperand::MOStore))
2641  ? "on"
2642  : Flags & MachineMemOperand::MOLoad ? "from" : "into";
2643  if (Token.stringValue() != Word)
2644  return error(Twine("expected '") + Word + "'");
2645  lex();
2646 
2647  if (parseMachinePointerInfo(Ptr))
2648  return true;
2649  }
2650  unsigned BaseAlignment = (Size != MemoryLocation::UnknownSize ? Size : 1);
2651  AAMDNodes AAInfo;
2652  MDNode *Range = nullptr;
2653  while (consumeIfPresent(MIToken::comma)) {
2654  switch (Token.kind()) {
2655  case MIToken::kw_align:
2656  if (parseAlignment(BaseAlignment))
2657  return true;
2658  break;
2659  case MIToken::kw_addrspace:
2660  if (parseAddrspace(Ptr.AddrSpace))
2661  return true;
2662  break;
2663  case MIToken::md_tbaa:
2664  lex();
2665  if (parseMDNode(AAInfo.TBAA))
2666  return true;
2667  break;
2669  lex();
2670  if (parseMDNode(AAInfo.Scope))
2671  return true;
2672  break;
2673  case MIToken::md_noalias:
2674  lex();
2675  if (parseMDNode(AAInfo.NoAlias))
2676  return true;
2677  break;
2678  case MIToken::md_range:
2679  lex();
2680  if (parseMDNode(Range))
2681  return true;
2682  break;
2683  // TODO: Report an error on duplicate metadata nodes.
2684  default:
2685  return error("expected 'align' or '!tbaa' or '!alias.scope' or "
2686  "'!noalias' or '!range'");
2687  }
2688  }
2689  if (expectAndConsume(MIToken::rparen))
2690  return true;
2691  Dest = MF.getMachineMemOperand(Ptr, Flags, Size, BaseAlignment, AAInfo, Range,
2692  SSID, Order, FailureOrder);
2693  return false;
2694 }
2695 
2696 bool MIParser::parsePreOrPostInstrSymbol(MCSymbol *&Symbol) {
2697  assert((Token.is(MIToken::kw_pre_instr_symbol) ||
2698  Token.is(MIToken::kw_post_instr_symbol)) &&
2699  "Invalid token for a pre- post-instruction symbol!");
2700  lex();
2701  if (Token.isNot(MIToken::MCSymbol))
2702  return error("expected a symbol after 'pre-instr-symbol'");
2703  Symbol = getOrCreateMCSymbol(Token.stringValue());
2704  lex();
2705  if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
2706  Token.is(MIToken::lbrace))
2707  return false;
2708  if (Token.isNot(MIToken::comma))
2709  return error("expected ',' before the next machine operand");
2710  lex();
2711  return false;
2712 }
2713 
2714 void MIParser::initNames2InstrOpCodes() {
2715  if (!Names2InstrOpCodes.empty())
2716  return;
2717  const auto *TII = MF.getSubtarget().getInstrInfo();
2718  assert(TII && "Expected target instruction info");
2719  for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
2720  Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
2721 }
2722 
2723 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
2724  initNames2InstrOpCodes();
2725  auto InstrInfo = Names2InstrOpCodes.find(InstrName);
2726  if (InstrInfo == Names2InstrOpCodes.end())
2727  return true;
2728  OpCode = InstrInfo->getValue();
2729  return false;
2730 }
2731 
2732 void MIParser::initNames2Regs() {
2733  if (!Names2Regs.empty())
2734  return;
2735  // The '%noreg' register is the register 0.
2736  Names2Regs.insert(std::make_pair("noreg", 0));
2737  const auto *TRI = MF.getSubtarget().getRegisterInfo();
2738  assert(TRI && "Expected target register info");
2739  for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
2740  bool WasInserted =
2741  Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
2742  .second;
2743  (void)WasInserted;
2744  assert(WasInserted && "Expected registers to be unique case-insensitively");
2745  }
2746 }
2747 
2748 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
2749  initNames2Regs();
2750  auto RegInfo = Names2Regs.find(RegName);
2751  if (RegInfo == Names2Regs.end())
2752  return true;
2753  Reg = RegInfo->getValue();
2754  return false;
2755 }
2756 
2757 void MIParser::initNames2RegMasks() {
2758  if (!Names2RegMasks.empty())
2759  return;
2760  const auto *TRI = MF.getSubtarget().getRegisterInfo();
2761  assert(TRI && "Expected target register info");
2762  ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
2763  ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
2764  assert(RegMasks.size() == RegMaskNames.size());
2765  for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
2766  Names2RegMasks.insert(
2767  std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
2768 }
2769 
2770 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
2771  initNames2RegMasks();
2772  auto RegMaskInfo = Names2RegMasks.find(Identifier);
2773  if (RegMaskInfo == Names2RegMasks.end())
2774  return nullptr;
2775  return RegMaskInfo->getValue();
2776 }
2777 
2778 void MIParser::initNames2SubRegIndices() {
2779  if (!Names2SubRegIndices.empty())
2780  return;
2782  for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
2783  Names2SubRegIndices.insert(
2784  std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
2785 }
2786 
2787 unsigned MIParser::getSubRegIndex(StringRef Name) {
2788  initNames2SubRegIndices();
2789  auto SubRegInfo = Names2SubRegIndices.find(Name);
2790  if (SubRegInfo == Names2SubRegIndices.end())
2791  return 0;
2792  return SubRegInfo->getValue();
2793 }
2794 
2796  const Function &F,
2797  DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
2798  ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
2799  MST.incorporateFunction(F);
2800  for (auto &BB : F) {
2801  if (BB.hasName())
2802  continue;
2803  int Slot = MST.getLocalSlot(&BB);
2804  if (Slot == -1)
2805  continue;
2806  Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
2807  }
2808 }
2809 
2811  unsigned Slot,
2812  const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
2813  auto BlockInfo = Slots2BasicBlocks.find(Slot);
2814  if (BlockInfo == Slots2BasicBlocks.end())
2815  return nullptr;
2816  return BlockInfo->second;
2817 }
2818 
2819 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
2820  if (Slots2BasicBlocks.empty())
2821  initSlots2BasicBlocks(MF.getFunction(), Slots2BasicBlocks);
2822  return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
2823 }
2824 
2825 const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
2826  if (&F == &MF.getFunction())
2827  return getIRBlock(Slot);
2828  DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
2829  initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
2830  return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
2831 }
2832 
2833 static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST,
2834  DenseMap<unsigned, const Value *> &Slots2Values) {
2835  int Slot = MST.getLocalSlot(V);
2836  if (Slot == -1)
2837  return;
2838  Slots2Values.insert(std::make_pair(unsigned(Slot), V));
2839 }
2840 
2841 /// Creates the mapping from slot numbers to function's unnamed IR values.
2842 static void initSlots2Values(const Function &F,
2843  DenseMap<unsigned, const Value *> &Slots2Values) {
2844  ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
2845  MST.incorporateFunction(F);
2846  for (const auto &Arg : F.args())
2847  mapValueToSlot(&Arg, MST, Slots2Values);
2848  for (const auto &BB : F) {
2849  mapValueToSlot(&BB, MST, Slots2Values);
2850  for (const auto &I : BB)
2851  mapValueToSlot(&I, MST, Slots2Values);
2852  }
2853 }
2854 
2855 const Value *MIParser::getIRValue(unsigned Slot) {
2856  if (Slots2Values.empty())
2857  initSlots2Values(MF.getFunction(), Slots2Values);
2858  auto ValueInfo = Slots2Values.find(Slot);
2859  if (ValueInfo == Slots2Values.end())
2860  return nullptr;
2861  return ValueInfo->second;
2862 }
2863 
2864 void MIParser::initNames2TargetIndices() {
2865  if (!Names2TargetIndices.empty())
2866  return;
2867  const auto *TII = MF.getSubtarget().getInstrInfo();
2868  assert(TII && "Expected target instruction info");
2869  auto Indices = TII->getSerializableTargetIndices();
2870  for (const auto &I : Indices)
2871  Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
2872 }
2873 
2874 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
2875  initNames2TargetIndices();
2876  auto IndexInfo = Names2TargetIndices.find(Name);
2877  if (IndexInfo == Names2TargetIndices.end())
2878  return true;
2879  Index = IndexInfo->second;
2880  return false;
2881 }
2882 
2883 void MIParser::initNames2DirectTargetFlags() {
2884  if (!Names2DirectTargetFlags.empty())
2885  return;
2886  const auto *TII = MF.getSubtarget().getInstrInfo();
2887  assert(TII && "Expected target instruction info");
2889  for (const auto &I : Flags)
2890  Names2DirectTargetFlags.insert(
2891  std::make_pair(StringRef(I.second), I.first));
2892 }
2893 
2894 bool MIParser::getDirectTargetFlag(StringRef Name, unsigned &Flag) {
2895  initNames2DirectTargetFlags();
2896  auto FlagInfo = Names2DirectTargetFlags.find(Name);
2897  if (FlagInfo == Names2DirectTargetFlags.end())
2898  return true;
2899  Flag = FlagInfo->second;
2900  return false;
2901 }
2902 
2903 void MIParser::initNames2BitmaskTargetFlags() {
2904  if (!Names2BitmaskTargetFlags.empty())
2905  return;
2906  const auto *TII = MF.getSubtarget().getInstrInfo();
2907  assert(TII && "Expected target instruction info");
2909  for (const auto &I : Flags)
2910  Names2BitmaskTargetFlags.insert(
2911  std::make_pair(StringRef(I.second), I.first));
2912 }
2913 
2914 bool MIParser::getBitmaskTargetFlag(StringRef Name, unsigned &Flag) {
2915  initNames2BitmaskTargetFlags();
2916  auto FlagInfo = Names2BitmaskTargetFlags.find(Name);
2917  if (FlagInfo == Names2BitmaskTargetFlags.end())
2918  return true;
2919  Flag = FlagInfo->second;
2920  return false;
2921 }
2922 
2923 void MIParser::initNames2MMOTargetFlags() {
2924  if (!Names2MMOTargetFlags.empty())
2925  return;
2926  const auto *TII = MF.getSubtarget().getInstrInfo();
2927  assert(TII && "Expected target instruction info");
2928  auto Flags = TII->getSerializableMachineMemOperandTargetFlags();
2929  for (const auto &I : Flags)
2930  Names2MMOTargetFlags.insert(
2931  std::make_pair(StringRef(I.second), I.first));
2932 }
2933 
2934 bool MIParser::getMMOTargetFlag(StringRef Name,
2935  MachineMemOperand::Flags &Flag) {
2936  initNames2MMOTargetFlags();
2937  auto FlagInfo = Names2MMOTargetFlags.find(Name);
2938  if (FlagInfo == Names2MMOTargetFlags.end())
2939  return true;
2940  Flag = FlagInfo->second;
2941  return false;
2942 }
2943 
2944 MCSymbol *MIParser::getOrCreateMCSymbol(StringRef Name) {
2945  // FIXME: Currently we can't recognize temporary or local symbols and call all
2946  // of the appropriate forms to create them. However, this handles basic cases
2947  // well as most of the special aspects are recognized by a prefix on their
2948  // name, and the input names should already be unique. For test cases, keeping
2949  // the symbol name out of the symbol table isn't terribly important.
2950  return MF.getContext().getOrCreateSymbol(Name);
2951 }
2952 
2953 bool MIParser::parseStringConstant(std::string &Result) {
2954  if (Token.isNot(MIToken::StringConstant))
2955  return error("expected string constant");
2956  Result = Token.stringValue();
2957  lex();
2958  return false;
2959 }
2960 
2962  StringRef Src,
2963  SMDiagnostic &Error) {
2964  return MIParser(PFS, Error, Src).parseBasicBlockDefinitions(PFS.MBBSlots);
2965 }
2966 
2968  StringRef Src, SMDiagnostic &Error) {
2969  return MIParser(PFS, Error, Src).parseBasicBlocks();
2970 }
2971 
2973  MachineBasicBlock *&MBB, StringRef Src,
2974  SMDiagnostic &Error) {
2975  return MIParser(PFS, Error, Src).parseStandaloneMBB(MBB);
2976 }
2977 
2979  unsigned &Reg, StringRef Src,
2980  SMDiagnostic &Error) {
2981  return MIParser(PFS, Error, Src).parseStandaloneRegister(Reg);
2982 }
2983 
2985  unsigned &Reg, StringRef Src,
2986  SMDiagnostic &Error) {
2987  return MIParser(PFS, Error, Src).parseStandaloneNamedRegister(Reg);
2988 }
2989 
2991  VRegInfo *&Info, StringRef Src,
2992  SMDiagnostic &Error) {
2993  return MIParser(PFS, Error, Src).parseStandaloneVirtualRegister(Info);
2994 }
2995 
2997  int &FI, StringRef Src,
2998  SMDiagnostic &Error) {
2999  return MIParser(PFS, Error, Src).parseStandaloneStackObject(FI);
3000 }
3001 
3003  MDNode *&Node, StringRef Src, SMDiagnostic &Error) {
3004  return MIParser(PFS, Error, Src).parseStandaloneMDNode(Node);
3005 }
bool isFPPredicate() const
Definition: InstrTypes.h:738
ArrayRef< std::pair< unsigned, const char * > > getSerializableDirectMachineOperandTargetFlags() const override
Return an array that contains the direct target flag values and their names.
uint64_t CallInst * C
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
Definition: MemoryBuffer.h:70
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
bool parseMachineBasicBlockDefinitions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine basic block definitions, and skip the machine instructions.
Definition: MIParser.cpp:2961
static void initSlots2BasicBlocks(const Function &F, DenseMap< unsigned, const BasicBlock *> &Slots2BasicBlocks)
Definition: MIParser.cpp:2795
A common definition of LaneBitmask for use in TableGen and CodeGen.
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1563
static MachineOperand CreateCImm(const ConstantInt *CI)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
DenseMap< unsigned, unsigned > JumpTableSlots
Definition: MIParser.h:63
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:228
LLVMContext & Context
const T & back() const
back - Get the last element.
Definition: ArrayRef.h:158
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition: Metadata.h:661
Atomic ordering constants.
DenseMap< unsigned, unsigned > ConstantPoolSlots
Definition: MIParser.h:62
This class represents lattice values for constants.
Definition: AllocatorList.h:24
MDNode * TBAA
The tag for type-based alias analysis.
Definition: Metadata.h:658
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:148
static MachineOperand CreateMCSymbol(MCSymbol *Sym, unsigned char TargetFlags=0)
void setTargetFlags(unsigned F)
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
static BranchProbability getRaw(uint32_t N)
static MCCFIInstruction createRememberState(MCSymbol *L)
.cfi_remember_state Save all current rules for all registers.
Definition: MCDwarf.h:538
const MCPhysReg * getImplicitUses() const
Return a list of registers that are potentially read by any instance of this machine instruction...
Definition: MCInstrDesc.h:524
static MachineOperand CreateJTI(unsigned Idx, unsigned char TargetFlags=0)
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:164
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int Offset)
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition: MCDwarf.h:488
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
unsigned Reg
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID...
This file contains the declarations for metadata subclasses.
unsigned less or equal
Definition: InstrTypes.h:672
unsigned less than
Definition: InstrTypes.h:671
int getLocalSlot(const Value *V)
Return the slot number of the specified local value.
Definition: AsmWriter.cpp:855
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:652
ArrayRef< std::pair< unsigned, const char * > > getSerializableBitmaskMachineOperandTargetFlags() const override
Return an array that contains the bitmask target flag values and their names.
iterator find(StringRef Key)
Definition: StringMap.h:333
DenseMap< unsigned, int > StackObjectSlots
Definition: MIParser.h:61
LLT getType(unsigned Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register...
1 1 1 0 True if unordered or not equal
Definition: InstrTypes.h:662
#define error(X)
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:1186
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
Definition: DataLayout.h:363
unsigned const TargetRegisterInfo * TRI
A debug info location.
Definition: DebugLoc.h:34
Metadata node.
Definition: Metadata.h:864
F(f)
DenseMap< unsigned, VRegInfo * > VRegInfos
Definition: MIParser.h:58
Manage lifetime of a slot tracker for printing IR.
bool parseMBBReference(PerFunctionMIParsingState &PFS, MachineBasicBlock *&MBB, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:2972
const TargetRegisterClass * RC
Definition: MIParser.h:39
static MCCFIInstruction createDefCfaOffset(MCSymbol *L, int Offset)
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition: MCDwarf.h:475
MachineInstr * CreateMachineInstr(const MCInstrDesc &MCID, const DebugLoc &DL, bool NoImp=false)
CreateMachineInstr - Allocate a new MachineInstr.
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...
static MCCFIInstruction createAdjustCfaOffset(MCSymbol *L, int Adjustment)
.cfi_adjust_cfa_offset Same as .cfi_def_cfa_offset, but Offset is a relative value that is added/subt...
Definition: MCDwarf.h:482
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:128
static MachineOperand CreateIntrinsicID(Intrinsic::ID ID)
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1509
static MachineOperand CreateReg(unsigned 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 MCCFIInstruction createUndefined(MCSymbol *L, unsigned Register)
.cfi_undefined From now on the previous value of Register can&#39;t be restored anymore.
Definition: MCDwarf.h:527
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:221
const char * getRegClassName(const TargetRegisterClass *Class) const
Returns the name of the register class.
1 0 0 1 True if unordered or equal
Definition: InstrTypes.h:657
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...
Definition: MIRPrinter.cpp:503
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition: InstrTypes.h:656
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition: SlotMapping.h:35
A description of a memory reference used in the backend.
amdgpu Simplify well known AMD library false Value Value const Twine & Name
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:967
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
const HexagonInstrInfo * TII
static const BasicBlock * getIRBlockFromSlot(unsigned Slot, const DenseMap< unsigned, const BasicBlock *> &Slots2BasicBlocks)
Definition: MIParser.cpp:2810
VRegInfo & getVRegInfoNamed(StringRef RegName)
Definition: MIParser.cpp:103
union llvm::VRegInfo::@347 D
support::ulittle32_t Word
Definition: IRSymtab.h:51
unsigned SubReg
static constexpr LaneBitmask getAll()
Definition: LaneBitmask.h:84
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:653
const Name2RegBankMap & Names2RegBanks
Definition: MIParser.h:55
The memory access is dereferenceable (i.e., doesn&#39;t trap).
static MachineOperand CreateRegMask(const uint32_t *Mask)
CreateRegMask - Creates a register mask operand referencing Mask.
static MachineOperand CreateRegLiveOut(const uint32_t *Mask)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE R Default(T Value)
Definition: StringSwitch.h:203
LLVM_NODISCARD unsigned addFrameInst(const MCCFIInstruction &Inst)
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, unsigned base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
This file implements a class to represent arbitrary precision integral constant values and operations...
AtomicOrdering
Atomic ordering for LLVM&#39;s memory model.
DenseMap< unsigned, int > FixedStackObjectSlots
Definition: MIParser.h:60
static std::string getRegisterName(const TargetRegisterInfo *TRI, unsigned Reg)
Definition: MIParser.cpp:921
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition: SourceMgr.h:131
#define UINT64_MAX
Definition: DataTypes.h:83
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
PseudoSourceValueManager & getPSVManager() const
virtual unsigned lookupName(const char *Name, unsigned Len) const =0
Look up target intrinsic by name.
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
Definition: Module.cpp:114
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
const char * getSubRegIndexName(unsigned SubIdx) const
Return the human-readable symbolic target-specific name for the specified SubRegIndex.
void setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol)
Set a symbol that will be emitted just after the instruction itself.
virtual const TargetInstrInfo * getInstrInfo() const
static LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
bool parseVirtualRegisterReference(PerFunctionMIParsingState &PFS, VRegInfo *&Info, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:2990
static MachineOperand CreatePredicate(unsigned Pred)
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
const PseudoSourceValue * getFixedStack(int FI)
Return a pseudo source value referencing a fixed stack frame entry, e.g., a spill slot...
Analysis containing CSE Info
Definition: CSEInfo.cpp:21
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
void normalizeSuccProbs()
Normalize probabilities of all successors so that the sum of them becomes one.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
const char * getName(unsigned RegNo) const
Return the human-readable symbolic target-specific name for the specified physical register...
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:118
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:176
unsigned getMainFileID() const
Definition: SourceMgr.h:140
bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
MCContext & getContext() const
The memory access is volatile.
static MCCFIInstruction createSameValue(MCSymbol *L, unsigned Register)
.cfi_same_value Current value of Register is the same as in the previous frame.
Definition: MCDwarf.h:533
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1166
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:43
bool parseStackObjectReference(PerFunctionMIParsingState &PFS, int &FI, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:2996
static MCCFIInstruction createNegateRAState(MCSymbol *L)
.cfi_negate_ra_state AArch64 negate RA state.
Definition: MCDwarf.h:514
const MCPhysReg * getImplicitDefs() const
Return a list of registers that are potentially written by any instance of this machine instruction...
Definition: MCInstrDesc.h:546
void addLiveIn(MCPhysReg PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
unsigned const MachineRegisterInfo * MRI
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
static const char * printImplicitRegisterFlag(const MachineOperand &MO)
Definition: MIParser.cpp:916
static MCCFIInstruction createDefCfa(MCSymbol *L, unsigned Register, int Offset)
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it...
Definition: MCDwarf.h:461
static Intrinsic::ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
Definition: Function.cpp:535
static MachineOperand CreateCPI(unsigned Idx, int Offset, unsigned char TargetFlags=0)
bool hasName() const
Definition: Value.h:251
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
const PseudoSourceValue * getExternalSymbolCallEntry(const char *ES)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
static MCCFIInstruction createDefCfaRegister(MCSymbol *L, unsigned Register)
.cfi_def_cfa_register modifies a rule for computing CFA.
Definition: MCDwarf.h:468
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1434
static MachineOperand CreateFPImm(const ConstantFP *CFP)
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
static MCCFIInstruction createWindowSave(MCSymbol *L)
.cfi_window_save SPARC register window is saved.
Definition: MCDwarf.h:509
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:224
StringMap< VRegInfo * > VRegInfosNamed
Definition: MIParser.h:59
unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition: Dwarf.cpp:152
const MCPhysReg * ImplicitDefs
Definition: MCInstrDesc.h:174
void setType(unsigned VReg, LLT Ty)
Set the low-level type of VReg to Ty.
BumpPtrAllocator Allocator
Definition: MIParser.h:50
static MachineOperand CreateBA(const BlockAddress *BA, int64_t Offset, unsigned char TargetFlags=0)
bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, unsigned &Reg, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:2984
void setFlag(MIFlag Flag)
Set a MI flag.
Definition: MachineInstr.h:300
bool isValid() const
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:646
static MCCFIInstruction createRelOffset(MCSymbol *L, unsigned Register, int Offset)
.cfi_rel_offset Previous value of Register is saved at offset Offset from the current CFA register...
Definition: MCDwarf.h:496
static MachineOperand CreateGA(const GlobalValue *GV, int64_t Offset, unsigned char TargetFlags=0)
static MachineOperand CreateTargetIndex(unsigned Idx, int64_t Offset, unsigned char TargetFlags=0)
static MCCFIInstruction createRestore(MCSymbol *L, unsigned Register)
.cfi_restore says that the rule for Register is now the same as it was at the beginning of the functi...
Definition: MCDwarf.h:521
0 1 1 1 True if ordered (no nans)
Definition: InstrTypes.h:655
The memory access is non-temporal.
llvm::Expected< Value > parse(llvm::StringRef JSON)
Parses the provided JSON source, or returns a ParseError.
Definition: JSON.cpp:511
MachineFunction & MF
Definition: MIParser.h:51
std::vector< GlobalValue * > GlobalValues
Definition: SlotMapping.h:34
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling...
Definition: SourceMgr.h:42
void setOffset(int64_t Offset)
1 1 1 1 Always true (always folded)
Definition: InstrTypes.h:663
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:193
void incorporateFunction(const Function &F)
Incorporate the given function.
Definition: AsmWriter.cpp:841
const SlotMapping & IRSlots
Definition: MIParser.h:53
static MCCFIInstruction createRestoreState(MCSymbol *L)
.cfi_restore_state Restore the previously saved state.
Definition: MCDwarf.h:543
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
This class contains a discriminated union of information about pointers in memory operands...
const char * createExternalSymbolName(StringRef Name)
Allocate a string and populate it with the given external symbol name.
1 1 0 1 True if unordered, less than, or equal
Definition: InstrTypes.h:661
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges=None, ArrayRef< SMFixIt > FixIts=None) const
Return an SMDiagnostic at the specified location with the specified string.
Definition: SourceMgr.cpp:169
signed greater than
Definition: InstrTypes.h:673
bool parseMachineInstructions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine instructions.
Definition: MIParser.cpp:2967
TargetIntrinsicInfo - Interface to description of machine instruction set.
Struct that holds a reference to a particular GUID in a global value summary.
The memory access writes data.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef drop_front(size_t N=1) const
Return a StringRef equal to &#39;this&#39; but with the first N elements dropped.
Definition: StringRef.h:645
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:650
const Name2RegClassMap & Names2RegClasses
Definition: MIParser.h:54
unsigned createIncompleteVirtualRegister(StringRef Name="")
Creates a new virtual register that has no register class, register bank or size assigned yet...
static MachineOperand CreateMetadata(const MDNode *Meta)
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
void setFlags(unsigned flags)
Definition: MachineInstr.h:304
enum llvm::VRegInfo::uint8_t Kind
MachineOperand class - Representation of each machine instruction operand.
1 1 0 0 True if unordered or less than
Definition: InstrTypes.h:660
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Module.h This file contains the declarations for the Module class.
static bool isImplicitOperandIn(const MachineOperand &ImplicitOperand, ArrayRef< ParsedMachineOperand > Operands)
Return true if the parsed machine operands contain a given machine operand.
Definition: MIParser.cpp:928
StringRef getMessage() const
Definition: SourceMgr.h:291
signed less than
Definition: InstrTypes.h:675
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:644
MDNode * NoAlias
The tag specifying the noalias scope.
Definition: Metadata.h:664
uint32_t * allocateRegMask()
Allocate and initialize a register mask with NumRegister bits.
This class implements the register bank concept.
Definition: RegisterBank.h:29
const Function & getFunction() const
Return the LLVM function that this machine code represents.
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:42
ValueSymbolTable * getValueSymbolTable()
getSymbolTable() - Return the symbol table if any, otherwise nullptr.
Definition: Function.h:648
bool isIntPredicate() const
Definition: InstrTypes.h:739
signed less or equal
Definition: InstrTypes.h:676
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:220
Class for arbitrary precision integers.
Definition: APInt.h:70
Special value supplied for machine level alias analysis.
const PseudoSourceValue * getJumpTable()
Return a pseudo source value referencing a jump table.
const PseudoSourceValue * getGlobalValueCallEntry(const GlobalValue *GV)
static MachineOperand CreateES(const char *SymName, unsigned char TargetFlags=0)
const PseudoSourceValue * getGOT()
Return a pseudo source value referencing the global offset table (or something the like)...
LLVM_ATTRIBUTE_ALWAYS_INLINE StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:70
This struct contains the mappings from the slot numbers to unnamed metadata nodes, global values and types.
Definition: SlotMapping.h:33
bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3002
static SMLoc getFromPointer(const char *Ptr)
Definition: SMLoc.h:37
Flags
Flags values. These may be or&#39;d together.
amdgpu Simplify well known AMD library false Value Value * Arg
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
The memory access reads data.
bool Explicit
VReg was explicitly specified in the .mir file.
Definition: MIParser.h:37
Representation of each machine instruction.
Definition: MachineInstr.h:64
const AllocaInst * getObjectAllocation(int ObjectIdx) const
Return the underlying Alloca of the specified stack object if it exists.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
const char * getBufferEnd() const
Definition: MemoryBuffer.h:61
int getColumnNo() const
Definition: SourceMgr.h:289
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
void setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol)
Set a symbol that will be emitted just prior to the instruction itself.
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:123
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
unsigned greater or equal
Definition: InstrTypes.h:670
This file provides utility analysis objects describing memory locations.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:45
virtual const TargetIntrinsicInfo * getIntrinsicInfo() const
If intrinsic information is available, return it. If not, return null.
static MachineOperand CreateCFIIndex(unsigned CFIIndex)
unsigned VReg
Definition: MIParser.h:42
static MachineOperand CreateImm(int64_t Val)
VRegInfo & getVRegInfo(unsigned Num)
Definition: MIParser.cpp:92
#define I(x, y, z)
Definition: MD5.cpp:58
The memory access always returns the same value (or traps).
iterator end()
Definition: DenseMap.h:109
bool isCall() const
Return true if the instruction is a call.
Definition: MCInstrDesc.h:258
0 1 1 0 True if ordered and operands are unequal
Definition: InstrTypes.h:654
DenseMap< unsigned, MachineBasicBlock * > MBBSlots
Definition: MIParser.h:57
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
unsigned getNumSubRegIndices() const
Return the number of sub-register indices understood by the target.
uint32_t Size
Definition: Profile.cpp:47
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
1 0 1 0 True if unordered or greater than
Definition: InstrTypes.h:658
const char * getBufferStart() const
Definition: MemoryBuffer.h:60
Value * lookup(StringRef Name) const
This method finds the value with the given Name in the the symbol table.
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:18
bool isReg() const
isReg - Tests if this is a MO_Register operand.
const unsigned Kind
const PseudoSourceValue * getStack()
Return a pseudo source value referencing the area below the stack frame of a function, e.g., the argument space.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void insert(iterator MBBI, MachineBasicBlock *MBB)
void setMemRefs(MachineFunction &MF, ArrayRef< MachineMemOperand *> MemRefs)
Assign this MachineInstr&#39;s memory reference descriptor list.
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:649
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:566
LLVM Value Representation.
Definition: Value.h:73
static LLT pointer(uint16_t AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space (defaulting to 0).
A token produced by the machine instruction lexer.
Definition: MILexer.h:28
1 0 1 1 True if unordered, greater than, or equal
Definition: InstrTypes.h:659
Synchronized with respect to all concurrently executing threads.
Definition: LLVMContext.h:59
Lightweight error class with error context and mandatory checking.
Definition: Error.h:158
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:81
IRTranslator LLVM IR MI
unsigned greater than
Definition: InstrTypes.h:669
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
static LLT vector(uint16_t NumElements, unsigned ScalarSizeInBits)
Get a low-level vector of some number of elements and element width.
const RegisterBank * RegBank
Definition: MIParser.h:40
Represents a location in source code.
Definition: SMLoc.h:24
void setIsDebug(bool Val=true)
static MCCFIInstruction createEscape(MCSymbol *L, StringRef Vals)
.cfi_escape Allows the user to add arbitrary bytes to the unwind info.
Definition: MCDwarf.h:549
bool parseRegisterReference(PerFunctionMIParsingState &PFS, unsigned &Reg, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:2978
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:651
static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST, DenseMap< unsigned, const Value *> &Slots2Values)
Definition: MIParser.cpp:2833
static void initSlots2Values(const Function &F, DenseMap< unsigned, const Value *> &Slots2Values)
Creates the mapping from slot numbers to function&#39;s unnamed IR values.
Definition: MIParser.cpp:2842
static MachineOperand CreateFI(int Idx)
const PseudoSourceValue * getConstantPool()
Return a pseudo source value referencing the constant pool.
iterator end()
Definition: StringMap.h:318
static MCCFIInstruction createRegister(MCSymbol *L, unsigned Register1, unsigned Register2)
.cfi_register Previous value of Register1 is saved in register Register2.
Definition: MCDwarf.h:503
iterator_range< arg_iterator > args()
Definition: Function.h:689
0 0 0 0 Always false (always folded)
Definition: InstrTypes.h:648
signed greater or equal
Definition: InstrTypes.h:674
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
const MCPhysReg * ImplicitUses
Definition: MCInstrDesc.h:173
bool isImplicit() const
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:260
PerFunctionMIParsingState(MachineFunction &MF, SourceMgr &SM, const SlotMapping &IRSlots, const Name2RegClassMap &Names2RegClasses, const Name2RegBankMap &Names2RegBanks)
Definition: MIParser.cpp:84
void tieOperands(unsigned DefIdx, unsigned UseIdx)
Add a tie between the register operands at DefIdx and UseIdx.