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