blob: 36b34395d4d645a43e3592733bba53e787c57751 [file] [log] [blame]
Alex Lorenz8e0a1b42015-06-22 17:02:30 +00001//===- MIParser.cpp - Machine instructions parser implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the parsing of machine instructions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "MIParser.h"
Alex Lorenz91370c52015-06-22 20:37:46 +000015#include "MILexer.h"
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000016#include "llvm/ADT/StringMap.h"
Alex Lorenzad156fb2015-07-31 20:49:21 +000017#include "llvm/AsmParser/Parser.h"
Alex Lorenz5d6108e2015-06-26 22:56:48 +000018#include "llvm/AsmParser/SlotMapping.h"
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000019#include "llvm/CodeGen/MachineBasicBlock.h"
20#include "llvm/CodeGen/MachineFunction.h"
Alex Lorenz7feaf7c2015-07-16 23:37:45 +000021#include "llvm/CodeGen/MachineFrameInfo.h"
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000022#include "llvm/CodeGen/MachineInstr.h"
Alex Lorenzcb268d42015-07-06 23:07:26 +000023#include "llvm/CodeGen/MachineInstrBuilder.h"
Alex Lorenz4af7e612015-08-03 23:08:19 +000024#include "llvm/CodeGen/MachineMemOperand.h"
Alex Lorenzf4baeb52015-07-21 22:28:27 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Alex Lorenz7feaf7c2015-07-16 23:37:45 +000026#include "llvm/IR/Instructions.h"
Alex Lorenzdeb53492015-07-28 17:28:03 +000027#include "llvm/IR/Constants.h"
Alex Lorenz5d6108e2015-06-26 22:56:48 +000028#include "llvm/IR/Module.h"
Alex Lorenz8a1915b2015-07-27 22:42:41 +000029#include "llvm/IR/ModuleSlotTracker.h"
Alex Lorenzdeb53492015-07-28 17:28:03 +000030#include "llvm/IR/ValueSymbolTable.h"
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000031#include "llvm/Support/raw_ostream.h"
32#include "llvm/Support/SourceMgr.h"
33#include "llvm/Target/TargetSubtargetInfo.h"
34#include "llvm/Target/TargetInstrInfo.h"
35
36using namespace llvm;
37
38namespace {
39
Alex Lorenz36962cd2015-07-07 02:08:46 +000040/// A wrapper struct around the 'MachineOperand' struct that includes a source
41/// range.
42struct MachineOperandWithLocation {
43 MachineOperand Operand;
44 StringRef::iterator Begin;
45 StringRef::iterator End;
46
47 MachineOperandWithLocation(const MachineOperand &Operand,
48 StringRef::iterator Begin, StringRef::iterator End)
49 : Operand(Operand), Begin(Begin), End(End) {}
50};
51
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000052class MIParser {
53 SourceMgr &SM;
54 MachineFunction &MF;
55 SMDiagnostic &Error;
Alex Lorenz91370c52015-06-22 20:37:46 +000056 StringRef Source, CurrentSource;
57 MIToken Token;
Alex Lorenz7a503fa2015-07-07 17:46:43 +000058 const PerFunctionMIParsingState &PFS;
Alex Lorenz5d6108e2015-06-26 22:56:48 +000059 /// Maps from indices to unnamed global values and metadata nodes.
60 const SlotMapping &IRSlots;
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000061 /// Maps from instruction names to op codes.
62 StringMap<unsigned> Names2InstrOpCodes;
Alex Lorenzf3db51de2015-06-23 16:35:26 +000063 /// Maps from register names to registers.
64 StringMap<unsigned> Names2Regs;
Alex Lorenz8f6f4282015-06-29 16:57:06 +000065 /// Maps from register mask names to register masks.
66 StringMap<const uint32_t *> Names2RegMasks;
Alex Lorenz2eacca82015-07-13 23:24:34 +000067 /// Maps from subregister names to subregister indices.
68 StringMap<unsigned> Names2SubRegIndices;
Alex Lorenz8a1915b2015-07-27 22:42:41 +000069 /// Maps from slot numbers to function's unnamed basic blocks.
70 DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks;
Alex Lorenzef5c1962015-07-28 23:02:45 +000071 /// Maps from target index names to target indices.
72 StringMap<int> Names2TargetIndices;
Alex Lorenz49873a82015-08-06 00:44:07 +000073 /// Maps from direct target flag names to the direct target flag values.
74 StringMap<unsigned> Names2DirectTargetFlags;
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000075
76public:
77 MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
Alex Lorenz7a503fa2015-07-07 17:46:43 +000078 StringRef Source, const PerFunctionMIParsingState &PFS,
Alex Lorenz5d6108e2015-06-26 22:56:48 +000079 const SlotMapping &IRSlots);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000080
Alex Lorenz91370c52015-06-22 20:37:46 +000081 void lex();
82
Alex Lorenz8e0a1b42015-06-22 17:02:30 +000083 /// Report an error at the current location with the given message.
84 ///
85 /// This function always return true.
86 bool error(const Twine &Msg);
87
Alex Lorenz91370c52015-06-22 20:37:46 +000088 /// Report an error at the given location with the given message.
89 ///
90 /// This function always return true.
91 bool error(StringRef::iterator Loc, const Twine &Msg);
92
Alex Lorenz5022f6b2015-08-13 23:10:16 +000093 bool
94 parseBasicBlockDefinitions(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
95 bool parseBasicBlocks();
Alex Lorenz3708a642015-06-30 17:47:50 +000096 bool parse(MachineInstr *&MI);
Alex Lorenz1ea60892015-07-27 20:29:27 +000097 bool parseStandaloneMBB(MachineBasicBlock *&MBB);
98 bool parseStandaloneNamedRegister(unsigned &Reg);
Alex Lorenz12045a42015-07-27 17:42:45 +000099 bool parseStandaloneVirtualRegister(unsigned &Reg);
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000100
101 bool
102 parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
103 bool parseBasicBlock(MachineBasicBlock &MBB);
104 bool parseBasicBlockLiveins(MachineBasicBlock &MBB);
105 bool parseBasicBlockSuccessors(MachineBasicBlock &MBB);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000106
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000107 bool parseRegister(unsigned &Reg);
Alex Lorenzcb268d42015-07-06 23:07:26 +0000108 bool parseRegisterFlag(unsigned &Flags);
Alex Lorenz2eacca82015-07-13 23:24:34 +0000109 bool parseSubRegisterIndex(unsigned &SubReg);
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000110 bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
Alex Lorenz240fc1e2015-06-23 23:42:28 +0000111 bool parseImmediateOperand(MachineOperand &Dest);
Alex Lorenz7eaff4c2015-08-05 18:44:00 +0000112 bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
Alex Lorenz05e38822015-08-05 18:52:21 +0000113 bool parseTypedImmediateOperand(MachineOperand &Dest);
Alex Lorenzad156fb2015-07-31 20:49:21 +0000114 bool parseFPImmediateOperand(MachineOperand &Dest);
Alex Lorenzf09df002015-06-30 18:16:42 +0000115 bool parseMBBReference(MachineBasicBlock *&MBB);
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000116 bool parseMBBOperand(MachineOperand &Dest);
Alex Lorenz7feaf7c2015-07-16 23:37:45 +0000117 bool parseStackObjectOperand(MachineOperand &Dest);
Alex Lorenzea882122015-08-12 21:17:02 +0000118 bool parseFixedStackFrameIndex(int &FI);
Alex Lorenz7feaf7c2015-07-16 23:37:45 +0000119 bool parseFixedStackObjectOperand(MachineOperand &Dest);
Alex Lorenz41df7d32015-07-28 17:09:52 +0000120 bool parseGlobalValue(GlobalValue *&GV);
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000121 bool parseGlobalAddressOperand(MachineOperand &Dest);
Alex Lorenzab980492015-07-20 20:51:18 +0000122 bool parseConstantPoolIndexOperand(MachineOperand &Dest);
Alex Lorenz31d70682015-07-15 23:38:35 +0000123 bool parseJumpTableIndexOperand(MachineOperand &Dest);
Alex Lorenz6ede3742015-07-21 16:59:53 +0000124 bool parseExternalSymbolOperand(MachineOperand &Dest);
Alex Lorenz44f29252015-07-22 21:07:04 +0000125 bool parseMDNode(MDNode *&Node);
Alex Lorenz35e44462015-07-22 17:58:46 +0000126 bool parseMetadataOperand(MachineOperand &Dest);
Alex Lorenzf4baeb52015-07-21 22:28:27 +0000127 bool parseCFIOffset(int &Offset);
Alex Lorenz8cfc6862015-07-23 23:09:07 +0000128 bool parseCFIRegister(unsigned &Reg);
Alex Lorenzf4baeb52015-07-21 22:28:27 +0000129 bool parseCFIOperand(MachineOperand &Dest);
Alex Lorenzdeb53492015-07-28 17:28:03 +0000130 bool parseIRBlock(BasicBlock *&BB, const Function &F);
131 bool parseBlockAddressOperand(MachineOperand &Dest);
Alex Lorenzef5c1962015-07-28 23:02:45 +0000132 bool parseTargetIndexOperand(MachineOperand &Dest);
Alex Lorenzb97c9ef2015-08-10 23:24:42 +0000133 bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000134 bool parseMachineOperand(MachineOperand &Dest);
Alex Lorenz49873a82015-08-06 00:44:07 +0000135 bool parseMachineOperandAndTargetFlags(MachineOperand &Dest);
Alex Lorenzdc24c172015-08-07 20:21:00 +0000136 bool parseOffset(int64_t &Offset);
Alex Lorenz620f8912015-08-13 20:33:33 +0000137 bool parseAlignment(unsigned &Alignment);
Alex Lorenz5672a892015-08-05 22:26:15 +0000138 bool parseOperandsOffset(MachineOperand &Op);
Alex Lorenz4af7e612015-08-03 23:08:19 +0000139 bool parseIRValue(Value *&V);
Alex Lorenza518b792015-08-04 00:24:45 +0000140 bool parseMemoryOperandFlag(unsigned &Flags);
Alex Lorenz91097a32015-08-12 20:33:26 +0000141 bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
142 bool parseMachinePointerInfo(MachinePointerInfo &Dest);
Alex Lorenz4af7e612015-08-03 23:08:19 +0000143 bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000144
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000145private:
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000146 /// Convert the integer literal in the current token into an unsigned integer.
147 ///
148 /// Return true if an error occurred.
149 bool getUnsigned(unsigned &Result);
150
Alex Lorenz4af7e612015-08-03 23:08:19 +0000151 /// Convert the integer literal in the current token into an uint64.
152 ///
153 /// Return true if an error occurred.
154 bool getUint64(uint64_t &Result);
155
Alex Lorenz8cfc6862015-07-23 23:09:07 +0000156 /// If the current token is of the given kind, consume it and return false.
157 /// Otherwise report an error and return true.
158 bool expectAndConsume(MIToken::TokenKind TokenKind);
159
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000160 /// If the current token is of the given kind, consume it and return true.
161 /// Otherwise return false.
162 bool consumeIfPresent(MIToken::TokenKind TokenKind);
163
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000164 void initNames2InstrOpCodes();
165
166 /// Try to convert an instruction name to an opcode. Return true if the
167 /// instruction name is invalid.
168 bool parseInstrName(StringRef InstrName, unsigned &OpCode);
Alex Lorenz91370c52015-06-22 20:37:46 +0000169
Alex Lorenze5a44662015-07-17 00:24:15 +0000170 bool parseInstruction(unsigned &OpCode, unsigned &Flags);
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000171
Alex Lorenz36962cd2015-07-07 02:08:46 +0000172 bool verifyImplicitOperands(ArrayRef<MachineOperandWithLocation> Operands,
173 const MCInstrDesc &MCID);
174
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000175 void initNames2Regs();
176
177 /// Try to convert a register name to a register number. Return true if the
178 /// register name is invalid.
179 bool getRegisterByName(StringRef RegName, unsigned &Reg);
Alex Lorenz8f6f4282015-06-29 16:57:06 +0000180
181 void initNames2RegMasks();
182
183 /// Check if the given identifier is a name of a register mask.
184 ///
185 /// Return null if the identifier isn't a register mask.
186 const uint32_t *getRegMask(StringRef Identifier);
Alex Lorenz2eacca82015-07-13 23:24:34 +0000187
188 void initNames2SubRegIndices();
189
190 /// Check if the given identifier is a name of a subregister index.
191 ///
192 /// Return 0 if the name isn't a subregister index class.
193 unsigned getSubRegIndex(StringRef Name);
Alex Lorenz8a1915b2015-07-27 22:42:41 +0000194
Alex Lorenz8a1915b2015-07-27 22:42:41 +0000195 const BasicBlock *getIRBlock(unsigned Slot);
Alex Lorenzcba8c5f2015-08-06 23:57:04 +0000196 const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
Alex Lorenzef5c1962015-07-28 23:02:45 +0000197
198 void initNames2TargetIndices();
199
200 /// Try to convert a name of target index to the corresponding target index.
201 ///
202 /// Return true if the name isn't a name of a target index.
203 bool getTargetIndex(StringRef Name, int &Index);
Alex Lorenz49873a82015-08-06 00:44:07 +0000204
205 void initNames2DirectTargetFlags();
206
207 /// Try to convert a name of a direct target flag to the corresponding
208 /// target flag.
209 ///
210 /// Return true if the name isn't a name of a direct flag.
211 bool getDirectTargetFlag(StringRef Name, unsigned &Flag);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000212};
213
214} // end anonymous namespace
215
216MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
Alex Lorenz7a503fa2015-07-07 17:46:43 +0000217 StringRef Source, const PerFunctionMIParsingState &PFS,
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000218 const SlotMapping &IRSlots)
Alex Lorenz91370c52015-06-22 20:37:46 +0000219 : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
Alex Lorenz3fb77682015-08-06 23:17:42 +0000220 PFS(PFS), IRSlots(IRSlots) {}
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000221
Alex Lorenz91370c52015-06-22 20:37:46 +0000222void MIParser::lex() {
223 CurrentSource = lexMIToken(
224 CurrentSource, Token,
225 [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
226}
227
228bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
229
230bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
Alex Lorenz91370c52015-06-22 20:37:46 +0000231 assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000232 const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
233 if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
234 // Create an ordinary diagnostic when the source manager's buffer is the
235 // source string.
236 Error = SM.GetMessage(SMLoc::getFromPointer(Loc), SourceMgr::DK_Error, Msg);
237 return true;
238 }
239 // Create a diagnostic for a YAML string literal.
240 Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
241 Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
242 Source, None, None);
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000243 return true;
244}
245
Alex Lorenz8cfc6862015-07-23 23:09:07 +0000246static const char *toString(MIToken::TokenKind TokenKind) {
247 switch (TokenKind) {
248 case MIToken::comma:
249 return "','";
Alex Lorenzfbe9c042015-07-29 18:51:21 +0000250 case MIToken::equal:
251 return "'='";
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000252 case MIToken::colon:
253 return "':'";
Alex Lorenzdeb53492015-07-28 17:28:03 +0000254 case MIToken::lparen:
255 return "'('";
256 case MIToken::rparen:
257 return "')'";
Alex Lorenz8cfc6862015-07-23 23:09:07 +0000258 default:
259 return "<unknown token>";
260 }
261}
262
263bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
264 if (Token.isNot(TokenKind))
265 return error(Twine("expected ") + toString(TokenKind));
266 lex();
267 return false;
268}
269
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000270bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
271 if (Token.isNot(TokenKind))
272 return false;
Alex Lorenz91370c52015-06-22 20:37:46 +0000273 lex();
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000274 return true;
275}
Alex Lorenz91370c52015-06-22 20:37:46 +0000276
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000277bool MIParser::parseBasicBlockDefinition(
278 DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
279 assert(Token.is(MIToken::MachineBasicBlockLabel));
280 unsigned ID = 0;
281 if (getUnsigned(ID))
282 return true;
283 auto Loc = Token.location();
284 auto Name = Token.stringValue();
285 lex();
286 bool HasAddressTaken = false;
287 bool IsLandingPad = false;
288 unsigned Alignment = 0;
289 BasicBlock *BB = nullptr;
290 if (consumeIfPresent(MIToken::lparen)) {
291 do {
292 // TODO: Report an error when multiple same attributes are specified.
293 switch (Token.kind()) {
294 case MIToken::kw_address_taken:
295 HasAddressTaken = true;
296 lex();
297 break;
298 case MIToken::kw_landing_pad:
299 IsLandingPad = true;
300 lex();
301 break;
302 case MIToken::kw_align:
303 if (parseAlignment(Alignment))
304 return true;
305 break;
306 case MIToken::IRBlock:
307 // TODO: Report an error when both name and ir block are specified.
308 if (parseIRBlock(BB, *MF.getFunction()))
309 return true;
310 lex();
311 break;
312 default:
313 break;
314 }
315 } while (consumeIfPresent(MIToken::comma));
316 if (expectAndConsume(MIToken::rparen))
317 return true;
318 }
319 if (expectAndConsume(MIToken::colon))
320 return true;
321
322 if (!Name.empty()) {
323 BB = dyn_cast_or_null<BasicBlock>(
324 MF.getFunction()->getValueSymbolTable().lookup(Name));
325 if (!BB)
326 return error(Loc, Twine("basic block '") + Name +
327 "' is not defined in the function '" +
328 MF.getName() + "'");
329 }
330 auto *MBB = MF.CreateMachineBasicBlock(BB);
331 MF.insert(MF.end(), MBB);
332 bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
333 if (!WasInserted)
334 return error(Loc, Twine("redefinition of machine basic block with id #") +
335 Twine(ID));
336 if (Alignment)
337 MBB->setAlignment(Alignment);
338 if (HasAddressTaken)
339 MBB->setHasAddressTaken();
340 MBB->setIsLandingPad(IsLandingPad);
341 return false;
342}
343
344bool MIParser::parseBasicBlockDefinitions(
345 DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
346 lex();
347 // Skip until the first machine basic block.
348 while (Token.is(MIToken::Newline))
349 lex();
350 if (Token.isErrorOrEOF())
351 return Token.isError();
352 if (Token.isNot(MIToken::MachineBasicBlockLabel))
353 return error("expected a basic block definition before instructions");
Alex Lorenzf9a2b122015-08-14 18:57:24 +0000354 unsigned BraceDepth = 0;
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000355 do {
356 if (parseBasicBlockDefinition(MBBSlots))
357 return true;
358 bool IsAfterNewline = false;
359 // Skip until the next machine basic block.
360 while (true) {
361 if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
362 Token.isErrorOrEOF())
363 break;
364 else if (Token.is(MIToken::MachineBasicBlockLabel))
365 return error("basic block definition should be located at the start of "
366 "the line");
Alex Lorenzf9a2b122015-08-14 18:57:24 +0000367 else if (consumeIfPresent(MIToken::Newline)) {
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000368 IsAfterNewline = true;
Alex Lorenzf9a2b122015-08-14 18:57:24 +0000369 continue;
370 }
371 IsAfterNewline = false;
372 if (Token.is(MIToken::lbrace))
373 ++BraceDepth;
374 if (Token.is(MIToken::rbrace)) {
375 if (!BraceDepth)
376 return error("extraneous closing brace ('}')");
377 --BraceDepth;
378 }
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000379 lex();
380 }
Alex Lorenzf9a2b122015-08-14 18:57:24 +0000381 // Verify that we closed all of the '{' at the end of a file or a block.
382 if (!Token.isError() && BraceDepth)
383 return error("expected '}'"); // FIXME: Report a note that shows '{'.
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000384 } while (!Token.isErrorOrEOF());
385 return Token.isError();
386}
387
388bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
389 assert(Token.is(MIToken::kw_liveins));
390 lex();
391 if (expectAndConsume(MIToken::colon))
392 return true;
393 if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
394 return false;
395 do {
396 if (Token.isNot(MIToken::NamedRegister))
397 return error("expected a named register");
398 unsigned Reg = 0;
399 if (parseRegister(Reg))
400 return true;
401 MBB.addLiveIn(Reg);
402 lex();
403 } while (consumeIfPresent(MIToken::comma));
404 return false;
405}
406
407bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
408 assert(Token.is(MIToken::kw_successors));
409 lex();
410 if (expectAndConsume(MIToken::colon))
411 return true;
412 if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
413 return false;
414 do {
415 if (Token.isNot(MIToken::MachineBasicBlock))
416 return error("expected a machine basic block reference");
417 MachineBasicBlock *SuccMBB = nullptr;
418 if (parseMBBReference(SuccMBB))
419 return true;
420 lex();
421 unsigned Weight = 0;
422 if (consumeIfPresent(MIToken::lparen)) {
423 if (Token.isNot(MIToken::IntegerLiteral))
424 return error("expected an integer literal after '('");
425 if (getUnsigned(Weight))
426 return true;
427 lex();
428 if (expectAndConsume(MIToken::rparen))
429 return true;
430 }
431 MBB.addSuccessor(SuccMBB, Weight);
432 } while (consumeIfPresent(MIToken::comma));
433 return false;
434}
435
436bool MIParser::parseBasicBlock(MachineBasicBlock &MBB) {
437 // Skip the definition.
438 assert(Token.is(MIToken::MachineBasicBlockLabel));
439 lex();
440 if (consumeIfPresent(MIToken::lparen)) {
441 while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
442 lex();
443 consumeIfPresent(MIToken::rparen);
444 }
445 consumeIfPresent(MIToken::colon);
446
447 // Parse the liveins and successors.
448 // N.B: Multiple lists of successors and liveins are allowed and they're
449 // merged into one.
450 // Example:
451 // liveins: %edi
452 // liveins: %esi
453 //
454 // is equivalent to
455 // liveins: %edi, %esi
456 while (true) {
457 if (Token.is(MIToken::kw_successors)) {
458 if (parseBasicBlockSuccessors(MBB))
459 return true;
460 } else if (Token.is(MIToken::kw_liveins)) {
461 if (parseBasicBlockLiveins(MBB))
462 return true;
463 } else if (consumeIfPresent(MIToken::Newline)) {
464 continue;
465 } else
466 break;
467 if (!Token.isNewlineOrEOF())
468 return error("expected line break at the end of a list");
469 lex();
470 }
471
472 // Parse the instructions.
Alex Lorenzf9a2b122015-08-14 18:57:24 +0000473 bool IsInBundle = false;
474 MachineInstr *PrevMI = nullptr;
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000475 while (true) {
476 if (Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof))
477 return false;
478 else if (consumeIfPresent(MIToken::Newline))
479 continue;
Alex Lorenzf9a2b122015-08-14 18:57:24 +0000480 if (consumeIfPresent(MIToken::rbrace)) {
481 // The first parsing pass should verify that all closing '}' have an
482 // opening '{'.
483 assert(IsInBundle);
484 IsInBundle = false;
485 continue;
486 }
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000487 MachineInstr *MI = nullptr;
488 if (parse(MI))
489 return true;
490 MBB.insert(MBB.end(), MI);
Alex Lorenzf9a2b122015-08-14 18:57:24 +0000491 if (IsInBundle) {
492 PrevMI->setFlag(MachineInstr::BundledSucc);
493 MI->setFlag(MachineInstr::BundledPred);
494 }
495 PrevMI = MI;
496 if (Token.is(MIToken::lbrace)) {
497 if (IsInBundle)
498 return error("nested instruction bundles are not allowed");
499 lex();
500 // This instruction is the start of the bundle.
501 MI->setFlag(MachineInstr::BundledSucc);
502 IsInBundle = true;
503 if (!Token.is(MIToken::Newline))
504 // The next instruction can be on the same line.
505 continue;
506 }
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000507 assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
508 lex();
509 }
510 return false;
511}
512
513bool MIParser::parseBasicBlocks() {
514 lex();
515 // Skip until the first machine basic block.
516 while (Token.is(MIToken::Newline))
517 lex();
518 if (Token.isErrorOrEOF())
519 return Token.isError();
520 // The first parsing pass should have verified that this token is a MBB label
521 // in the 'parseBasicBlockDefinitions' method.
522 assert(Token.is(MIToken::MachineBasicBlockLabel));
523 do {
524 MachineBasicBlock *MBB = nullptr;
525 if (parseMBBReference(MBB))
526 return true;
527 if (parseBasicBlock(*MBB))
528 return true;
529 // The method 'parseBasicBlock' should parse the whole block until the next
530 // block or the end of file.
531 assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
532 } while (Token.isNot(MIToken::Eof));
533 return false;
534}
535
536bool MIParser::parse(MachineInstr *&MI) {
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000537 // Parse any register operands before '='
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000538 MachineOperand MO = MachineOperand::CreateImm(0);
Alex Lorenz36962cd2015-07-07 02:08:46 +0000539 SmallVector<MachineOperandWithLocation, 8> Operands;
Alex Lorenzfbe9c042015-07-29 18:51:21 +0000540 while (Token.isRegister() || Token.isRegisterFlag()) {
Alex Lorenz36962cd2015-07-07 02:08:46 +0000541 auto Loc = Token.location();
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000542 if (parseRegisterOperand(MO, /*IsDef=*/true))
Alex Lorenz3708a642015-06-30 17:47:50 +0000543 return true;
Alex Lorenz36962cd2015-07-07 02:08:46 +0000544 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
Alex Lorenzfbe9c042015-07-29 18:51:21 +0000545 if (Token.isNot(MIToken::comma))
546 break;
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000547 lex();
548 }
Alex Lorenzfbe9c042015-07-29 18:51:21 +0000549 if (!Operands.empty() && expectAndConsume(MIToken::equal))
550 return true;
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000551
Alex Lorenze5a44662015-07-17 00:24:15 +0000552 unsigned OpCode, Flags = 0;
553 if (Token.isError() || parseInstruction(OpCode, Flags))
Alex Lorenz3708a642015-06-30 17:47:50 +0000554 return true;
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000555
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000556 // Parse the remaining machine operands.
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000557 while (!Token.isNewlineOrEOF() && Token.isNot(MIToken::kw_debug_location) &&
Alex Lorenzf9a2b122015-08-14 18:57:24 +0000558 Token.isNot(MIToken::coloncolon) && Token.isNot(MIToken::lbrace)) {
Alex Lorenz36962cd2015-07-07 02:08:46 +0000559 auto Loc = Token.location();
Alex Lorenz49873a82015-08-06 00:44:07 +0000560 if (parseMachineOperandAndTargetFlags(MO))
Alex Lorenz3708a642015-06-30 17:47:50 +0000561 return true;
Alex Lorenz36962cd2015-07-07 02:08:46 +0000562 Operands.push_back(MachineOperandWithLocation(MO, Loc, Token.location()));
Alex Lorenzf9a2b122015-08-14 18:57:24 +0000563 if (Token.isNewlineOrEOF() || Token.is(MIToken::coloncolon) ||
564 Token.is(MIToken::lbrace))
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000565 break;
Alex Lorenz3708a642015-06-30 17:47:50 +0000566 if (Token.isNot(MIToken::comma))
567 return error("expected ',' before the next machine operand");
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000568 lex();
569 }
570
Alex Lorenz46d760d2015-07-22 21:15:11 +0000571 DebugLoc DebugLocation;
572 if (Token.is(MIToken::kw_debug_location)) {
573 lex();
574 if (Token.isNot(MIToken::exclaim))
575 return error("expected a metadata node after 'debug-location'");
576 MDNode *Node = nullptr;
577 if (parseMDNode(Node))
578 return true;
579 DebugLocation = DebugLoc(Node);
580 }
581
Alex Lorenz4af7e612015-08-03 23:08:19 +0000582 // Parse the machine memory operands.
583 SmallVector<MachineMemOperand *, 2> MemOperands;
584 if (Token.is(MIToken::coloncolon)) {
585 lex();
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000586 while (!Token.isNewlineOrEOF()) {
Alex Lorenz4af7e612015-08-03 23:08:19 +0000587 MachineMemOperand *MemOp = nullptr;
588 if (parseMachineMemoryOperand(MemOp))
589 return true;
590 MemOperands.push_back(MemOp);
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000591 if (Token.isNewlineOrEOF())
Alex Lorenz4af7e612015-08-03 23:08:19 +0000592 break;
593 if (Token.isNot(MIToken::comma))
594 return error("expected ',' before the next machine memory operand");
595 lex();
596 }
597 }
598
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000599 const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
Alex Lorenz36962cd2015-07-07 02:08:46 +0000600 if (!MCID.isVariadic()) {
601 // FIXME: Move the implicit operand verification to the machine verifier.
602 if (verifyImplicitOperands(Operands, MCID))
603 return true;
604 }
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000605
Alex Lorenzcb268d42015-07-06 23:07:26 +0000606 // TODO: Check for extraneous machine operands.
Alex Lorenz46d760d2015-07-22 21:15:11 +0000607 MI = MF.CreateMachineInstr(MCID, DebugLocation, /*NoImplicit=*/true);
Alex Lorenze5a44662015-07-17 00:24:15 +0000608 MI->setFlags(Flags);
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000609 for (const auto &Operand : Operands)
Alex Lorenz36962cd2015-07-07 02:08:46 +0000610 MI->addOperand(MF, Operand.Operand);
Alex Lorenz4af7e612015-08-03 23:08:19 +0000611 if (MemOperands.empty())
612 return false;
613 MachineInstr::mmo_iterator MemRefs =
614 MF.allocateMemRefsArray(MemOperands.size());
615 std::copy(MemOperands.begin(), MemOperands.end(), MemRefs);
616 MI->setMemRefs(MemRefs, MemRefs + MemOperands.size());
Alex Lorenz3708a642015-06-30 17:47:50 +0000617 return false;
Alex Lorenz8e0a1b42015-06-22 17:02:30 +0000618}
619
Alex Lorenz1ea60892015-07-27 20:29:27 +0000620bool MIParser::parseStandaloneMBB(MachineBasicBlock *&MBB) {
Alex Lorenzf09df002015-06-30 18:16:42 +0000621 lex();
622 if (Token.isNot(MIToken::MachineBasicBlock))
623 return error("expected a machine basic block reference");
624 if (parseMBBReference(MBB))
625 return true;
626 lex();
627 if (Token.isNot(MIToken::Eof))
628 return error(
629 "expected end of string after the machine basic block reference");
630 return false;
631}
632
Alex Lorenz1ea60892015-07-27 20:29:27 +0000633bool MIParser::parseStandaloneNamedRegister(unsigned &Reg) {
Alex Lorenz9fab3702015-07-14 21:24:41 +0000634 lex();
635 if (Token.isNot(MIToken::NamedRegister))
636 return error("expected a named register");
637 if (parseRegister(Reg))
638 return 0;
639 lex();
640 if (Token.isNot(MIToken::Eof))
641 return error("expected end of string after the register reference");
642 return false;
643}
644
Alex Lorenz12045a42015-07-27 17:42:45 +0000645bool MIParser::parseStandaloneVirtualRegister(unsigned &Reg) {
646 lex();
647 if (Token.isNot(MIToken::VirtualRegister))
648 return error("expected a virtual register");
649 if (parseRegister(Reg))
650 return 0;
651 lex();
652 if (Token.isNot(MIToken::Eof))
653 return error("expected end of string after the register reference");
654 return false;
655}
656
Alex Lorenz36962cd2015-07-07 02:08:46 +0000657static const char *printImplicitRegisterFlag(const MachineOperand &MO) {
658 assert(MO.isImplicit());
659 return MO.isDef() ? "implicit-def" : "implicit";
660}
661
662static std::string getRegisterName(const TargetRegisterInfo *TRI,
663 unsigned Reg) {
664 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "expected phys reg");
665 return StringRef(TRI->getName(Reg)).lower();
666}
667
668bool MIParser::verifyImplicitOperands(
669 ArrayRef<MachineOperandWithLocation> Operands, const MCInstrDesc &MCID) {
670 if (MCID.isCall())
671 // We can't verify call instructions as they can contain arbitrary implicit
672 // register and register mask operands.
673 return false;
674
675 // Gather all the expected implicit operands.
676 SmallVector<MachineOperand, 4> ImplicitOperands;
677 if (MCID.ImplicitDefs)
678 for (const uint16_t *ImpDefs = MCID.getImplicitDefs(); *ImpDefs; ++ImpDefs)
679 ImplicitOperands.push_back(
680 MachineOperand::CreateReg(*ImpDefs, true, true));
681 if (MCID.ImplicitUses)
682 for (const uint16_t *ImpUses = MCID.getImplicitUses(); *ImpUses; ++ImpUses)
683 ImplicitOperands.push_back(
684 MachineOperand::CreateReg(*ImpUses, false, true));
685
686 const auto *TRI = MF.getSubtarget().getRegisterInfo();
687 assert(TRI && "Expected target register info");
688 size_t I = ImplicitOperands.size(), J = Operands.size();
689 while (I) {
690 --I;
691 if (J) {
692 --J;
693 const auto &ImplicitOperand = ImplicitOperands[I];
694 const auto &Operand = Operands[J].Operand;
695 if (ImplicitOperand.isIdenticalTo(Operand))
696 continue;
697 if (Operand.isReg() && Operand.isImplicit()) {
698 return error(Operands[J].Begin,
699 Twine("expected an implicit register operand '") +
700 printImplicitRegisterFlag(ImplicitOperand) + " %" +
701 getRegisterName(TRI, ImplicitOperand.getReg()) + "'");
702 }
703 }
704 // TODO: Fix source location when Operands[J].end is right before '=', i.e:
705 // insead of reporting an error at this location:
706 // %eax = MOV32r0
707 // ^
708 // report the error at the following location:
709 // %eax = MOV32r0
710 // ^
711 return error(J < Operands.size() ? Operands[J].End : Token.location(),
712 Twine("missing implicit register operand '") +
713 printImplicitRegisterFlag(ImplicitOperands[I]) + " %" +
714 getRegisterName(TRI, ImplicitOperands[I].getReg()) + "'");
715 }
716 return false;
717}
718
Alex Lorenze5a44662015-07-17 00:24:15 +0000719bool MIParser::parseInstruction(unsigned &OpCode, unsigned &Flags) {
720 if (Token.is(MIToken::kw_frame_setup)) {
721 Flags |= MachineInstr::FrameSetup;
722 lex();
723 }
Alex Lorenz91370c52015-06-22 20:37:46 +0000724 if (Token.isNot(MIToken::Identifier))
725 return error("expected a machine instruction");
726 StringRef InstrName = Token.stringValue();
727 if (parseInstrName(InstrName, OpCode))
728 return error(Twine("unknown machine instruction name '") + InstrName + "'");
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000729 lex();
730 return false;
731}
732
733bool MIParser::parseRegister(unsigned &Reg) {
734 switch (Token.kind()) {
Alex Lorenz12b554e2015-06-24 17:34:58 +0000735 case MIToken::underscore:
736 Reg = 0;
737 break;
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000738 case MIToken::NamedRegister: {
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000739 StringRef Name = Token.stringValue();
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000740 if (getRegisterByName(Name, Reg))
741 return error(Twine("unknown register name '") + Name + "'");
742 break;
743 }
Alex Lorenz53464512015-07-10 22:51:20 +0000744 case MIToken::VirtualRegister: {
745 unsigned ID;
746 if (getUnsigned(ID))
747 return true;
748 const auto RegInfo = PFS.VirtualRegisterSlots.find(ID);
749 if (RegInfo == PFS.VirtualRegisterSlots.end())
750 return error(Twine("use of undefined virtual register '%") + Twine(ID) +
751 "'");
752 Reg = RegInfo->second;
753 break;
754 }
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000755 // TODO: Parse other register kinds.
756 default:
757 llvm_unreachable("The current token should be a register");
758 }
759 return false;
760}
761
Alex Lorenzcb268d42015-07-06 23:07:26 +0000762bool MIParser::parseRegisterFlag(unsigned &Flags) {
Alex Lorenz2b3cf192015-08-05 18:09:03 +0000763 const unsigned OldFlags = Flags;
Alex Lorenzcb268d42015-07-06 23:07:26 +0000764 switch (Token.kind()) {
765 case MIToken::kw_implicit:
766 Flags |= RegState::Implicit;
767 break;
768 case MIToken::kw_implicit_define:
769 Flags |= RegState::ImplicitDefine;
770 break;
Alex Lorenzcbbfd0b2015-07-07 20:34:53 +0000771 case MIToken::kw_dead:
772 Flags |= RegState::Dead;
773 break;
Alex Lorenz495ad872015-07-08 21:23:34 +0000774 case MIToken::kw_killed:
775 Flags |= RegState::Kill;
776 break;
Alex Lorenz4d026b892015-07-08 23:58:31 +0000777 case MIToken::kw_undef:
778 Flags |= RegState::Undef;
779 break;
Alex Lorenz01c1a5e2015-08-05 17:49:03 +0000780 case MIToken::kw_early_clobber:
781 Flags |= RegState::EarlyClobber;
782 break;
Alex Lorenz90752582015-08-05 17:41:17 +0000783 case MIToken::kw_debug_use:
784 Flags |= RegState::Debug;
785 break;
Alex Lorenzcb268d42015-07-06 23:07:26 +0000786 // TODO: parse the other register flags.
787 default:
788 llvm_unreachable("The current token should be a register flag");
789 }
Alex Lorenz2b3cf192015-08-05 18:09:03 +0000790 if (OldFlags == Flags)
791 // We know that the same flag is specified more than once when the flags
792 // weren't modified.
793 return error("duplicate '" + Token.stringValue() + "' register flag");
Alex Lorenzcb268d42015-07-06 23:07:26 +0000794 lex();
795 return false;
796}
797
Alex Lorenz2eacca82015-07-13 23:24:34 +0000798bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
799 assert(Token.is(MIToken::colon));
800 lex();
801 if (Token.isNot(MIToken::Identifier))
802 return error("expected a subregister index after ':'");
803 auto Name = Token.stringValue();
804 SubReg = getSubRegIndex(Name);
805 if (!SubReg)
806 return error(Twine("use of unknown subregister index '") + Name + "'");
807 lex();
808 return false;
809}
810
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000811bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
812 unsigned Reg;
Alex Lorenzcb268d42015-07-06 23:07:26 +0000813 unsigned Flags = IsDef ? RegState::Define : 0;
814 while (Token.isRegisterFlag()) {
815 if (parseRegisterFlag(Flags))
816 return true;
817 }
818 if (!Token.isRegister())
819 return error("expected a register after register flags");
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000820 if (parseRegister(Reg))
821 return true;
822 lex();
Alex Lorenz2eacca82015-07-13 23:24:34 +0000823 unsigned SubReg = 0;
824 if (Token.is(MIToken::colon)) {
825 if (parseSubRegisterIndex(SubReg))
826 return true;
827 }
Alex Lorenz495ad872015-07-08 21:23:34 +0000828 Dest = MachineOperand::CreateReg(
829 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
Alex Lorenz2eacca82015-07-13 23:24:34 +0000830 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
Alex Lorenz01c1a5e2015-08-05 17:49:03 +0000831 Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug);
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000832 return false;
833}
834
Alex Lorenz240fc1e2015-06-23 23:42:28 +0000835bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
836 assert(Token.is(MIToken::IntegerLiteral));
837 const APSInt &Int = Token.integerValue();
838 if (Int.getMinSignedBits() > 64)
Alex Lorenz3f2058d2015-08-05 19:03:42 +0000839 return error("integer literal is too large to be an immediate operand");
Alex Lorenz240fc1e2015-06-23 23:42:28 +0000840 Dest = MachineOperand::CreateImm(Int.getExtValue());
841 lex();
842 return false;
843}
844
Alex Lorenz7eaff4c2015-08-05 18:44:00 +0000845bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
Alex Lorenz3fb77682015-08-06 23:17:42 +0000846 auto Source = StringRef(Loc, Token.range().end() - Loc).str();
Alex Lorenz7eaff4c2015-08-05 18:44:00 +0000847 lex();
848 SMDiagnostic Err;
849 C = parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent());
850 if (!C)
851 return error(Loc + Err.getColumnNo(), Err.getMessage());
852 return false;
853}
854
Alex Lorenz05e38822015-08-05 18:52:21 +0000855bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
856 assert(Token.is(MIToken::IntegerType));
857 auto Loc = Token.location();
858 lex();
859 if (Token.isNot(MIToken::IntegerLiteral))
860 return error("expected an integer literal");
861 const Constant *C = nullptr;
862 if (parseIRConstant(Loc, C))
863 return true;
864 Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C));
865 return false;
866}
867
Alex Lorenzad156fb2015-07-31 20:49:21 +0000868bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
869 auto Loc = Token.location();
870 lex();
871 if (Token.isNot(MIToken::FloatingPointLiteral))
872 return error("expected a floating point literal");
Alex Lorenz7eaff4c2015-08-05 18:44:00 +0000873 const Constant *C = nullptr;
874 if (parseIRConstant(Loc, C))
875 return true;
Alex Lorenzad156fb2015-07-31 20:49:21 +0000876 Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
877 return false;
878}
879
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000880bool MIParser::getUnsigned(unsigned &Result) {
881 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
882 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
883 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
884 if (Val64 == Limit)
885 return error("expected 32-bit integer (too large)");
886 Result = Val64;
887 return false;
888}
889
Alex Lorenzf09df002015-06-30 18:16:42 +0000890bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000891 assert(Token.is(MIToken::MachineBasicBlock) ||
892 Token.is(MIToken::MachineBasicBlockLabel));
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000893 unsigned Number;
894 if (getUnsigned(Number))
895 return true;
Alex Lorenz7a503fa2015-07-07 17:46:43 +0000896 auto MBBInfo = PFS.MBBSlots.find(Number);
897 if (MBBInfo == PFS.MBBSlots.end())
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000898 return error(Twine("use of undefined machine basic block #") +
899 Twine(Number));
Alex Lorenzf09df002015-06-30 18:16:42 +0000900 MBB = MBBInfo->second;
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000901 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
902 return error(Twine("the name of machine basic block #") + Twine(Number) +
903 " isn't '" + Token.stringValue() + "'");
Alex Lorenzf09df002015-06-30 18:16:42 +0000904 return false;
905}
906
907bool MIParser::parseMBBOperand(MachineOperand &Dest) {
908 MachineBasicBlock *MBB;
909 if (parseMBBReference(MBB))
910 return true;
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000911 Dest = MachineOperand::CreateMBB(MBB);
912 lex();
913 return false;
914}
915
Alex Lorenz7feaf7c2015-07-16 23:37:45 +0000916bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
917 assert(Token.is(MIToken::StackObject));
918 unsigned ID;
919 if (getUnsigned(ID))
920 return true;
921 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
922 if (ObjectInfo == PFS.StackObjectSlots.end())
923 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
924 "'");
925 StringRef Name;
926 if (const auto *Alloca =
927 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
928 Name = Alloca->getName();
929 if (!Token.stringValue().empty() && Token.stringValue() != Name)
930 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
931 "' isn't '" + Token.stringValue() + "'");
932 lex();
933 Dest = MachineOperand::CreateFI(ObjectInfo->second);
934 return false;
935}
936
Alex Lorenzea882122015-08-12 21:17:02 +0000937bool MIParser::parseFixedStackFrameIndex(int &FI) {
Alex Lorenz7feaf7c2015-07-16 23:37:45 +0000938 assert(Token.is(MIToken::FixedStackObject));
939 unsigned ID;
940 if (getUnsigned(ID))
941 return true;
942 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
943 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
944 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
945 Twine(ID) + "'");
946 lex();
Alex Lorenzea882122015-08-12 21:17:02 +0000947 FI = ObjectInfo->second;
948 return false;
949}
950
951bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
952 int FI;
953 if (parseFixedStackFrameIndex(FI))
954 return true;
955 Dest = MachineOperand::CreateFI(FI);
Alex Lorenz7feaf7c2015-07-16 23:37:45 +0000956 return false;
957}
958
Alex Lorenz41df7d32015-07-28 17:09:52 +0000959bool MIParser::parseGlobalValue(GlobalValue *&GV) {
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000960 switch (Token.kind()) {
Alex Lorenz970c12e2015-08-05 17:35:55 +0000961 case MIToken::NamedGlobalValue: {
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000962 const Module *M = MF.getFunction()->getParent();
Alex Lorenz970c12e2015-08-05 17:35:55 +0000963 GV = M->getNamedValue(Token.stringValue());
Alex Lorenz41df7d32015-07-28 17:09:52 +0000964 if (!GV)
Alex Lorenz3fb77682015-08-06 23:17:42 +0000965 return error(Twine("use of undefined global value '") + Token.range() +
966 "'");
Alex Lorenz41df7d32015-07-28 17:09:52 +0000967 break;
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000968 }
969 case MIToken::GlobalValue: {
970 unsigned GVIdx;
971 if (getUnsigned(GVIdx))
972 return true;
973 if (GVIdx >= IRSlots.GlobalValues.size())
974 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
975 "'");
Alex Lorenz41df7d32015-07-28 17:09:52 +0000976 GV = IRSlots.GlobalValues[GVIdx];
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000977 break;
978 }
979 default:
980 llvm_unreachable("The current token should be a global value");
981 }
Alex Lorenz41df7d32015-07-28 17:09:52 +0000982 return false;
983}
984
985bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
986 GlobalValue *GV = nullptr;
987 if (parseGlobalValue(GV))
988 return true;
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000989 lex();
Alex Lorenz5672a892015-08-05 22:26:15 +0000990 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
Alex Lorenz5672a892015-08-05 22:26:15 +0000991 if (parseOperandsOffset(Dest))
992 return true;
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000993 return false;
994}
995
Alex Lorenzab980492015-07-20 20:51:18 +0000996bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
997 assert(Token.is(MIToken::ConstantPoolItem));
998 unsigned ID;
999 if (getUnsigned(ID))
1000 return true;
1001 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
1002 if (ConstantInfo == PFS.ConstantPoolSlots.end())
1003 return error("use of undefined constant '%const." + Twine(ID) + "'");
1004 lex();
Alex Lorenzab980492015-07-20 20:51:18 +00001005 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
Alex Lorenz5672a892015-08-05 22:26:15 +00001006 if (parseOperandsOffset(Dest))
1007 return true;
Alex Lorenzab980492015-07-20 20:51:18 +00001008 return false;
1009}
1010
Alex Lorenz31d70682015-07-15 23:38:35 +00001011bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
1012 assert(Token.is(MIToken::JumpTableIndex));
1013 unsigned ID;
1014 if (getUnsigned(ID))
1015 return true;
1016 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
1017 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
1018 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
1019 lex();
Alex Lorenz31d70682015-07-15 23:38:35 +00001020 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
1021 return false;
1022}
1023
Alex Lorenz6ede3742015-07-21 16:59:53 +00001024bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
Alex Lorenz970c12e2015-08-05 17:35:55 +00001025 assert(Token.is(MIToken::ExternalSymbol));
1026 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
Alex Lorenz6ede3742015-07-21 16:59:53 +00001027 lex();
Alex Lorenz6ede3742015-07-21 16:59:53 +00001028 Dest = MachineOperand::CreateES(Symbol);
Alex Lorenz5672a892015-08-05 22:26:15 +00001029 if (parseOperandsOffset(Dest))
1030 return true;
Alex Lorenz6ede3742015-07-21 16:59:53 +00001031 return false;
1032}
1033
Alex Lorenz44f29252015-07-22 21:07:04 +00001034bool MIParser::parseMDNode(MDNode *&Node) {
Alex Lorenz35e44462015-07-22 17:58:46 +00001035 assert(Token.is(MIToken::exclaim));
1036 auto Loc = Token.location();
1037 lex();
1038 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1039 return error("expected metadata id after '!'");
1040 unsigned ID;
1041 if (getUnsigned(ID))
1042 return true;
1043 auto NodeInfo = IRSlots.MetadataNodes.find(ID);
1044 if (NodeInfo == IRSlots.MetadataNodes.end())
1045 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
1046 lex();
Alex Lorenz44f29252015-07-22 21:07:04 +00001047 Node = NodeInfo->second.get();
1048 return false;
1049}
1050
1051bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
1052 MDNode *Node = nullptr;
1053 if (parseMDNode(Node))
1054 return true;
1055 Dest = MachineOperand::CreateMetadata(Node);
Alex Lorenz35e44462015-07-22 17:58:46 +00001056 return false;
1057}
1058
Alex Lorenzf4baeb52015-07-21 22:28:27 +00001059bool MIParser::parseCFIOffset(int &Offset) {
1060 if (Token.isNot(MIToken::IntegerLiteral))
1061 return error("expected a cfi offset");
1062 if (Token.integerValue().getMinSignedBits() > 32)
1063 return error("expected a 32 bit integer (the cfi offset is too large)");
1064 Offset = (int)Token.integerValue().getExtValue();
1065 lex();
1066 return false;
1067}
1068
Alex Lorenz8cfc6862015-07-23 23:09:07 +00001069bool MIParser::parseCFIRegister(unsigned &Reg) {
1070 if (Token.isNot(MIToken::NamedRegister))
1071 return error("expected a cfi register");
1072 unsigned LLVMReg;
1073 if (parseRegister(LLVMReg))
Alex Lorenzf4baeb52015-07-21 22:28:27 +00001074 return true;
Alex Lorenz8cfc6862015-07-23 23:09:07 +00001075 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1076 assert(TRI && "Expected target register info");
1077 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
1078 if (DwarfReg < 0)
1079 return error("invalid DWARF register");
1080 Reg = (unsigned)DwarfReg;
1081 lex();
1082 return false;
1083}
1084
1085bool MIParser::parseCFIOperand(MachineOperand &Dest) {
1086 auto Kind = Token.kind();
1087 lex();
1088 auto &MMI = MF.getMMI();
1089 int Offset;
1090 unsigned Reg;
1091 unsigned CFIIndex;
1092 switch (Kind) {
1093 case MIToken::kw_cfi_offset:
1094 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1095 parseCFIOffset(Offset))
1096 return true;
1097 CFIIndex =
1098 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
1099 break;
Alex Lorenz5b0d5f62015-07-27 20:39:03 +00001100 case MIToken::kw_cfi_def_cfa_register:
1101 if (parseCFIRegister(Reg))
1102 return true;
1103 CFIIndex =
1104 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
1105 break;
Alex Lorenz8cfc6862015-07-23 23:09:07 +00001106 case MIToken::kw_cfi_def_cfa_offset:
1107 if (parseCFIOffset(Offset))
1108 return true;
1109 // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
1110 CFIIndex = MMI.addFrameInst(
1111 MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
1112 break;
Alex Lorenzb1393232015-07-29 18:57:23 +00001113 case MIToken::kw_cfi_def_cfa:
1114 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1115 parseCFIOffset(Offset))
1116 return true;
1117 // NB: MCCFIInstruction::createDefCfa negates the offset.
1118 CFIIndex =
1119 MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
1120 break;
Alex Lorenz8cfc6862015-07-23 23:09:07 +00001121 default:
1122 // TODO: Parse the other CFI operands.
1123 llvm_unreachable("The current token should be a cfi operand");
1124 }
1125 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
Alex Lorenzf4baeb52015-07-21 22:28:27 +00001126 return false;
1127}
1128
Alex Lorenzdeb53492015-07-28 17:28:03 +00001129bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
1130 switch (Token.kind()) {
Alex Lorenz970c12e2015-08-05 17:35:55 +00001131 case MIToken::NamedIRBlock: {
1132 BB = dyn_cast_or_null<BasicBlock>(
1133 F.getValueSymbolTable().lookup(Token.stringValue()));
Alex Lorenzdeb53492015-07-28 17:28:03 +00001134 if (!BB)
Alex Lorenz3fb77682015-08-06 23:17:42 +00001135 return error(Twine("use of undefined IR block '") + Token.range() + "'");
Alex Lorenzdeb53492015-07-28 17:28:03 +00001136 break;
1137 }
1138 case MIToken::IRBlock: {
1139 unsigned SlotNumber = 0;
1140 if (getUnsigned(SlotNumber))
1141 return true;
Alex Lorenzcba8c5f2015-08-06 23:57:04 +00001142 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
Alex Lorenzdeb53492015-07-28 17:28:03 +00001143 if (!BB)
1144 return error(Twine("use of undefined IR block '%ir-block.") +
1145 Twine(SlotNumber) + "'");
1146 break;
1147 }
1148 default:
1149 llvm_unreachable("The current token should be an IR block reference");
1150 }
1151 return false;
1152}
1153
1154bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
1155 assert(Token.is(MIToken::kw_blockaddress));
1156 lex();
1157 if (expectAndConsume(MIToken::lparen))
1158 return true;
1159 if (Token.isNot(MIToken::GlobalValue) &&
Alex Lorenz970c12e2015-08-05 17:35:55 +00001160 Token.isNot(MIToken::NamedGlobalValue))
Alex Lorenzdeb53492015-07-28 17:28:03 +00001161 return error("expected a global value");
1162 GlobalValue *GV = nullptr;
1163 if (parseGlobalValue(GV))
1164 return true;
1165 auto *F = dyn_cast<Function>(GV);
1166 if (!F)
1167 return error("expected an IR function reference");
1168 lex();
1169 if (expectAndConsume(MIToken::comma))
1170 return true;
1171 BasicBlock *BB = nullptr;
Alex Lorenz970c12e2015-08-05 17:35:55 +00001172 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
Alex Lorenzdeb53492015-07-28 17:28:03 +00001173 return error("expected an IR block reference");
1174 if (parseIRBlock(BB, *F))
1175 return true;
1176 lex();
1177 if (expectAndConsume(MIToken::rparen))
1178 return true;
Alex Lorenzdeb53492015-07-28 17:28:03 +00001179 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
Alex Lorenz5672a892015-08-05 22:26:15 +00001180 if (parseOperandsOffset(Dest))
1181 return true;
Alex Lorenzdeb53492015-07-28 17:28:03 +00001182 return false;
1183}
1184
Alex Lorenzef5c1962015-07-28 23:02:45 +00001185bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
1186 assert(Token.is(MIToken::kw_target_index));
1187 lex();
1188 if (expectAndConsume(MIToken::lparen))
1189 return true;
1190 if (Token.isNot(MIToken::Identifier))
1191 return error("expected the name of the target index");
1192 int Index = 0;
1193 if (getTargetIndex(Token.stringValue(), Index))
1194 return error("use of undefined target index '" + Token.stringValue() + "'");
1195 lex();
1196 if (expectAndConsume(MIToken::rparen))
1197 return true;
Alex Lorenzef5c1962015-07-28 23:02:45 +00001198 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
Alex Lorenz5672a892015-08-05 22:26:15 +00001199 if (parseOperandsOffset(Dest))
1200 return true;
Alex Lorenzef5c1962015-07-28 23:02:45 +00001201 return false;
1202}
1203
Alex Lorenzb97c9ef2015-08-10 23:24:42 +00001204bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
1205 assert(Token.is(MIToken::kw_liveout));
1206 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1207 assert(TRI && "Expected target register info");
1208 uint32_t *Mask = MF.allocateRegisterMask(TRI->getNumRegs());
1209 lex();
1210 if (expectAndConsume(MIToken::lparen))
1211 return true;
1212 while (true) {
1213 if (Token.isNot(MIToken::NamedRegister))
1214 return error("expected a named register");
1215 unsigned Reg = 0;
1216 if (parseRegister(Reg))
1217 return true;
1218 lex();
1219 Mask[Reg / 32] |= 1U << (Reg % 32);
1220 // TODO: Report an error if the same register is used more than once.
1221 if (Token.isNot(MIToken::comma))
1222 break;
1223 lex();
1224 }
1225 if (expectAndConsume(MIToken::rparen))
1226 return true;
1227 Dest = MachineOperand::CreateRegLiveOut(Mask);
1228 return false;
1229}
1230
Alex Lorenzf3db51de2015-06-23 16:35:26 +00001231bool MIParser::parseMachineOperand(MachineOperand &Dest) {
1232 switch (Token.kind()) {
Alex Lorenzcb268d42015-07-06 23:07:26 +00001233 case MIToken::kw_implicit:
1234 case MIToken::kw_implicit_define:
Alex Lorenzcbbfd0b2015-07-07 20:34:53 +00001235 case MIToken::kw_dead:
Alex Lorenz495ad872015-07-08 21:23:34 +00001236 case MIToken::kw_killed:
Alex Lorenz4d026b892015-07-08 23:58:31 +00001237 case MIToken::kw_undef:
Alex Lorenz01c1a5e2015-08-05 17:49:03 +00001238 case MIToken::kw_early_clobber:
Alex Lorenz90752582015-08-05 17:41:17 +00001239 case MIToken::kw_debug_use:
Alex Lorenz12b554e2015-06-24 17:34:58 +00001240 case MIToken::underscore:
Alex Lorenzf3db51de2015-06-23 16:35:26 +00001241 case MIToken::NamedRegister:
Alex Lorenz53464512015-07-10 22:51:20 +00001242 case MIToken::VirtualRegister:
Alex Lorenzf3db51de2015-06-23 16:35:26 +00001243 return parseRegisterOperand(Dest);
Alex Lorenz240fc1e2015-06-23 23:42:28 +00001244 case MIToken::IntegerLiteral:
1245 return parseImmediateOperand(Dest);
Alex Lorenz05e38822015-08-05 18:52:21 +00001246 case MIToken::IntegerType:
1247 return parseTypedImmediateOperand(Dest);
Alex Lorenzad156fb2015-07-31 20:49:21 +00001248 case MIToken::kw_half:
1249 case MIToken::kw_float:
1250 case MIToken::kw_double:
1251 case MIToken::kw_x86_fp80:
1252 case MIToken::kw_fp128:
1253 case MIToken::kw_ppc_fp128:
1254 return parseFPImmediateOperand(Dest);
Alex Lorenz33f0aef2015-06-26 16:46:11 +00001255 case MIToken::MachineBasicBlock:
1256 return parseMBBOperand(Dest);
Alex Lorenz7feaf7c2015-07-16 23:37:45 +00001257 case MIToken::StackObject:
1258 return parseStackObjectOperand(Dest);
1259 case MIToken::FixedStackObject:
1260 return parseFixedStackObjectOperand(Dest);
Alex Lorenz5d6108e2015-06-26 22:56:48 +00001261 case MIToken::GlobalValue:
1262 case MIToken::NamedGlobalValue:
1263 return parseGlobalAddressOperand(Dest);
Alex Lorenzab980492015-07-20 20:51:18 +00001264 case MIToken::ConstantPoolItem:
1265 return parseConstantPoolIndexOperand(Dest);
Alex Lorenz31d70682015-07-15 23:38:35 +00001266 case MIToken::JumpTableIndex:
1267 return parseJumpTableIndexOperand(Dest);
Alex Lorenz6ede3742015-07-21 16:59:53 +00001268 case MIToken::ExternalSymbol:
Alex Lorenz6ede3742015-07-21 16:59:53 +00001269 return parseExternalSymbolOperand(Dest);
Alex Lorenz35e44462015-07-22 17:58:46 +00001270 case MIToken::exclaim:
1271 return parseMetadataOperand(Dest);
Alex Lorenz8cfc6862015-07-23 23:09:07 +00001272 case MIToken::kw_cfi_offset:
Alex Lorenz5b0d5f62015-07-27 20:39:03 +00001273 case MIToken::kw_cfi_def_cfa_register:
Alex Lorenzf4baeb52015-07-21 22:28:27 +00001274 case MIToken::kw_cfi_def_cfa_offset:
Alex Lorenzb1393232015-07-29 18:57:23 +00001275 case MIToken::kw_cfi_def_cfa:
Alex Lorenzf4baeb52015-07-21 22:28:27 +00001276 return parseCFIOperand(Dest);
Alex Lorenzdeb53492015-07-28 17:28:03 +00001277 case MIToken::kw_blockaddress:
1278 return parseBlockAddressOperand(Dest);
Alex Lorenzef5c1962015-07-28 23:02:45 +00001279 case MIToken::kw_target_index:
1280 return parseTargetIndexOperand(Dest);
Alex Lorenzb97c9ef2015-08-10 23:24:42 +00001281 case MIToken::kw_liveout:
1282 return parseLiveoutRegisterMaskOperand(Dest);
Alex Lorenzf3db51de2015-06-23 16:35:26 +00001283 case MIToken::Error:
1284 return true;
Alex Lorenz8f6f4282015-06-29 16:57:06 +00001285 case MIToken::Identifier:
1286 if (const auto *RegMask = getRegMask(Token.stringValue())) {
1287 Dest = MachineOperand::CreateRegMask(RegMask);
1288 lex();
1289 break;
1290 }
1291 // fallthrough
Alex Lorenzf3db51de2015-06-23 16:35:26 +00001292 default:
1293 // TODO: parse the other machine operands.
1294 return error("expected a machine operand");
1295 }
Alex Lorenz91370c52015-06-22 20:37:46 +00001296 return false;
1297}
1298
Alex Lorenz49873a82015-08-06 00:44:07 +00001299bool MIParser::parseMachineOperandAndTargetFlags(MachineOperand &Dest) {
1300 unsigned TF = 0;
1301 bool HasTargetFlags = false;
1302 if (Token.is(MIToken::kw_target_flags)) {
1303 HasTargetFlags = true;
1304 lex();
1305 if (expectAndConsume(MIToken::lparen))
1306 return true;
1307 if (Token.isNot(MIToken::Identifier))
1308 return error("expected the name of the target flag");
1309 if (getDirectTargetFlag(Token.stringValue(), TF))
1310 return error("use of undefined target flag '" + Token.stringValue() +
1311 "'");
1312 lex();
1313 // TODO: Parse target's bit target flags.
1314 if (expectAndConsume(MIToken::rparen))
1315 return true;
1316 }
1317 auto Loc = Token.location();
1318 if (parseMachineOperand(Dest))
1319 return true;
1320 if (!HasTargetFlags)
1321 return false;
1322 if (Dest.isReg())
1323 return error(Loc, "register operands can't have target flags");
1324 Dest.setTargetFlags(TF);
1325 return false;
1326}
1327
Alex Lorenzdc24c172015-08-07 20:21:00 +00001328bool MIParser::parseOffset(int64_t &Offset) {
Alex Lorenz5672a892015-08-05 22:26:15 +00001329 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
1330 return false;
Alex Lorenz3fb77682015-08-06 23:17:42 +00001331 StringRef Sign = Token.range();
Alex Lorenz5672a892015-08-05 22:26:15 +00001332 bool IsNegative = Token.is(MIToken::minus);
1333 lex();
1334 if (Token.isNot(MIToken::IntegerLiteral))
1335 return error("expected an integer literal after '" + Sign + "'");
1336 if (Token.integerValue().getMinSignedBits() > 64)
1337 return error("expected 64-bit integer (too large)");
Alex Lorenzdc24c172015-08-07 20:21:00 +00001338 Offset = Token.integerValue().getExtValue();
Alex Lorenz5672a892015-08-05 22:26:15 +00001339 if (IsNegative)
1340 Offset = -Offset;
1341 lex();
Alex Lorenzdc24c172015-08-07 20:21:00 +00001342 return false;
1343}
1344
Alex Lorenz620f8912015-08-13 20:33:33 +00001345bool MIParser::parseAlignment(unsigned &Alignment) {
1346 assert(Token.is(MIToken::kw_align));
1347 lex();
Alex Lorenz68661042015-08-13 20:55:01 +00001348 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
Alex Lorenz620f8912015-08-13 20:33:33 +00001349 return error("expected an integer literal after 'align'");
1350 if (getUnsigned(Alignment))
1351 return true;
1352 lex();
1353 return false;
1354}
1355
Alex Lorenzdc24c172015-08-07 20:21:00 +00001356bool MIParser::parseOperandsOffset(MachineOperand &Op) {
1357 int64_t Offset = 0;
1358 if (parseOffset(Offset))
1359 return true;
Alex Lorenz5672a892015-08-05 22:26:15 +00001360 Op.setOffset(Offset);
1361 return false;
1362}
1363
Alex Lorenz4af7e612015-08-03 23:08:19 +00001364bool MIParser::parseIRValue(Value *&V) {
1365 switch (Token.kind()) {
Alex Lorenz970c12e2015-08-05 17:35:55 +00001366 case MIToken::NamedIRValue: {
1367 V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue());
Alex Lorenz4af7e612015-08-03 23:08:19 +00001368 if (!V)
Alex Lorenz2791dcc2015-08-12 21:27:16 +00001369 V = MF.getFunction()->getParent()->getValueSymbolTable().lookup(
1370 Token.stringValue());
1371 if (!V)
Alex Lorenz3fb77682015-08-06 23:17:42 +00001372 return error(Twine("use of undefined IR value '") + Token.range() + "'");
Alex Lorenz4af7e612015-08-03 23:08:19 +00001373 break;
1374 }
1375 // TODO: Parse unnamed IR value references.
1376 default:
1377 llvm_unreachable("The current token should be an IR block reference");
1378 }
1379 return false;
1380}
1381
1382bool MIParser::getUint64(uint64_t &Result) {
1383 assert(Token.hasIntegerValue());
1384 if (Token.integerValue().getActiveBits() > 64)
1385 return error("expected 64-bit integer (too large)");
1386 Result = Token.integerValue().getZExtValue();
1387 return false;
1388}
1389
Alex Lorenza518b792015-08-04 00:24:45 +00001390bool MIParser::parseMemoryOperandFlag(unsigned &Flags) {
Alex Lorenze86d5152015-08-06 18:26:36 +00001391 const unsigned OldFlags = Flags;
Alex Lorenza518b792015-08-04 00:24:45 +00001392 switch (Token.kind()) {
1393 case MIToken::kw_volatile:
1394 Flags |= MachineMemOperand::MOVolatile;
1395 break;
Alex Lorenz10fd0382015-08-06 16:49:30 +00001396 case MIToken::kw_non_temporal:
1397 Flags |= MachineMemOperand::MONonTemporal;
1398 break;
Alex Lorenzdc8de2a2015-08-06 16:55:53 +00001399 case MIToken::kw_invariant:
1400 Flags |= MachineMemOperand::MOInvariant;
1401 break;
Alex Lorenzdc8de2a2015-08-06 16:55:53 +00001402 // TODO: parse the target specific memory operand flags.
Alex Lorenza518b792015-08-04 00:24:45 +00001403 default:
1404 llvm_unreachable("The current token should be a memory operand flag");
1405 }
Alex Lorenze86d5152015-08-06 18:26:36 +00001406 if (OldFlags == Flags)
1407 // We know that the same flag is specified more than once when the flags
1408 // weren't modified.
1409 return error("duplicate '" + Token.stringValue() + "' memory operand flag");
Alex Lorenza518b792015-08-04 00:24:45 +00001410 lex();
1411 return false;
1412}
1413
Alex Lorenz91097a32015-08-12 20:33:26 +00001414bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
1415 switch (Token.kind()) {
Alex Lorenz46e95582015-08-12 20:44:16 +00001416 case MIToken::kw_stack:
1417 PSV = MF.getPSVManager().getStack();
1418 break;
Alex Lorenzd858f872015-08-12 21:00:22 +00001419 case MIToken::kw_got:
1420 PSV = MF.getPSVManager().getGOT();
1421 break;
Alex Lorenz4be56e92015-08-12 21:11:08 +00001422 case MIToken::kw_jump_table:
1423 PSV = MF.getPSVManager().getJumpTable();
1424 break;
Alex Lorenz91097a32015-08-12 20:33:26 +00001425 case MIToken::kw_constant_pool:
1426 PSV = MF.getPSVManager().getConstantPool();
1427 break;
Alex Lorenz0cc671b2015-08-12 21:23:17 +00001428 case MIToken::FixedStackObject: {
1429 int FI;
1430 if (parseFixedStackFrameIndex(FI))
1431 return true;
1432 PSV = MF.getPSVManager().getFixedStack(FI);
1433 // The token was already consumed, so use return here instead of break.
1434 return false;
1435 }
Alex Lorenz91097a32015-08-12 20:33:26 +00001436 // TODO: Parse the other pseudo source values.
1437 default:
1438 llvm_unreachable("The current token should be pseudo source value");
1439 }
1440 lex();
1441 return false;
1442}
1443
1444bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
Alex Lorenzd858f872015-08-12 21:00:22 +00001445 if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
Alex Lorenz0cc671b2015-08-12 21:23:17 +00001446 Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
1447 Token.is(MIToken::FixedStackObject)) {
Alex Lorenz91097a32015-08-12 20:33:26 +00001448 const PseudoSourceValue *PSV = nullptr;
1449 if (parseMemoryPseudoSourceValue(PSV))
1450 return true;
1451 int64_t Offset = 0;
1452 if (parseOffset(Offset))
1453 return true;
1454 Dest = MachinePointerInfo(PSV, Offset);
1455 return false;
1456 }
1457 if (Token.isNot(MIToken::NamedIRValue))
1458 return error("expected an IR value reference");
1459 Value *V = nullptr;
1460 if (parseIRValue(V))
1461 return true;
1462 if (!V->getType()->isPointerTy())
1463 return error("expected a pointer IR value");
1464 lex();
1465 int64_t Offset = 0;
1466 if (parseOffset(Offset))
1467 return true;
1468 Dest = MachinePointerInfo(V, Offset);
1469 return false;
1470}
1471
Alex Lorenz4af7e612015-08-03 23:08:19 +00001472bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
1473 if (expectAndConsume(MIToken::lparen))
1474 return true;
Alex Lorenza518b792015-08-04 00:24:45 +00001475 unsigned Flags = 0;
1476 while (Token.isMemoryOperandFlag()) {
1477 if (parseMemoryOperandFlag(Flags))
1478 return true;
1479 }
Alex Lorenz4af7e612015-08-03 23:08:19 +00001480 if (Token.isNot(MIToken::Identifier) ||
1481 (Token.stringValue() != "load" && Token.stringValue() != "store"))
1482 return error("expected 'load' or 'store' memory operation");
Alex Lorenz4af7e612015-08-03 23:08:19 +00001483 if (Token.stringValue() == "load")
1484 Flags |= MachineMemOperand::MOLoad;
1485 else
1486 Flags |= MachineMemOperand::MOStore;
1487 lex();
1488
1489 if (Token.isNot(MIToken::IntegerLiteral))
1490 return error("expected the size integer literal after memory operation");
1491 uint64_t Size;
1492 if (getUint64(Size))
1493 return true;
1494 lex();
1495
1496 const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
1497 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != Word)
1498 return error(Twine("expected '") + Word + "'");
1499 lex();
1500
Alex Lorenz91097a32015-08-12 20:33:26 +00001501 MachinePointerInfo Ptr = MachinePointerInfo();
1502 if (parseMachinePointerInfo(Ptr))
Alex Lorenz83127732015-08-07 20:26:52 +00001503 return true;
Alex Lorenz61420f72015-08-07 20:48:30 +00001504 unsigned BaseAlignment = Size;
1505 if (Token.is(MIToken::comma)) {
1506 lex();
1507 if (Token.isNot(MIToken::kw_align))
1508 return error("expected 'align'");
Alex Lorenz620f8912015-08-13 20:33:33 +00001509 if (parseAlignment(BaseAlignment))
Alex Lorenz61420f72015-08-07 20:48:30 +00001510 return true;
Alex Lorenz61420f72015-08-07 20:48:30 +00001511 }
Alex Lorenz4af7e612015-08-03 23:08:19 +00001512 // TODO: Parse the attached metadata nodes.
1513 if (expectAndConsume(MIToken::rparen))
1514 return true;
Alex Lorenz91097a32015-08-12 20:33:26 +00001515 Dest = MF.getMachineMemOperand(Ptr, Flags, Size, BaseAlignment);
Alex Lorenz4af7e612015-08-03 23:08:19 +00001516 return false;
1517}
1518
Alex Lorenz8e0a1b42015-06-22 17:02:30 +00001519void MIParser::initNames2InstrOpCodes() {
1520 if (!Names2InstrOpCodes.empty())
1521 return;
1522 const auto *TII = MF.getSubtarget().getInstrInfo();
1523 assert(TII && "Expected target instruction info");
1524 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
1525 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
1526}
1527
1528bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
1529 initNames2InstrOpCodes();
1530 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
1531 if (InstrInfo == Names2InstrOpCodes.end())
1532 return true;
1533 OpCode = InstrInfo->getValue();
1534 return false;
1535}
1536
Alex Lorenzf3db51de2015-06-23 16:35:26 +00001537void MIParser::initNames2Regs() {
1538 if (!Names2Regs.empty())
1539 return;
Alex Lorenz12b554e2015-06-24 17:34:58 +00001540 // The '%noreg' register is the register 0.
1541 Names2Regs.insert(std::make_pair("noreg", 0));
Alex Lorenzf3db51de2015-06-23 16:35:26 +00001542 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1543 assert(TRI && "Expected target register info");
1544 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
1545 bool WasInserted =
1546 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
1547 .second;
1548 (void)WasInserted;
1549 assert(WasInserted && "Expected registers to be unique case-insensitively");
1550 }
1551}
1552
1553bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
1554 initNames2Regs();
1555 auto RegInfo = Names2Regs.find(RegName);
1556 if (RegInfo == Names2Regs.end())
1557 return true;
1558 Reg = RegInfo->getValue();
1559 return false;
1560}
1561
Alex Lorenz8f6f4282015-06-29 16:57:06 +00001562void MIParser::initNames2RegMasks() {
1563 if (!Names2RegMasks.empty())
1564 return;
1565 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1566 assert(TRI && "Expected target register info");
1567 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
1568 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
1569 assert(RegMasks.size() == RegMaskNames.size());
1570 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
1571 Names2RegMasks.insert(
1572 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
1573}
1574
1575const uint32_t *MIParser::getRegMask(StringRef Identifier) {
1576 initNames2RegMasks();
1577 auto RegMaskInfo = Names2RegMasks.find(Identifier);
1578 if (RegMaskInfo == Names2RegMasks.end())
1579 return nullptr;
1580 return RegMaskInfo->getValue();
1581}
1582
Alex Lorenz2eacca82015-07-13 23:24:34 +00001583void MIParser::initNames2SubRegIndices() {
1584 if (!Names2SubRegIndices.empty())
1585 return;
1586 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1587 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1588 Names2SubRegIndices.insert(
1589 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1590}
1591
1592unsigned MIParser::getSubRegIndex(StringRef Name) {
1593 initNames2SubRegIndices();
1594 auto SubRegInfo = Names2SubRegIndices.find(Name);
1595 if (SubRegInfo == Names2SubRegIndices.end())
1596 return 0;
1597 return SubRegInfo->getValue();
1598}
1599
Alex Lorenzcba8c5f2015-08-06 23:57:04 +00001600static void initSlots2BasicBlocks(
1601 const Function &F,
1602 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1603 ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
Alex Lorenz8a1915b2015-07-27 22:42:41 +00001604 MST.incorporateFunction(F);
1605 for (auto &BB : F) {
1606 if (BB.hasName())
1607 continue;
1608 int Slot = MST.getLocalSlot(&BB);
1609 if (Slot == -1)
1610 continue;
1611 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1612 }
1613}
1614
Alex Lorenzcba8c5f2015-08-06 23:57:04 +00001615static const BasicBlock *getIRBlockFromSlot(
1616 unsigned Slot,
1617 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
Alex Lorenz8a1915b2015-07-27 22:42:41 +00001618 auto BlockInfo = Slots2BasicBlocks.find(Slot);
1619 if (BlockInfo == Slots2BasicBlocks.end())
1620 return nullptr;
1621 return BlockInfo->second;
1622}
1623
Alex Lorenzcba8c5f2015-08-06 23:57:04 +00001624const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1625 if (Slots2BasicBlocks.empty())
1626 initSlots2BasicBlocks(*MF.getFunction(), Slots2BasicBlocks);
1627 return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
1628}
1629
1630const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
1631 if (&F == MF.getFunction())
1632 return getIRBlock(Slot);
1633 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
1634 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
1635 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
1636}
1637
Alex Lorenzef5c1962015-07-28 23:02:45 +00001638void MIParser::initNames2TargetIndices() {
1639 if (!Names2TargetIndices.empty())
1640 return;
1641 const auto *TII = MF.getSubtarget().getInstrInfo();
1642 assert(TII && "Expected target instruction info");
1643 auto Indices = TII->getSerializableTargetIndices();
1644 for (const auto &I : Indices)
1645 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
1646}
1647
1648bool MIParser::getTargetIndex(StringRef Name, int &Index) {
1649 initNames2TargetIndices();
1650 auto IndexInfo = Names2TargetIndices.find(Name);
1651 if (IndexInfo == Names2TargetIndices.end())
1652 return true;
1653 Index = IndexInfo->second;
1654 return false;
1655}
1656
Alex Lorenz49873a82015-08-06 00:44:07 +00001657void MIParser::initNames2DirectTargetFlags() {
1658 if (!Names2DirectTargetFlags.empty())
1659 return;
1660 const auto *TII = MF.getSubtarget().getInstrInfo();
1661 assert(TII && "Expected target instruction info");
1662 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
1663 for (const auto &I : Flags)
1664 Names2DirectTargetFlags.insert(
1665 std::make_pair(StringRef(I.second), I.first));
1666}
1667
1668bool MIParser::getDirectTargetFlag(StringRef Name, unsigned &Flag) {
1669 initNames2DirectTargetFlags();
1670 auto FlagInfo = Names2DirectTargetFlags.find(Name);
1671 if (FlagInfo == Names2DirectTargetFlags.end())
1672 return true;
1673 Flag = FlagInfo->second;
1674 return false;
1675}
1676
Alex Lorenz5022f6b2015-08-13 23:10:16 +00001677bool llvm::parseMachineBasicBlockDefinitions(MachineFunction &MF, StringRef Src,
1678 PerFunctionMIParsingState &PFS,
1679 const SlotMapping &IRSlots,
1680 SMDiagnostic &Error) {
1681 SourceMgr SM;
1682 SM.AddNewSourceBuffer(
1683 MemoryBuffer::getMemBuffer(Src, "", /*RequiresNullTerminator=*/false),
1684 SMLoc());
1685 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1686 .parseBasicBlockDefinitions(PFS.MBBSlots);
1687}
1688
1689bool llvm::parseMachineInstructions(MachineFunction &MF, StringRef Src,
1690 const PerFunctionMIParsingState &PFS,
1691 const SlotMapping &IRSlots,
1692 SMDiagnostic &Error) {
1693 SourceMgr SM;
1694 SM.AddNewSourceBuffer(
1695 MemoryBuffer::getMemBuffer(Src, "", /*RequiresNullTerminator=*/false),
1696 SMLoc());
1697 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseBasicBlocks();
Alex Lorenz8e0a1b42015-06-22 17:02:30 +00001698}
Alex Lorenzf09df002015-06-30 18:16:42 +00001699
Alex Lorenz7a503fa2015-07-07 17:46:43 +00001700bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
1701 MachineFunction &MF, StringRef Src,
1702 const PerFunctionMIParsingState &PFS,
1703 const SlotMapping &IRSlots, SMDiagnostic &Error) {
Alex Lorenz1ea60892015-07-27 20:29:27 +00001704 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMBB(MBB);
Alex Lorenzf09df002015-06-30 18:16:42 +00001705}
Alex Lorenz9fab3702015-07-14 21:24:41 +00001706
1707bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
1708 MachineFunction &MF, StringRef Src,
1709 const PerFunctionMIParsingState &PFS,
1710 const SlotMapping &IRSlots,
1711 SMDiagnostic &Error) {
Alex Lorenz1ea60892015-07-27 20:29:27 +00001712 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1713 .parseStandaloneNamedRegister(Reg);
Alex Lorenz9fab3702015-07-14 21:24:41 +00001714}
Alex Lorenz12045a42015-07-27 17:42:45 +00001715
1716bool llvm::parseVirtualRegisterReference(unsigned &Reg, SourceMgr &SM,
1717 MachineFunction &MF, StringRef Src,
1718 const PerFunctionMIParsingState &PFS,
1719 const SlotMapping &IRSlots,
1720 SMDiagnostic &Error) {
1721 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1722 .parseStandaloneVirtualRegister(Reg);
1723}