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