LLVM  7.0.0svn
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 Source,
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 *&Node);
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 
717 bool MIParser::parse(MachineInstr *&MI) {
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");
1962  assert(TRI && "Expected target register info");
1963  lex();
1964  if (expectAndConsume(MIToken::lparen))
1965  return true;
1966 
1967  uint32_t *Mask = MF.allocateRegisterMask(TRI->getNumRegs());
1968  while (true) {
1969  if (Token.isNot(MIToken::NamedRegister))
1970  return error("expected a named register");
1971  unsigned Reg;
1972  if (parseNamedRegister(Reg))
1973  return true;
1974  lex();
1975  Mask[Reg / 32] |= 1U << (Reg % 32);
1976  // TODO: Report an error if the same register is used more than once.
1977  if (Token.isNot(MIToken::comma))
1978  break;
1979  lex();
1980  }
1981 
1982  if (expectAndConsume(MIToken::rparen))
1983  return true;
1984  Dest = MachineOperand::CreateRegMask(Mask);
1985  return false;
1986 }
1987 
1988 bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
1989  assert(Token.is(MIToken::kw_liveout));
1990  const auto *TRI = MF.getSubtarget().getRegisterInfo();
1991  assert(TRI && "Expected target register info");
1992  uint32_t *Mask = MF.allocateRegisterMask(TRI->getNumRegs());
1993  lex();
1994  if (expectAndConsume(MIToken::lparen))
1995  return true;
1996  while (true) {
1997  if (Token.isNot(MIToken::NamedRegister))
1998  return error("expected a named register");
1999  unsigned Reg;
2000  if (parseNamedRegister(Reg))
2001  return true;
2002  lex();
2003  Mask[Reg / 32] |= 1U << (Reg % 32);
2004  // TODO: Report an error if the same register is used more than once.
2005  if (Token.isNot(MIToken::comma))
2006  break;
2007  lex();
2008  }
2009  if (expectAndConsume(MIToken::rparen))
2010  return true;
2011  Dest = MachineOperand::CreateRegLiveOut(Mask);
2012  return false;
2013 }
2014 
2015 bool MIParser::parseMachineOperand(MachineOperand &Dest,
2016  Optional<unsigned> &TiedDefIdx) {
2017  switch (Token.kind()) {
2018  case MIToken::kw_implicit:
2020  case MIToken::kw_def:
2021  case MIToken::kw_dead:
2022  case MIToken::kw_killed:
2023  case MIToken::kw_undef:
2024  case MIToken::kw_internal:
2026  case MIToken::kw_debug_use:
2027  case MIToken::kw_renamable:
2028  case MIToken::underscore:
2032  return parseRegisterOperand(Dest, TiedDefIdx);
2034  return parseImmediateOperand(Dest);
2035  case MIToken::kw_half:
2036  case MIToken::kw_float:
2037  case MIToken::kw_double:
2038  case MIToken::kw_x86_fp80:
2039  case MIToken::kw_fp128:
2040  case MIToken::kw_ppc_fp128:
2041  return parseFPImmediateOperand(Dest);
2043  return parseMBBOperand(Dest);
2044  case MIToken::StackObject:
2045  return parseStackObjectOperand(Dest);
2047  return parseFixedStackObjectOperand(Dest);
2048  case MIToken::GlobalValue:
2050  return parseGlobalAddressOperand(Dest);
2052  return parseConstantPoolIndexOperand(Dest);
2054  return parseJumpTableIndexOperand(Dest);
2056  return parseExternalSymbolOperand(Dest);
2058  return parseSubRegisterIndexOperand(Dest);
2059  case MIToken::md_diexpr:
2060  case MIToken::exclaim:
2061  return parseMetadataOperand(Dest);
2076  return parseCFIOperand(Dest);
2078  return parseBlockAddressOperand(Dest);
2079  case MIToken::kw_intrinsic:
2080  return parseIntrinsicOperand(Dest);
2082  return parseTargetIndexOperand(Dest);
2083  case MIToken::kw_liveout:
2084  return parseLiveoutRegisterMaskOperand(Dest);
2085  case MIToken::kw_floatpred:
2086  case MIToken::kw_intpred:
2087  return parsePredicateOperand(Dest);
2088  case MIToken::Error:
2089  return true;
2090  case MIToken::Identifier:
2091  if (const auto *RegMask = getRegMask(Token.stringValue())) {
2092  Dest = MachineOperand::CreateRegMask(RegMask);
2093  lex();
2094  break;
2095  } else if (Token.stringValue() == "CustomRegMask") {
2096  return parseCustomRegisterMaskOperand(Dest);
2097  } else
2098  return parseTypedImmediateOperand(Dest);
2099  default:
2100  // FIXME: Parse the MCSymbol machine operand.
2101  return error("expected a machine operand");
2102  }
2103  return false;
2104 }
2105 
2106 bool MIParser::parseMachineOperandAndTargetFlags(
2107  MachineOperand &Dest, Optional<unsigned> &TiedDefIdx) {
2108  unsigned TF = 0;
2109  bool HasTargetFlags = false;
2110  if (Token.is(MIToken::kw_target_flags)) {
2111  HasTargetFlags = true;
2112  lex();
2113  if (expectAndConsume(MIToken::lparen))
2114  return true;
2115  if (Token.isNot(MIToken::Identifier))
2116  return error("expected the name of the target flag");
2117  if (getDirectTargetFlag(Token.stringValue(), TF)) {
2118  if (getBitmaskTargetFlag(Token.stringValue(), TF))
2119  return error("use of undefined target flag '" + Token.stringValue() +
2120  "'");
2121  }
2122  lex();
2123  while (Token.is(MIToken::comma)) {
2124  lex();
2125  if (Token.isNot(MIToken::Identifier))
2126  return error("expected the name of the target flag");
2127  unsigned BitFlag = 0;
2128  if (getBitmaskTargetFlag(Token.stringValue(), BitFlag))
2129  return error("use of undefined target flag '" + Token.stringValue() +
2130  "'");
2131  // TODO: Report an error when using a duplicate bit target flag.
2132  TF |= BitFlag;
2133  lex();
2134  }
2135  if (expectAndConsume(MIToken::rparen))
2136  return true;
2137  }
2138  auto Loc = Token.location();
2139  if (parseMachineOperand(Dest, TiedDefIdx))
2140  return true;
2141  if (!HasTargetFlags)
2142  return false;
2143  if (Dest.isReg())
2144  return error(Loc, "register operands can't have target flags");
2145  Dest.setTargetFlags(TF);
2146  return false;
2147 }
2148 
2149 bool MIParser::parseOffset(int64_t &Offset) {
2150  if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
2151  return false;
2152  StringRef Sign = Token.range();
2153  bool IsNegative = Token.is(MIToken::minus);
2154  lex();
2155  if (Token.isNot(MIToken::IntegerLiteral))
2156  return error("expected an integer literal after '" + Sign + "'");
2157  if (Token.integerValue().getMinSignedBits() > 64)
2158  return error("expected 64-bit integer (too large)");
2159  Offset = Token.integerValue().getExtValue();
2160  if (IsNegative)
2161  Offset = -Offset;
2162  lex();
2163  return false;
2164 }
2165 
2166 bool MIParser::parseAlignment(unsigned &Alignment) {
2167  assert(Token.is(MIToken::kw_align));
2168  lex();
2169  if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
2170  return error("expected an integer literal after 'align'");
2171  if (getUnsigned(Alignment))
2172  return true;
2173  lex();
2174  return false;
2175 }
2176 
2177 bool MIParser::parseAddrspace(unsigned &Addrspace) {
2178  assert(Token.is(MIToken::kw_addrspace));
2179  lex();
2180  if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
2181  return error("expected an integer literal after 'addrspace'");
2182  if (getUnsigned(Addrspace))
2183  return true;
2184  lex();
2185  return false;
2186 }
2187 
2188 bool MIParser::parseOperandsOffset(MachineOperand &Op) {
2189  int64_t Offset = 0;
2190  if (parseOffset(Offset))
2191  return true;
2192  Op.setOffset(Offset);
2193  return false;
2194 }
2195 
2196 bool MIParser::parseIRValue(const Value *&V) {
2197  switch (Token.kind()) {
2198  case MIToken::NamedIRValue: {
2199  V = MF.getFunction().getValueSymbolTable()->lookup(Token.stringValue());
2200  break;
2201  }
2202  case MIToken::IRValue: {
2203  unsigned SlotNumber = 0;
2204  if (getUnsigned(SlotNumber))
2205  return true;
2206  V = getIRValue(SlotNumber);
2207  break;
2208  }
2210  case MIToken::GlobalValue: {
2211  GlobalValue *GV = nullptr;
2212  if (parseGlobalValue(GV))
2213  return true;
2214  V = GV;
2215  break;
2216  }
2217  case MIToken::QuotedIRValue: {
2218  const Constant *C = nullptr;
2219  if (parseIRConstant(Token.location(), Token.stringValue(), C))
2220  return true;
2221  V = C;
2222  break;
2223  }
2224  default:
2225  llvm_unreachable("The current token should be an IR block reference");
2226  }
2227  if (!V)
2228  return error(Twine("use of undefined IR value '") + Token.range() + "'");
2229  return false;
2230 }
2231 
2232 bool MIParser::getUint64(uint64_t &Result) {
2233  if (Token.hasIntegerValue()) {
2234  if (Token.integerValue().getActiveBits() > 64)
2235  return error("expected 64-bit integer (too large)");
2236  Result = Token.integerValue().getZExtValue();
2237  return false;
2238  }
2239  if (Token.is(MIToken::HexLiteral)) {
2240  APInt A;
2241  if (getHexUint(A))
2242  return true;
2243  if (A.getBitWidth() > 64)
2244  return error("expected 64-bit integer (too large)");
2245  Result = A.getZExtValue();
2246  return false;
2247  }
2248  return true;
2249 }
2250 
2251 bool MIParser::getHexUint(APInt &Result) {
2252  assert(Token.is(MIToken::HexLiteral));
2253  StringRef S = Token.range();
2254  assert(S[0] == '0' && tolower(S[1]) == 'x');
2255  // This could be a floating point literal with a special prefix.
2256  if (!isxdigit(S[2]))
2257  return true;
2258  StringRef V = S.substr(2);
2259  APInt A(V.size()*4, V, 16);
2260 
2261  // If A is 0, then A.getActiveBits() is 0. This isn't a valid bitwidth. Make
2262  // sure it isn't the case before constructing result.
2263  unsigned NumBits = (A == 0) ? 32 : A.getActiveBits();
2264  Result = APInt(NumBits, ArrayRef<uint64_t>(A.getRawData(), A.getNumWords()));
2265  return false;
2266 }
2267 
2268 bool MIParser::parseMemoryOperandFlag(MachineMemOperand::Flags &Flags) {
2269  const auto OldFlags = Flags;
2270  switch (Token.kind()) {
2271  case MIToken::kw_volatile:
2273  break;
2276  break;
2279  break;
2280  case MIToken::kw_invariant:
2282  break;
2283  case MIToken::StringConstant: {
2285  if (getMMOTargetFlag(Token.stringValue(), TF))
2286  return error("use of undefined target MMO flag '" + Token.stringValue() +
2287  "'");
2288  Flags |= TF;
2289  break;
2290  }
2291  default:
2292  llvm_unreachable("The current token should be a memory operand flag");
2293  }
2294  if (OldFlags == Flags)
2295  // We know that the same flag is specified more than once when the flags
2296  // weren't modified.
2297  return error("duplicate '" + Token.stringValue() + "' memory operand flag");
2298  lex();
2299  return false;
2300 }
2301 
2302 bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
2303  switch (Token.kind()) {
2304  case MIToken::kw_stack:
2305  PSV = MF.getPSVManager().getStack();
2306  break;
2307  case MIToken::kw_got:
2308  PSV = MF.getPSVManager().getGOT();
2309  break;
2311  PSV = MF.getPSVManager().getJumpTable();
2312  break;
2314  PSV = MF.getPSVManager().getConstantPool();
2315  break;
2317  int FI;
2318  if (parseFixedStackFrameIndex(FI))
2319  return true;
2320  PSV = MF.getPSVManager().getFixedStack(FI);
2321  // The token was already consumed, so use return here instead of break.
2322  return false;
2323  }
2324  case MIToken::StackObject: {
2325  int FI;
2326  if (parseStackFrameIndex(FI))
2327  return true;
2328  PSV = MF.getPSVManager().getFixedStack(FI);
2329  // The token was already consumed, so use return here instead of break.
2330  return false;
2331  }
2333  lex();
2334  switch (Token.kind()) {
2335  case MIToken::GlobalValue:
2337  GlobalValue *GV = nullptr;
2338  if (parseGlobalValue(GV))
2339  return true;
2341  break;
2342  }
2345  MF.createExternalSymbolName(Token.stringValue()));
2346  break;
2347  default:
2348  return error(
2349  "expected a global value or an external symbol after 'call-entry'");
2350  }
2351  break;
2352  default:
2353  llvm_unreachable("The current token should be pseudo source value");
2354  }
2355  lex();
2356  return false;
2357 }
2358 
2359 bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
2360  if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
2361  Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
2362  Token.is(MIToken::FixedStackObject) || Token.is(MIToken::StackObject) ||
2363  Token.is(MIToken::kw_call_entry)) {
2364  const PseudoSourceValue *PSV = nullptr;
2365  if (parseMemoryPseudoSourceValue(PSV))
2366  return true;
2367  int64_t Offset = 0;
2368  if (parseOffset(Offset))
2369  return true;
2370  Dest = MachinePointerInfo(PSV, Offset);
2371  return false;
2372  }
2373  if (Token.isNot(MIToken::NamedIRValue) && Token.isNot(MIToken::IRValue) &&
2374  Token.isNot(MIToken::GlobalValue) &&
2375  Token.isNot(MIToken::NamedGlobalValue) &&
2376  Token.isNot(MIToken::QuotedIRValue))
2377  return error("expected an IR value reference");
2378  const Value *V = nullptr;
2379  if (parseIRValue(V))
2380  return true;
2381  if (!V->getType()->isPointerTy())
2382  return error("expected a pointer IR value");
2383  lex();
2384  int64_t Offset = 0;
2385  if (parseOffset(Offset))
2386  return true;
2387  Dest = MachinePointerInfo(V, Offset);
2388  return false;
2389 }
2390 
2391 bool MIParser::parseOptionalScope(LLVMContext &Context,
2392  SyncScope::ID &SSID) {
2393  SSID = SyncScope::System;
2394  if (Token.is(MIToken::Identifier) && Token.stringValue() == "syncscope") {
2395  lex();
2396  if (expectAndConsume(MIToken::lparen))
2397  return error("expected '(' in syncscope");
2398 
2399  std::string SSN;
2400  if (parseStringConstant(SSN))
2401  return true;
2402 
2403  SSID = Context.getOrInsertSyncScopeID(SSN);
2404  if (expectAndConsume(MIToken::rparen))
2405  return error("expected ')' in syncscope");
2406  }
2407 
2408  return false;
2409 }
2410 
2411 bool MIParser::parseOptionalAtomicOrdering(AtomicOrdering &Order) {
2412  Order = AtomicOrdering::NotAtomic;
2413  if (Token.isNot(MIToken::Identifier))
2414  return false;
2415 
2416  Order = StringSwitch<AtomicOrdering>(Token.stringValue())
2417  .Case("unordered", AtomicOrdering::Unordered)
2418  .Case("monotonic", AtomicOrdering::Monotonic)
2419  .Case("acquire", AtomicOrdering::Acquire)
2420  .Case("release", AtomicOrdering::Release)
2424 
2425  if (Order != AtomicOrdering::NotAtomic) {
2426  lex();
2427  return false;
2428  }
2429 
2430  return error("expected an atomic scope, ordering or a size integer literal");
2431 }
2432 
2433 bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
2434  if (expectAndConsume(MIToken::lparen))
2435  return true;
2437  while (Token.isMemoryOperandFlag()) {
2438  if (parseMemoryOperandFlag(Flags))
2439  return true;
2440  }
2441  if (Token.isNot(MIToken::Identifier) ||
2442  (Token.stringValue() != "load" && Token.stringValue() != "store"))
2443  return error("expected 'load' or 'store' memory operation");
2444  if (Token.stringValue() == "load")
2445  Flags |= MachineMemOperand::MOLoad;
2446  else
2447  Flags |= MachineMemOperand::MOStore;
2448  lex();
2449 
2450  // Optional 'store' for operands that both load and store.
2451  if (Token.is(MIToken::Identifier) && Token.stringValue() == "store") {
2452  Flags |= MachineMemOperand::MOStore;
2453  lex();
2454  }
2455 
2456  // Optional synchronization scope.
2457  SyncScope::ID SSID;
2458  if (parseOptionalScope(MF.getFunction().getContext(), SSID))
2459  return true;
2460 
2461  // Up to two atomic orderings (cmpxchg provides guarantees on failure).
2462  AtomicOrdering Order, FailureOrder;
2463  if (parseOptionalAtomicOrdering(Order))
2464  return true;
2465 
2466  if (parseOptionalAtomicOrdering(FailureOrder))
2467  return true;
2468 
2469  if (Token.isNot(MIToken::IntegerLiteral))
2470  return error("expected the size integer literal after memory operation");
2471  uint64_t Size;
2472  if (getUint64(Size))
2473  return true;
2474  lex();
2475 
2477  if (Token.is(MIToken::Identifier)) {
2478  const char *Word =
2479  ((Flags & MachineMemOperand::MOLoad) &&
2480  (Flags & MachineMemOperand::MOStore))
2481  ? "on"
2482  : Flags & MachineMemOperand::MOLoad ? "from" : "into";
2483  if (Token.stringValue() != Word)
2484  return error(Twine("expected '") + Word + "'");
2485  lex();
2486 
2487  if (parseMachinePointerInfo(Ptr))
2488  return true;
2489  }
2490  unsigned BaseAlignment = Size;
2491  AAMDNodes AAInfo;
2492  MDNode *Range = nullptr;
2493  while (consumeIfPresent(MIToken::comma)) {
2494  switch (Token.kind()) {
2495  case MIToken::kw_align:
2496  if (parseAlignment(BaseAlignment))
2497  return true;
2498  break;
2499  case MIToken::kw_addrspace:
2500  if (parseAddrspace(Ptr.AddrSpace))
2501  return true;
2502  break;
2503  case MIToken::md_tbaa:
2504  lex();
2505  if (parseMDNode(AAInfo.TBAA))
2506  return true;
2507  break;
2509  lex();
2510  if (parseMDNode(AAInfo.Scope))
2511  return true;
2512  break;
2513  case MIToken::md_noalias:
2514  lex();
2515  if (parseMDNode(AAInfo.NoAlias))
2516  return true;
2517  break;
2518  case MIToken::md_range:
2519  lex();
2520  if (parseMDNode(Range))
2521  return true;
2522  break;
2523  // TODO: Report an error on duplicate metadata nodes.
2524  default:
2525  return error("expected 'align' or '!tbaa' or '!alias.scope' or "
2526  "'!noalias' or '!range'");
2527  }
2528  }
2529  if (expectAndConsume(MIToken::rparen))
2530  return true;
2531  Dest = MF.getMachineMemOperand(Ptr, Flags, Size, BaseAlignment, AAInfo, Range,
2532  SSID, Order, FailureOrder);
2533  return false;
2534 }
2535 
2536 void MIParser::initNames2InstrOpCodes() {
2537  if (!Names2InstrOpCodes.empty())
2538  return;
2539  const auto *TII = MF.getSubtarget().getInstrInfo();
2540  assert(TII && "Expected target instruction info");
2541  for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
2542  Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
2543 }
2544 
2545 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
2546  initNames2InstrOpCodes();
2547  auto InstrInfo = Names2InstrOpCodes.find(InstrName);
2548  if (InstrInfo == Names2InstrOpCodes.end())
2549  return true;
2550  OpCode = InstrInfo->getValue();
2551  return false;
2552 }
2553 
2554 void MIParser::initNames2Regs() {
2555  if (!Names2Regs.empty())
2556  return;
2557  // The '%noreg' register is the register 0.
2558  Names2Regs.insert(std::make_pair("noreg", 0));
2559  const auto *TRI = MF.getSubtarget().getRegisterInfo();
2560  assert(TRI && "Expected target register info");
2561  for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
2562  bool WasInserted =
2563  Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
2564  .second;
2565  (void)WasInserted;
2566  assert(WasInserted && "Expected registers to be unique case-insensitively");
2567  }
2568 }
2569 
2570 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
2571  initNames2Regs();
2572  auto RegInfo = Names2Regs.find(RegName);
2573  if (RegInfo == Names2Regs.end())
2574  return true;
2575  Reg = RegInfo->getValue();
2576  return false;
2577 }
2578 
2579 void MIParser::initNames2RegMasks() {
2580  if (!Names2RegMasks.empty())
2581  return;
2582  const auto *TRI = MF.getSubtarget().getRegisterInfo();
2583  assert(TRI && "Expected target register info");
2584  ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
2585  ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
2586  assert(RegMasks.size() == RegMaskNames.size());
2587  for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
2588  Names2RegMasks.insert(
2589  std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
2590 }
2591 
2592 const uint32_t *MIParser::getRegMask(StringRef Identifier) {
2593  initNames2RegMasks();
2594  auto RegMaskInfo = Names2RegMasks.find(Identifier);
2595  if (RegMaskInfo == Names2RegMasks.end())
2596  return nullptr;
2597  return RegMaskInfo->getValue();
2598 }
2599 
2600 void MIParser::initNames2SubRegIndices() {
2601  if (!Names2SubRegIndices.empty())
2602  return;
2604  for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
2605  Names2SubRegIndices.insert(
2606  std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
2607 }
2608 
2609 unsigned MIParser::getSubRegIndex(StringRef Name) {
2610  initNames2SubRegIndices();
2611  auto SubRegInfo = Names2SubRegIndices.find(Name);
2612  if (SubRegInfo == Names2SubRegIndices.end())
2613  return 0;
2614  return SubRegInfo->getValue();
2615 }
2616 
2618  const Function &F,
2619  DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
2620  ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
2621  MST.incorporateFunction(F);
2622  for (auto &BB : F) {
2623  if (BB.hasName())
2624  continue;
2625  int Slot = MST.getLocalSlot(&BB);
2626  if (Slot == -1)
2627  continue;
2628  Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
2629  }
2630 }
2631 
2633  unsigned Slot,
2634  const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
2635  auto BlockInfo = Slots2BasicBlocks.find(Slot);
2636  if (BlockInfo == Slots2BasicBlocks.end())
2637  return nullptr;
2638  return BlockInfo->second;
2639 }
2640 
2641 const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
2642  if (Slots2BasicBlocks.empty())
2643  initSlots2BasicBlocks(MF.getFunction(), Slots2BasicBlocks);
2644  return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
2645 }
2646 
2647 const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
2648  if (&F == &MF.getFunction())
2649  return getIRBlock(Slot);
2650  DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
2651  initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
2652  return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
2653 }
2654 
2655 static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST,
2656  DenseMap<unsigned, const Value *> &Slots2Values) {
2657  int Slot = MST.getLocalSlot(V);
2658  if (Slot == -1)
2659  return;
2660  Slots2Values.insert(std::make_pair(unsigned(Slot), V));
2661 }
2662 
2663 /// Creates the mapping from slot numbers to function's unnamed IR values.
2664 static void initSlots2Values(const Function &F,
2665  DenseMap<unsigned, const Value *> &Slots2Values) {
2666  ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
2667  MST.incorporateFunction(F);
2668  for (const auto &Arg : F.args())
2669  mapValueToSlot(&Arg, MST, Slots2Values);
2670  for (const auto &BB : F) {
2671  mapValueToSlot(&BB, MST, Slots2Values);
2672  for (const auto &I : BB)
2673  mapValueToSlot(&I, MST, Slots2Values);
2674  }
2675 }
2676 
2677 const Value *MIParser::getIRValue(unsigned Slot) {
2678  if (Slots2Values.empty())
2679  initSlots2Values(MF.getFunction(), Slots2Values);
2680  auto ValueInfo = Slots2Values.find(Slot);
2681  if (ValueInfo == Slots2Values.end())
2682  return nullptr;
2683  return ValueInfo->second;
2684 }
2685 
2686 void MIParser::initNames2TargetIndices() {
2687  if (!Names2TargetIndices.empty())
2688  return;
2689  const auto *TII = MF.getSubtarget().getInstrInfo();
2690  assert(TII && "Expected target instruction info");
2691  auto Indices = TII->getSerializableTargetIndices();
2692  for (const auto &I : Indices)
2693  Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
2694 }
2695 
2696 bool MIParser::getTargetIndex(StringRef Name, int &Index) {
2697  initNames2TargetIndices();
2698  auto IndexInfo = Names2TargetIndices.find(Name);
2699  if (IndexInfo == Names2TargetIndices.end())
2700  return true;
2701  Index = IndexInfo->second;
2702  return false;
2703 }
2704 
2705 void MIParser::initNames2DirectTargetFlags() {
2706  if (!Names2DirectTargetFlags.empty())
2707  return;
2708  const auto *TII = MF.getSubtarget().getInstrInfo();
2709  assert(TII && "Expected target instruction info");
2711  for (const auto &I : Flags)
2712  Names2DirectTargetFlags.insert(
2713  std::make_pair(StringRef(I.second), I.first));
2714 }
2715 
2716 bool MIParser::getDirectTargetFlag(StringRef Name, unsigned &Flag) {
2717  initNames2DirectTargetFlags();
2718  auto FlagInfo = Names2DirectTargetFlags.find(Name);
2719  if (FlagInfo == Names2DirectTargetFlags.end())
2720  return true;
2721  Flag = FlagInfo->second;
2722  return false;
2723 }
2724 
2725 void MIParser::initNames2BitmaskTargetFlags() {
2726  if (!Names2BitmaskTargetFlags.empty())
2727  return;
2728  const auto *TII = MF.getSubtarget().getInstrInfo();
2729  assert(TII && "Expected target instruction info");
2731  for (const auto &I : Flags)
2732  Names2BitmaskTargetFlags.insert(
2733  std::make_pair(StringRef(I.second), I.first));
2734 }
2735 
2736 bool MIParser::getBitmaskTargetFlag(StringRef Name, unsigned &Flag) {
2737  initNames2BitmaskTargetFlags();
2738  auto FlagInfo = Names2BitmaskTargetFlags.find(Name);
2739  if (FlagInfo == Names2BitmaskTargetFlags.end())
2740  return true;
2741  Flag = FlagInfo->second;
2742  return false;
2743 }
2744 
2745 void MIParser::initNames2MMOTargetFlags() {
2746  if (!Names2MMOTargetFlags.empty())
2747  return;
2748  const auto *TII = MF.getSubtarget().getInstrInfo();
2749  assert(TII && "Expected target instruction info");
2750  auto Flags = TII->getSerializableMachineMemOperandTargetFlags();
2751  for (const auto &I : Flags)
2752  Names2MMOTargetFlags.insert(
2753  std::make_pair(StringRef(I.second), I.first));
2754 }
2755 
2756 bool MIParser::getMMOTargetFlag(StringRef Name,
2757  MachineMemOperand::Flags &Flag) {
2758  initNames2MMOTargetFlags();
2759  auto FlagInfo = Names2MMOTargetFlags.find(Name);
2760  if (FlagInfo == Names2MMOTargetFlags.end())
2761  return true;
2762  Flag = FlagInfo->second;
2763  return false;
2764 }
2765 
2766 bool MIParser::parseStringConstant(std::string &Result) {
2767  if (Token.isNot(MIToken::StringConstant))
2768  return error("expected string constant");
2769  Result = Token.stringValue();
2770  lex();
2771  return false;
2772 }
2773 
2775  StringRef Src,
2776  SMDiagnostic &Error) {
2777  return MIParser(PFS, Error, Src).parseBasicBlockDefinitions(PFS.MBBSlots);
2778 }
2779 
2781  StringRef Src, SMDiagnostic &Error) {
2782  return MIParser(PFS, Error, Src).parseBasicBlocks();
2783 }
2784 
2786  MachineBasicBlock *&MBB, StringRef Src,
2787  SMDiagnostic &Error) {
2788  return MIParser(PFS, Error, Src).parseStandaloneMBB(MBB);
2789 }
2790 
2792  unsigned &Reg, StringRef Src,
2793  SMDiagnostic &Error) {
2794  return MIParser(PFS, Error, Src).parseStandaloneRegister(Reg);
2795 }
2796 
2798  unsigned &Reg, StringRef Src,
2799  SMDiagnostic &Error) {
2800  return MIParser(PFS, Error, Src).parseStandaloneNamedRegister(Reg);
2801 }
2802 
2804  VRegInfo *&Info, StringRef Src,
2805  SMDiagnostic &Error) {
2806  return MIParser(PFS, Error, Src).parseStandaloneVirtualRegister(Info);
2807 }
2808 
2810  int &FI, StringRef Src,
2811  SMDiagnostic &Error) {
2812  return MIParser(PFS, Error, Src).parseStandaloneStackObject(FI);
2813 }
2814 
2816  MDNode *&Node, StringRef Src, SMDiagnostic &Error) {
2817  return MIParser(PFS, Error, Src).parseStandaloneMDNode(Node);
2818 }
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:71
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:2774
static void initSlots2BasicBlocks(const Function &F, DenseMap< unsigned, const BasicBlock *> &Slots2BasicBlocks)
Definition: MIParser.cpp:2617
A common definition of LaneBitmask for use in TableGen and CodeGen.
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1547
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:75
void setTargetFlags(unsigned F)
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:137
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:522
const MCPhysReg * getImplicitUses() const
Return a list of registers that are potentially read by any instance of this machine instruction...
Definition: MCInstrDesc.h:513
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:161
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:477
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:843
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:908
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:2785
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:464
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:471
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:1493
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:511
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
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:947
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:2632
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.
Definition: regcomp.c:191
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:2803
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 ...
Synchronized with respect to all concurrently executing threads.
Definition: LLVMContext.h:59
VRegInfo & getVRegInfo(unsigned VReg)
Definition: MIParser.cpp:90
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:517
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:2809
const MCPhysReg * getImplicitDefs() const
Return a list of registers that are potentially written by any instance of this machine instruction...
Definition: MCInstrDesc.h:535
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:450
static Intrinsic::ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
Definition: Function.cpp:521
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:457
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1401
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:498
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:117
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:221
StringMap< VRegInfo * > VRegInfosNamed
Definition: MIParser.h:59
unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition: Dwarf.cpp:151
const MCPhysReg * ImplicitDefs
Definition: MCInstrDesc.h:171
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:2797
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 const unsigned End
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:485
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:505
0 1 1 1 True if ordered (no nans)
Definition: InstrTypes.h:894
The memory access is non-temporal.
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:193
void incorporateFunction(const Function &F)
Incorporate the given function.
Definition: AsmWriter.cpp:829
const SlotMapping & IRSlots
Definition: MIParser.h:53
uint32_t * allocateRegisterMask(unsigned NumRegister)
Allocate and initialize a register mask with NumRegister bits.
static MCCFIInstruction createRestoreState(MCSymbol *L)
.cfi_restore_state Restore the previously saved state.
Definition: MCDwarf.h:527
const AMDGPUAS & AS
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
This class contains a discriminated union of information about pointers in memory operands...
const char * createExternalSymbolName(StringRef Name)
Allocate a string and populate it with the given external symbol name.
1 1 0 1 True if unordered, less than, or equal
Definition: InstrTypes.h: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:169
signed greater than
Definition: InstrTypes.h:912
bool parseMachineInstructions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine instructions.
Definition: MIParser.cpp:2780
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...
union llvm::VRegInfo::@320 D
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:861
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
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:2815
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:121
const char * getBufferEnd() const
Definition: MemoryBuffer.h:62
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:62
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)
#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:252
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:61
Value * lookup(StringRef Name) const
This method finds the value with the given Name in the the symbol table.
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:18
bool isReg() const
isReg - Tests if this is a MO_Register operand.
const unsigned Kind
const PseudoSourceValue * getStack()
Return a pseudo source value referencing the area below the stack frame of a function, e.g., the argument space.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void insert(iterator MBBI, MachineBasicBlock *MBB)
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:156
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:533
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:960
bool parseRegisterReference(PerFunctionMIParsingState &PFS, unsigned &Reg, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:2791
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:2655
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:2664
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
void guessSuccessors(const MachineBasicBlock &MBB, SmallVectorImpl< MachineBasicBlock *> &Successors, bool &IsFallthrough)
Determine a possible list of successors of a basic block based on the basic block machine operand bei...
Definition: MIRPrinter.cpp:497
static MCCFIInstruction createRegister(MCSymbol *L, unsigned Register1, unsigned Register2)
.cfi_register Previous value of Register1 is saved in register Register2.
Definition: MCDwarf.h:492
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:170
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.