blob: c6383720e23df455845d257d38e17230e7a55262 [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 Lorenz1039fd12015-08-14 19:07:07 +0000780 case MIToken::kw_internal:
781 Flags |= RegState::InternalRead;
782 break;
Alex Lorenz01c1a5e2015-08-05 17:49:03 +0000783 case MIToken::kw_early_clobber:
784 Flags |= RegState::EarlyClobber;
785 break;
Alex Lorenz90752582015-08-05 17:41:17 +0000786 case MIToken::kw_debug_use:
787 Flags |= RegState::Debug;
788 break;
Alex Lorenzcb268d42015-07-06 23:07:26 +0000789 default:
790 llvm_unreachable("The current token should be a register flag");
791 }
Alex Lorenz2b3cf192015-08-05 18:09:03 +0000792 if (OldFlags == Flags)
793 // We know that the same flag is specified more than once when the flags
794 // weren't modified.
795 return error("duplicate '" + Token.stringValue() + "' register flag");
Alex Lorenzcb268d42015-07-06 23:07:26 +0000796 lex();
797 return false;
798}
799
Alex Lorenz2eacca82015-07-13 23:24:34 +0000800bool MIParser::parseSubRegisterIndex(unsigned &SubReg) {
801 assert(Token.is(MIToken::colon));
802 lex();
803 if (Token.isNot(MIToken::Identifier))
804 return error("expected a subregister index after ':'");
805 auto Name = Token.stringValue();
806 SubReg = getSubRegIndex(Name);
807 if (!SubReg)
808 return error(Twine("use of unknown subregister index '") + Name + "'");
809 lex();
810 return false;
811}
812
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000813bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
814 unsigned Reg;
Alex Lorenzcb268d42015-07-06 23:07:26 +0000815 unsigned Flags = IsDef ? RegState::Define : 0;
816 while (Token.isRegisterFlag()) {
817 if (parseRegisterFlag(Flags))
818 return true;
819 }
820 if (!Token.isRegister())
821 return error("expected a register after register flags");
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000822 if (parseRegister(Reg))
823 return true;
824 lex();
Alex Lorenz2eacca82015-07-13 23:24:34 +0000825 unsigned SubReg = 0;
826 if (Token.is(MIToken::colon)) {
827 if (parseSubRegisterIndex(SubReg))
828 return true;
829 }
Alex Lorenz495ad872015-07-08 21:23:34 +0000830 Dest = MachineOperand::CreateReg(
831 Reg, Flags & RegState::Define, Flags & RegState::Implicit,
Alex Lorenz2eacca82015-07-13 23:24:34 +0000832 Flags & RegState::Kill, Flags & RegState::Dead, Flags & RegState::Undef,
Alex Lorenz1039fd12015-08-14 19:07:07 +0000833 Flags & RegState::EarlyClobber, SubReg, Flags & RegState::Debug,
834 Flags & RegState::InternalRead);
Alex Lorenzf3db51de2015-06-23 16:35:26 +0000835 return false;
836}
837
Alex Lorenz240fc1e2015-06-23 23:42:28 +0000838bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
839 assert(Token.is(MIToken::IntegerLiteral));
840 const APSInt &Int = Token.integerValue();
841 if (Int.getMinSignedBits() > 64)
Alex Lorenz3f2058d2015-08-05 19:03:42 +0000842 return error("integer literal is too large to be an immediate operand");
Alex Lorenz240fc1e2015-06-23 23:42:28 +0000843 Dest = MachineOperand::CreateImm(Int.getExtValue());
844 lex();
845 return false;
846}
847
Alex Lorenz7eaff4c2015-08-05 18:44:00 +0000848bool MIParser::parseIRConstant(StringRef::iterator Loc, const Constant *&C) {
Alex Lorenz3fb77682015-08-06 23:17:42 +0000849 auto Source = StringRef(Loc, Token.range().end() - Loc).str();
Alex Lorenz7eaff4c2015-08-05 18:44:00 +0000850 lex();
851 SMDiagnostic Err;
852 C = parseConstantValue(Source.c_str(), Err, *MF.getFunction()->getParent());
853 if (!C)
854 return error(Loc + Err.getColumnNo(), Err.getMessage());
855 return false;
856}
857
Alex Lorenz05e38822015-08-05 18:52:21 +0000858bool MIParser::parseTypedImmediateOperand(MachineOperand &Dest) {
859 assert(Token.is(MIToken::IntegerType));
860 auto Loc = Token.location();
861 lex();
862 if (Token.isNot(MIToken::IntegerLiteral))
863 return error("expected an integer literal");
864 const Constant *C = nullptr;
865 if (parseIRConstant(Loc, C))
866 return true;
867 Dest = MachineOperand::CreateCImm(cast<ConstantInt>(C));
868 return false;
869}
870
Alex Lorenzad156fb2015-07-31 20:49:21 +0000871bool MIParser::parseFPImmediateOperand(MachineOperand &Dest) {
872 auto Loc = Token.location();
873 lex();
874 if (Token.isNot(MIToken::FloatingPointLiteral))
875 return error("expected a floating point literal");
Alex Lorenz7eaff4c2015-08-05 18:44:00 +0000876 const Constant *C = nullptr;
877 if (parseIRConstant(Loc, C))
878 return true;
Alex Lorenzad156fb2015-07-31 20:49:21 +0000879 Dest = MachineOperand::CreateFPImm(cast<ConstantFP>(C));
880 return false;
881}
882
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000883bool MIParser::getUnsigned(unsigned &Result) {
884 assert(Token.hasIntegerValue() && "Expected a token with an integer value");
885 const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
886 uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
887 if (Val64 == Limit)
888 return error("expected 32-bit integer (too large)");
889 Result = Val64;
890 return false;
891}
892
Alex Lorenzf09df002015-06-30 18:16:42 +0000893bool MIParser::parseMBBReference(MachineBasicBlock *&MBB) {
Alex Lorenz5022f6b2015-08-13 23:10:16 +0000894 assert(Token.is(MIToken::MachineBasicBlock) ||
895 Token.is(MIToken::MachineBasicBlockLabel));
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000896 unsigned Number;
897 if (getUnsigned(Number))
898 return true;
Alex Lorenz7a503fa2015-07-07 17:46:43 +0000899 auto MBBInfo = PFS.MBBSlots.find(Number);
900 if (MBBInfo == PFS.MBBSlots.end())
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000901 return error(Twine("use of undefined machine basic block #") +
902 Twine(Number));
Alex Lorenzf09df002015-06-30 18:16:42 +0000903 MBB = MBBInfo->second;
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000904 if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
905 return error(Twine("the name of machine basic block #") + Twine(Number) +
906 " isn't '" + Token.stringValue() + "'");
Alex Lorenzf09df002015-06-30 18:16:42 +0000907 return false;
908}
909
910bool MIParser::parseMBBOperand(MachineOperand &Dest) {
911 MachineBasicBlock *MBB;
912 if (parseMBBReference(MBB))
913 return true;
Alex Lorenz33f0aef2015-06-26 16:46:11 +0000914 Dest = MachineOperand::CreateMBB(MBB);
915 lex();
916 return false;
917}
918
Alex Lorenz7feaf7c2015-07-16 23:37:45 +0000919bool MIParser::parseStackObjectOperand(MachineOperand &Dest) {
920 assert(Token.is(MIToken::StackObject));
921 unsigned ID;
922 if (getUnsigned(ID))
923 return true;
924 auto ObjectInfo = PFS.StackObjectSlots.find(ID);
925 if (ObjectInfo == PFS.StackObjectSlots.end())
926 return error(Twine("use of undefined stack object '%stack.") + Twine(ID) +
927 "'");
928 StringRef Name;
929 if (const auto *Alloca =
930 MF.getFrameInfo()->getObjectAllocation(ObjectInfo->second))
931 Name = Alloca->getName();
932 if (!Token.stringValue().empty() && Token.stringValue() != Name)
933 return error(Twine("the name of the stack object '%stack.") + Twine(ID) +
934 "' isn't '" + Token.stringValue() + "'");
935 lex();
936 Dest = MachineOperand::CreateFI(ObjectInfo->second);
937 return false;
938}
939
Alex Lorenzea882122015-08-12 21:17:02 +0000940bool MIParser::parseFixedStackFrameIndex(int &FI) {
Alex Lorenz7feaf7c2015-07-16 23:37:45 +0000941 assert(Token.is(MIToken::FixedStackObject));
942 unsigned ID;
943 if (getUnsigned(ID))
944 return true;
945 auto ObjectInfo = PFS.FixedStackObjectSlots.find(ID);
946 if (ObjectInfo == PFS.FixedStackObjectSlots.end())
947 return error(Twine("use of undefined fixed stack object '%fixed-stack.") +
948 Twine(ID) + "'");
949 lex();
Alex Lorenzea882122015-08-12 21:17:02 +0000950 FI = ObjectInfo->second;
951 return false;
952}
953
954bool MIParser::parseFixedStackObjectOperand(MachineOperand &Dest) {
955 int FI;
956 if (parseFixedStackFrameIndex(FI))
957 return true;
958 Dest = MachineOperand::CreateFI(FI);
Alex Lorenz7feaf7c2015-07-16 23:37:45 +0000959 return false;
960}
961
Alex Lorenz41df7d32015-07-28 17:09:52 +0000962bool MIParser::parseGlobalValue(GlobalValue *&GV) {
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000963 switch (Token.kind()) {
Alex Lorenz970c12e2015-08-05 17:35:55 +0000964 case MIToken::NamedGlobalValue: {
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000965 const Module *M = MF.getFunction()->getParent();
Alex Lorenz970c12e2015-08-05 17:35:55 +0000966 GV = M->getNamedValue(Token.stringValue());
Alex Lorenz41df7d32015-07-28 17:09:52 +0000967 if (!GV)
Alex Lorenz3fb77682015-08-06 23:17:42 +0000968 return error(Twine("use of undefined global value '") + Token.range() +
969 "'");
Alex Lorenz41df7d32015-07-28 17:09:52 +0000970 break;
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000971 }
972 case MIToken::GlobalValue: {
973 unsigned GVIdx;
974 if (getUnsigned(GVIdx))
975 return true;
976 if (GVIdx >= IRSlots.GlobalValues.size())
977 return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
978 "'");
Alex Lorenz41df7d32015-07-28 17:09:52 +0000979 GV = IRSlots.GlobalValues[GVIdx];
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000980 break;
981 }
982 default:
983 llvm_unreachable("The current token should be a global value");
984 }
Alex Lorenz41df7d32015-07-28 17:09:52 +0000985 return false;
986}
987
988bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
989 GlobalValue *GV = nullptr;
990 if (parseGlobalValue(GV))
991 return true;
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000992 lex();
Alex Lorenz5672a892015-08-05 22:26:15 +0000993 Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
Alex Lorenz5672a892015-08-05 22:26:15 +0000994 if (parseOperandsOffset(Dest))
995 return true;
Alex Lorenz5d6108e2015-06-26 22:56:48 +0000996 return false;
997}
998
Alex Lorenzab980492015-07-20 20:51:18 +0000999bool MIParser::parseConstantPoolIndexOperand(MachineOperand &Dest) {
1000 assert(Token.is(MIToken::ConstantPoolItem));
1001 unsigned ID;
1002 if (getUnsigned(ID))
1003 return true;
1004 auto ConstantInfo = PFS.ConstantPoolSlots.find(ID);
1005 if (ConstantInfo == PFS.ConstantPoolSlots.end())
1006 return error("use of undefined constant '%const." + Twine(ID) + "'");
1007 lex();
Alex Lorenzab980492015-07-20 20:51:18 +00001008 Dest = MachineOperand::CreateCPI(ID, /*Offset=*/0);
Alex Lorenz5672a892015-08-05 22:26:15 +00001009 if (parseOperandsOffset(Dest))
1010 return true;
Alex Lorenzab980492015-07-20 20:51:18 +00001011 return false;
1012}
1013
Alex Lorenz31d70682015-07-15 23:38:35 +00001014bool MIParser::parseJumpTableIndexOperand(MachineOperand &Dest) {
1015 assert(Token.is(MIToken::JumpTableIndex));
1016 unsigned ID;
1017 if (getUnsigned(ID))
1018 return true;
1019 auto JumpTableEntryInfo = PFS.JumpTableSlots.find(ID);
1020 if (JumpTableEntryInfo == PFS.JumpTableSlots.end())
1021 return error("use of undefined jump table '%jump-table." + Twine(ID) + "'");
1022 lex();
Alex Lorenz31d70682015-07-15 23:38:35 +00001023 Dest = MachineOperand::CreateJTI(JumpTableEntryInfo->second);
1024 return false;
1025}
1026
Alex Lorenz6ede3742015-07-21 16:59:53 +00001027bool MIParser::parseExternalSymbolOperand(MachineOperand &Dest) {
Alex Lorenz970c12e2015-08-05 17:35:55 +00001028 assert(Token.is(MIToken::ExternalSymbol));
1029 const char *Symbol = MF.createExternalSymbolName(Token.stringValue());
Alex Lorenz6ede3742015-07-21 16:59:53 +00001030 lex();
Alex Lorenz6ede3742015-07-21 16:59:53 +00001031 Dest = MachineOperand::CreateES(Symbol);
Alex Lorenz5672a892015-08-05 22:26:15 +00001032 if (parseOperandsOffset(Dest))
1033 return true;
Alex Lorenz6ede3742015-07-21 16:59:53 +00001034 return false;
1035}
1036
Alex Lorenz44f29252015-07-22 21:07:04 +00001037bool MIParser::parseMDNode(MDNode *&Node) {
Alex Lorenz35e44462015-07-22 17:58:46 +00001038 assert(Token.is(MIToken::exclaim));
1039 auto Loc = Token.location();
1040 lex();
1041 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
1042 return error("expected metadata id after '!'");
1043 unsigned ID;
1044 if (getUnsigned(ID))
1045 return true;
1046 auto NodeInfo = IRSlots.MetadataNodes.find(ID);
1047 if (NodeInfo == IRSlots.MetadataNodes.end())
1048 return error(Loc, "use of undefined metadata '!" + Twine(ID) + "'");
1049 lex();
Alex Lorenz44f29252015-07-22 21:07:04 +00001050 Node = NodeInfo->second.get();
1051 return false;
1052}
1053
1054bool MIParser::parseMetadataOperand(MachineOperand &Dest) {
1055 MDNode *Node = nullptr;
1056 if (parseMDNode(Node))
1057 return true;
1058 Dest = MachineOperand::CreateMetadata(Node);
Alex Lorenz35e44462015-07-22 17:58:46 +00001059 return false;
1060}
1061
Alex Lorenzf4baeb52015-07-21 22:28:27 +00001062bool MIParser::parseCFIOffset(int &Offset) {
1063 if (Token.isNot(MIToken::IntegerLiteral))
1064 return error("expected a cfi offset");
1065 if (Token.integerValue().getMinSignedBits() > 32)
1066 return error("expected a 32 bit integer (the cfi offset is too large)");
1067 Offset = (int)Token.integerValue().getExtValue();
1068 lex();
1069 return false;
1070}
1071
Alex Lorenz8cfc6862015-07-23 23:09:07 +00001072bool MIParser::parseCFIRegister(unsigned &Reg) {
1073 if (Token.isNot(MIToken::NamedRegister))
1074 return error("expected a cfi register");
1075 unsigned LLVMReg;
1076 if (parseRegister(LLVMReg))
Alex Lorenzf4baeb52015-07-21 22:28:27 +00001077 return true;
Alex Lorenz8cfc6862015-07-23 23:09:07 +00001078 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1079 assert(TRI && "Expected target register info");
1080 int DwarfReg = TRI->getDwarfRegNum(LLVMReg, true);
1081 if (DwarfReg < 0)
1082 return error("invalid DWARF register");
1083 Reg = (unsigned)DwarfReg;
1084 lex();
1085 return false;
1086}
1087
1088bool MIParser::parseCFIOperand(MachineOperand &Dest) {
1089 auto Kind = Token.kind();
1090 lex();
1091 auto &MMI = MF.getMMI();
1092 int Offset;
1093 unsigned Reg;
1094 unsigned CFIIndex;
1095 switch (Kind) {
Alex Lorenz577d2712015-08-14 21:55:58 +00001096 case MIToken::kw_cfi_same_value:
1097 if (parseCFIRegister(Reg))
1098 return true;
1099 CFIIndex =
1100 MMI.addFrameInst(MCCFIInstruction::createSameValue(nullptr, Reg));
1101 break;
Alex Lorenz8cfc6862015-07-23 23:09:07 +00001102 case MIToken::kw_cfi_offset:
1103 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1104 parseCFIOffset(Offset))
1105 return true;
1106 CFIIndex =
1107 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, Reg, Offset));
1108 break;
Alex Lorenz5b0d5f62015-07-27 20:39:03 +00001109 case MIToken::kw_cfi_def_cfa_register:
1110 if (parseCFIRegister(Reg))
1111 return true;
1112 CFIIndex =
1113 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
1114 break;
Alex Lorenz8cfc6862015-07-23 23:09:07 +00001115 case MIToken::kw_cfi_def_cfa_offset:
1116 if (parseCFIOffset(Offset))
1117 return true;
1118 // NB: MCCFIInstruction::createDefCfaOffset negates the offset.
1119 CFIIndex = MMI.addFrameInst(
1120 MCCFIInstruction::createDefCfaOffset(nullptr, -Offset));
1121 break;
Alex Lorenzb1393232015-07-29 18:57:23 +00001122 case MIToken::kw_cfi_def_cfa:
1123 if (parseCFIRegister(Reg) || expectAndConsume(MIToken::comma) ||
1124 parseCFIOffset(Offset))
1125 return true;
1126 // NB: MCCFIInstruction::createDefCfa negates the offset.
1127 CFIIndex =
1128 MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
1129 break;
Alex Lorenz8cfc6862015-07-23 23:09:07 +00001130 default:
1131 // TODO: Parse the other CFI operands.
1132 llvm_unreachable("The current token should be a cfi operand");
1133 }
1134 Dest = MachineOperand::CreateCFIIndex(CFIIndex);
Alex Lorenzf4baeb52015-07-21 22:28:27 +00001135 return false;
1136}
1137
Alex Lorenzdeb53492015-07-28 17:28:03 +00001138bool MIParser::parseIRBlock(BasicBlock *&BB, const Function &F) {
1139 switch (Token.kind()) {
Alex Lorenz970c12e2015-08-05 17:35:55 +00001140 case MIToken::NamedIRBlock: {
1141 BB = dyn_cast_or_null<BasicBlock>(
1142 F.getValueSymbolTable().lookup(Token.stringValue()));
Alex Lorenzdeb53492015-07-28 17:28:03 +00001143 if (!BB)
Alex Lorenz3fb77682015-08-06 23:17:42 +00001144 return error(Twine("use of undefined IR block '") + Token.range() + "'");
Alex Lorenzdeb53492015-07-28 17:28:03 +00001145 break;
1146 }
1147 case MIToken::IRBlock: {
1148 unsigned SlotNumber = 0;
1149 if (getUnsigned(SlotNumber))
1150 return true;
Alex Lorenzcba8c5f2015-08-06 23:57:04 +00001151 BB = const_cast<BasicBlock *>(getIRBlock(SlotNumber, F));
Alex Lorenzdeb53492015-07-28 17:28:03 +00001152 if (!BB)
1153 return error(Twine("use of undefined IR block '%ir-block.") +
1154 Twine(SlotNumber) + "'");
1155 break;
1156 }
1157 default:
1158 llvm_unreachable("The current token should be an IR block reference");
1159 }
1160 return false;
1161}
1162
1163bool MIParser::parseBlockAddressOperand(MachineOperand &Dest) {
1164 assert(Token.is(MIToken::kw_blockaddress));
1165 lex();
1166 if (expectAndConsume(MIToken::lparen))
1167 return true;
1168 if (Token.isNot(MIToken::GlobalValue) &&
Alex Lorenz970c12e2015-08-05 17:35:55 +00001169 Token.isNot(MIToken::NamedGlobalValue))
Alex Lorenzdeb53492015-07-28 17:28:03 +00001170 return error("expected a global value");
1171 GlobalValue *GV = nullptr;
1172 if (parseGlobalValue(GV))
1173 return true;
1174 auto *F = dyn_cast<Function>(GV);
1175 if (!F)
1176 return error("expected an IR function reference");
1177 lex();
1178 if (expectAndConsume(MIToken::comma))
1179 return true;
1180 BasicBlock *BB = nullptr;
Alex Lorenz970c12e2015-08-05 17:35:55 +00001181 if (Token.isNot(MIToken::IRBlock) && Token.isNot(MIToken::NamedIRBlock))
Alex Lorenzdeb53492015-07-28 17:28:03 +00001182 return error("expected an IR block reference");
1183 if (parseIRBlock(BB, *F))
1184 return true;
1185 lex();
1186 if (expectAndConsume(MIToken::rparen))
1187 return true;
Alex Lorenzdeb53492015-07-28 17:28:03 +00001188 Dest = MachineOperand::CreateBA(BlockAddress::get(F, BB), /*Offset=*/0);
Alex Lorenz5672a892015-08-05 22:26:15 +00001189 if (parseOperandsOffset(Dest))
1190 return true;
Alex Lorenzdeb53492015-07-28 17:28:03 +00001191 return false;
1192}
1193
Alex Lorenzef5c1962015-07-28 23:02:45 +00001194bool MIParser::parseTargetIndexOperand(MachineOperand &Dest) {
1195 assert(Token.is(MIToken::kw_target_index));
1196 lex();
1197 if (expectAndConsume(MIToken::lparen))
1198 return true;
1199 if (Token.isNot(MIToken::Identifier))
1200 return error("expected the name of the target index");
1201 int Index = 0;
1202 if (getTargetIndex(Token.stringValue(), Index))
1203 return error("use of undefined target index '" + Token.stringValue() + "'");
1204 lex();
1205 if (expectAndConsume(MIToken::rparen))
1206 return true;
Alex Lorenzef5c1962015-07-28 23:02:45 +00001207 Dest = MachineOperand::CreateTargetIndex(unsigned(Index), /*Offset=*/0);
Alex Lorenz5672a892015-08-05 22:26:15 +00001208 if (parseOperandsOffset(Dest))
1209 return true;
Alex Lorenzef5c1962015-07-28 23:02:45 +00001210 return false;
1211}
1212
Alex Lorenzb97c9ef2015-08-10 23:24:42 +00001213bool MIParser::parseLiveoutRegisterMaskOperand(MachineOperand &Dest) {
1214 assert(Token.is(MIToken::kw_liveout));
1215 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1216 assert(TRI && "Expected target register info");
1217 uint32_t *Mask = MF.allocateRegisterMask(TRI->getNumRegs());
1218 lex();
1219 if (expectAndConsume(MIToken::lparen))
1220 return true;
1221 while (true) {
1222 if (Token.isNot(MIToken::NamedRegister))
1223 return error("expected a named register");
1224 unsigned Reg = 0;
1225 if (parseRegister(Reg))
1226 return true;
1227 lex();
1228 Mask[Reg / 32] |= 1U << (Reg % 32);
1229 // TODO: Report an error if the same register is used more than once.
1230 if (Token.isNot(MIToken::comma))
1231 break;
1232 lex();
1233 }
1234 if (expectAndConsume(MIToken::rparen))
1235 return true;
1236 Dest = MachineOperand::CreateRegLiveOut(Mask);
1237 return false;
1238}
1239
Alex Lorenzf3db51de2015-06-23 16:35:26 +00001240bool MIParser::parseMachineOperand(MachineOperand &Dest) {
1241 switch (Token.kind()) {
Alex Lorenzcb268d42015-07-06 23:07:26 +00001242 case MIToken::kw_implicit:
1243 case MIToken::kw_implicit_define:
Alex Lorenzcbbfd0b2015-07-07 20:34:53 +00001244 case MIToken::kw_dead:
Alex Lorenz495ad872015-07-08 21:23:34 +00001245 case MIToken::kw_killed:
Alex Lorenz4d026b892015-07-08 23:58:31 +00001246 case MIToken::kw_undef:
Alex Lorenz1039fd12015-08-14 19:07:07 +00001247 case MIToken::kw_internal:
Alex Lorenz01c1a5e2015-08-05 17:49:03 +00001248 case MIToken::kw_early_clobber:
Alex Lorenz90752582015-08-05 17:41:17 +00001249 case MIToken::kw_debug_use:
Alex Lorenz12b554e2015-06-24 17:34:58 +00001250 case MIToken::underscore:
Alex Lorenzf3db51de2015-06-23 16:35:26 +00001251 case MIToken::NamedRegister:
Alex Lorenz53464512015-07-10 22:51:20 +00001252 case MIToken::VirtualRegister:
Alex Lorenzf3db51de2015-06-23 16:35:26 +00001253 return parseRegisterOperand(Dest);
Alex Lorenz240fc1e2015-06-23 23:42:28 +00001254 case MIToken::IntegerLiteral:
1255 return parseImmediateOperand(Dest);
Alex Lorenz05e38822015-08-05 18:52:21 +00001256 case MIToken::IntegerType:
1257 return parseTypedImmediateOperand(Dest);
Alex Lorenzad156fb2015-07-31 20:49:21 +00001258 case MIToken::kw_half:
1259 case MIToken::kw_float:
1260 case MIToken::kw_double:
1261 case MIToken::kw_x86_fp80:
1262 case MIToken::kw_fp128:
1263 case MIToken::kw_ppc_fp128:
1264 return parseFPImmediateOperand(Dest);
Alex Lorenz33f0aef2015-06-26 16:46:11 +00001265 case MIToken::MachineBasicBlock:
1266 return parseMBBOperand(Dest);
Alex Lorenz7feaf7c2015-07-16 23:37:45 +00001267 case MIToken::StackObject:
1268 return parseStackObjectOperand(Dest);
1269 case MIToken::FixedStackObject:
1270 return parseFixedStackObjectOperand(Dest);
Alex Lorenz5d6108e2015-06-26 22:56:48 +00001271 case MIToken::GlobalValue:
1272 case MIToken::NamedGlobalValue:
1273 return parseGlobalAddressOperand(Dest);
Alex Lorenzab980492015-07-20 20:51:18 +00001274 case MIToken::ConstantPoolItem:
1275 return parseConstantPoolIndexOperand(Dest);
Alex Lorenz31d70682015-07-15 23:38:35 +00001276 case MIToken::JumpTableIndex:
1277 return parseJumpTableIndexOperand(Dest);
Alex Lorenz6ede3742015-07-21 16:59:53 +00001278 case MIToken::ExternalSymbol:
Alex Lorenz6ede3742015-07-21 16:59:53 +00001279 return parseExternalSymbolOperand(Dest);
Alex Lorenz35e44462015-07-22 17:58:46 +00001280 case MIToken::exclaim:
1281 return parseMetadataOperand(Dest);
Alex Lorenz577d2712015-08-14 21:55:58 +00001282 case MIToken::kw_cfi_same_value:
Alex Lorenz8cfc6862015-07-23 23:09:07 +00001283 case MIToken::kw_cfi_offset:
Alex Lorenz5b0d5f62015-07-27 20:39:03 +00001284 case MIToken::kw_cfi_def_cfa_register:
Alex Lorenzf4baeb52015-07-21 22:28:27 +00001285 case MIToken::kw_cfi_def_cfa_offset:
Alex Lorenzb1393232015-07-29 18:57:23 +00001286 case MIToken::kw_cfi_def_cfa:
Alex Lorenzf4baeb52015-07-21 22:28:27 +00001287 return parseCFIOperand(Dest);
Alex Lorenzdeb53492015-07-28 17:28:03 +00001288 case MIToken::kw_blockaddress:
1289 return parseBlockAddressOperand(Dest);
Alex Lorenzef5c1962015-07-28 23:02:45 +00001290 case MIToken::kw_target_index:
1291 return parseTargetIndexOperand(Dest);
Alex Lorenzb97c9ef2015-08-10 23:24:42 +00001292 case MIToken::kw_liveout:
1293 return parseLiveoutRegisterMaskOperand(Dest);
Alex Lorenzf3db51de2015-06-23 16:35:26 +00001294 case MIToken::Error:
1295 return true;
Alex Lorenz8f6f4282015-06-29 16:57:06 +00001296 case MIToken::Identifier:
1297 if (const auto *RegMask = getRegMask(Token.stringValue())) {
1298 Dest = MachineOperand::CreateRegMask(RegMask);
1299 lex();
1300 break;
1301 }
1302 // fallthrough
Alex Lorenzf3db51de2015-06-23 16:35:26 +00001303 default:
1304 // TODO: parse the other machine operands.
1305 return error("expected a machine operand");
1306 }
Alex Lorenz91370c52015-06-22 20:37:46 +00001307 return false;
1308}
1309
Alex Lorenz49873a82015-08-06 00:44:07 +00001310bool MIParser::parseMachineOperandAndTargetFlags(MachineOperand &Dest) {
1311 unsigned TF = 0;
1312 bool HasTargetFlags = false;
1313 if (Token.is(MIToken::kw_target_flags)) {
1314 HasTargetFlags = true;
1315 lex();
1316 if (expectAndConsume(MIToken::lparen))
1317 return true;
1318 if (Token.isNot(MIToken::Identifier))
1319 return error("expected the name of the target flag");
1320 if (getDirectTargetFlag(Token.stringValue(), TF))
1321 return error("use of undefined target flag '" + Token.stringValue() +
1322 "'");
1323 lex();
1324 // TODO: Parse target's bit target flags.
1325 if (expectAndConsume(MIToken::rparen))
1326 return true;
1327 }
1328 auto Loc = Token.location();
1329 if (parseMachineOperand(Dest))
1330 return true;
1331 if (!HasTargetFlags)
1332 return false;
1333 if (Dest.isReg())
1334 return error(Loc, "register operands can't have target flags");
1335 Dest.setTargetFlags(TF);
1336 return false;
1337}
1338
Alex Lorenzdc24c172015-08-07 20:21:00 +00001339bool MIParser::parseOffset(int64_t &Offset) {
Alex Lorenz5672a892015-08-05 22:26:15 +00001340 if (Token.isNot(MIToken::plus) && Token.isNot(MIToken::minus))
1341 return false;
Alex Lorenz3fb77682015-08-06 23:17:42 +00001342 StringRef Sign = Token.range();
Alex Lorenz5672a892015-08-05 22:26:15 +00001343 bool IsNegative = Token.is(MIToken::minus);
1344 lex();
1345 if (Token.isNot(MIToken::IntegerLiteral))
1346 return error("expected an integer literal after '" + Sign + "'");
1347 if (Token.integerValue().getMinSignedBits() > 64)
1348 return error("expected 64-bit integer (too large)");
Alex Lorenzdc24c172015-08-07 20:21:00 +00001349 Offset = Token.integerValue().getExtValue();
Alex Lorenz5672a892015-08-05 22:26:15 +00001350 if (IsNegative)
1351 Offset = -Offset;
1352 lex();
Alex Lorenzdc24c172015-08-07 20:21:00 +00001353 return false;
1354}
1355
Alex Lorenz620f8912015-08-13 20:33:33 +00001356bool MIParser::parseAlignment(unsigned &Alignment) {
1357 assert(Token.is(MIToken::kw_align));
1358 lex();
Alex Lorenz68661042015-08-13 20:55:01 +00001359 if (Token.isNot(MIToken::IntegerLiteral) || Token.integerValue().isSigned())
Alex Lorenz620f8912015-08-13 20:33:33 +00001360 return error("expected an integer literal after 'align'");
1361 if (getUnsigned(Alignment))
1362 return true;
1363 lex();
1364 return false;
1365}
1366
Alex Lorenzdc24c172015-08-07 20:21:00 +00001367bool MIParser::parseOperandsOffset(MachineOperand &Op) {
1368 int64_t Offset = 0;
1369 if (parseOffset(Offset))
1370 return true;
Alex Lorenz5672a892015-08-05 22:26:15 +00001371 Op.setOffset(Offset);
1372 return false;
1373}
1374
Alex Lorenz4af7e612015-08-03 23:08:19 +00001375bool MIParser::parseIRValue(Value *&V) {
1376 switch (Token.kind()) {
Alex Lorenz970c12e2015-08-05 17:35:55 +00001377 case MIToken::NamedIRValue: {
1378 V = MF.getFunction()->getValueSymbolTable().lookup(Token.stringValue());
Alex Lorenz4af7e612015-08-03 23:08:19 +00001379 if (!V)
Alex Lorenz2791dcc2015-08-12 21:27:16 +00001380 V = MF.getFunction()->getParent()->getValueSymbolTable().lookup(
1381 Token.stringValue());
1382 if (!V)
Alex Lorenz3fb77682015-08-06 23:17:42 +00001383 return error(Twine("use of undefined IR value '") + Token.range() + "'");
Alex Lorenz4af7e612015-08-03 23:08:19 +00001384 break;
1385 }
1386 // TODO: Parse unnamed IR value references.
1387 default:
1388 llvm_unreachable("The current token should be an IR block reference");
1389 }
1390 return false;
1391}
1392
1393bool MIParser::getUint64(uint64_t &Result) {
1394 assert(Token.hasIntegerValue());
1395 if (Token.integerValue().getActiveBits() > 64)
1396 return error("expected 64-bit integer (too large)");
1397 Result = Token.integerValue().getZExtValue();
1398 return false;
1399}
1400
Alex Lorenza518b792015-08-04 00:24:45 +00001401bool MIParser::parseMemoryOperandFlag(unsigned &Flags) {
Alex Lorenze86d5152015-08-06 18:26:36 +00001402 const unsigned OldFlags = Flags;
Alex Lorenza518b792015-08-04 00:24:45 +00001403 switch (Token.kind()) {
1404 case MIToken::kw_volatile:
1405 Flags |= MachineMemOperand::MOVolatile;
1406 break;
Alex Lorenz10fd0382015-08-06 16:49:30 +00001407 case MIToken::kw_non_temporal:
1408 Flags |= MachineMemOperand::MONonTemporal;
1409 break;
Alex Lorenzdc8de2a2015-08-06 16:55:53 +00001410 case MIToken::kw_invariant:
1411 Flags |= MachineMemOperand::MOInvariant;
1412 break;
Alex Lorenzdc8de2a2015-08-06 16:55:53 +00001413 // TODO: parse the target specific memory operand flags.
Alex Lorenza518b792015-08-04 00:24:45 +00001414 default:
1415 llvm_unreachable("The current token should be a memory operand flag");
1416 }
Alex Lorenze86d5152015-08-06 18:26:36 +00001417 if (OldFlags == Flags)
1418 // We know that the same flag is specified more than once when the flags
1419 // weren't modified.
1420 return error("duplicate '" + Token.stringValue() + "' memory operand flag");
Alex Lorenza518b792015-08-04 00:24:45 +00001421 lex();
1422 return false;
1423}
1424
Alex Lorenz91097a32015-08-12 20:33:26 +00001425bool MIParser::parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV) {
1426 switch (Token.kind()) {
Alex Lorenz46e95582015-08-12 20:44:16 +00001427 case MIToken::kw_stack:
1428 PSV = MF.getPSVManager().getStack();
1429 break;
Alex Lorenzd858f872015-08-12 21:00:22 +00001430 case MIToken::kw_got:
1431 PSV = MF.getPSVManager().getGOT();
1432 break;
Alex Lorenz4be56e92015-08-12 21:11:08 +00001433 case MIToken::kw_jump_table:
1434 PSV = MF.getPSVManager().getJumpTable();
1435 break;
Alex Lorenz91097a32015-08-12 20:33:26 +00001436 case MIToken::kw_constant_pool:
1437 PSV = MF.getPSVManager().getConstantPool();
1438 break;
Alex Lorenz0cc671b2015-08-12 21:23:17 +00001439 case MIToken::FixedStackObject: {
1440 int FI;
1441 if (parseFixedStackFrameIndex(FI))
1442 return true;
1443 PSV = MF.getPSVManager().getFixedStack(FI);
1444 // The token was already consumed, so use return here instead of break.
1445 return false;
1446 }
Alex Lorenz50b826f2015-08-14 21:08:30 +00001447 case MIToken::GlobalValue:
1448 case MIToken::NamedGlobalValue: {
1449 GlobalValue *GV = nullptr;
1450 if (parseGlobalValue(GV))
1451 return true;
1452 PSV = MF.getPSVManager().getGlobalValueCallEntry(GV);
1453 break;
1454 }
Alex Lorenzc3ba7502015-08-14 21:14:50 +00001455 case MIToken::ExternalSymbol:
1456 PSV = MF.getPSVManager().getExternalSymbolCallEntry(
1457 MF.createExternalSymbolName(Token.stringValue()));
1458 break;
Alex Lorenz91097a32015-08-12 20:33:26 +00001459 default:
1460 llvm_unreachable("The current token should be pseudo source value");
1461 }
1462 lex();
1463 return false;
1464}
1465
1466bool MIParser::parseMachinePointerInfo(MachinePointerInfo &Dest) {
Alex Lorenzd858f872015-08-12 21:00:22 +00001467 if (Token.is(MIToken::kw_constant_pool) || Token.is(MIToken::kw_stack) ||
Alex Lorenz0cc671b2015-08-12 21:23:17 +00001468 Token.is(MIToken::kw_got) || Token.is(MIToken::kw_jump_table) ||
Alex Lorenz50b826f2015-08-14 21:08:30 +00001469 Token.is(MIToken::FixedStackObject) || Token.is(MIToken::GlobalValue) ||
Alex Lorenzc3ba7502015-08-14 21:14:50 +00001470 Token.is(MIToken::NamedGlobalValue) ||
1471 Token.is(MIToken::ExternalSymbol)) {
Alex Lorenz91097a32015-08-12 20:33:26 +00001472 const PseudoSourceValue *PSV = nullptr;
1473 if (parseMemoryPseudoSourceValue(PSV))
1474 return true;
1475 int64_t Offset = 0;
1476 if (parseOffset(Offset))
1477 return true;
1478 Dest = MachinePointerInfo(PSV, Offset);
1479 return false;
1480 }
1481 if (Token.isNot(MIToken::NamedIRValue))
1482 return error("expected an IR value reference");
1483 Value *V = nullptr;
1484 if (parseIRValue(V))
1485 return true;
1486 if (!V->getType()->isPointerTy())
1487 return error("expected a pointer IR value");
1488 lex();
1489 int64_t Offset = 0;
1490 if (parseOffset(Offset))
1491 return true;
1492 Dest = MachinePointerInfo(V, Offset);
1493 return false;
1494}
1495
Alex Lorenz4af7e612015-08-03 23:08:19 +00001496bool MIParser::parseMachineMemoryOperand(MachineMemOperand *&Dest) {
1497 if (expectAndConsume(MIToken::lparen))
1498 return true;
Alex Lorenza518b792015-08-04 00:24:45 +00001499 unsigned Flags = 0;
1500 while (Token.isMemoryOperandFlag()) {
1501 if (parseMemoryOperandFlag(Flags))
1502 return true;
1503 }
Alex Lorenz4af7e612015-08-03 23:08:19 +00001504 if (Token.isNot(MIToken::Identifier) ||
1505 (Token.stringValue() != "load" && Token.stringValue() != "store"))
1506 return error("expected 'load' or 'store' memory operation");
Alex Lorenz4af7e612015-08-03 23:08:19 +00001507 if (Token.stringValue() == "load")
1508 Flags |= MachineMemOperand::MOLoad;
1509 else
1510 Flags |= MachineMemOperand::MOStore;
1511 lex();
1512
1513 if (Token.isNot(MIToken::IntegerLiteral))
1514 return error("expected the size integer literal after memory operation");
1515 uint64_t Size;
1516 if (getUint64(Size))
1517 return true;
1518 lex();
1519
1520 const char *Word = Flags & MachineMemOperand::MOLoad ? "from" : "into";
1521 if (Token.isNot(MIToken::Identifier) || Token.stringValue() != Word)
1522 return error(Twine("expected '") + Word + "'");
1523 lex();
1524
Alex Lorenz91097a32015-08-12 20:33:26 +00001525 MachinePointerInfo Ptr = MachinePointerInfo();
1526 if (parseMachinePointerInfo(Ptr))
Alex Lorenz83127732015-08-07 20:26:52 +00001527 return true;
Alex Lorenz61420f72015-08-07 20:48:30 +00001528 unsigned BaseAlignment = Size;
1529 if (Token.is(MIToken::comma)) {
1530 lex();
1531 if (Token.isNot(MIToken::kw_align))
1532 return error("expected 'align'");
Alex Lorenz620f8912015-08-13 20:33:33 +00001533 if (parseAlignment(BaseAlignment))
Alex Lorenz61420f72015-08-07 20:48:30 +00001534 return true;
Alex Lorenz61420f72015-08-07 20:48:30 +00001535 }
Alex Lorenz4af7e612015-08-03 23:08:19 +00001536 // TODO: Parse the attached metadata nodes.
1537 if (expectAndConsume(MIToken::rparen))
1538 return true;
Alex Lorenz91097a32015-08-12 20:33:26 +00001539 Dest = MF.getMachineMemOperand(Ptr, Flags, Size, BaseAlignment);
Alex Lorenz4af7e612015-08-03 23:08:19 +00001540 return false;
1541}
1542
Alex Lorenz8e0a1b42015-06-22 17:02:30 +00001543void MIParser::initNames2InstrOpCodes() {
1544 if (!Names2InstrOpCodes.empty())
1545 return;
1546 const auto *TII = MF.getSubtarget().getInstrInfo();
1547 assert(TII && "Expected target instruction info");
1548 for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
1549 Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
1550}
1551
1552bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
1553 initNames2InstrOpCodes();
1554 auto InstrInfo = Names2InstrOpCodes.find(InstrName);
1555 if (InstrInfo == Names2InstrOpCodes.end())
1556 return true;
1557 OpCode = InstrInfo->getValue();
1558 return false;
1559}
1560
Alex Lorenzf3db51de2015-06-23 16:35:26 +00001561void MIParser::initNames2Regs() {
1562 if (!Names2Regs.empty())
1563 return;
Alex Lorenz12b554e2015-06-24 17:34:58 +00001564 // The '%noreg' register is the register 0.
1565 Names2Regs.insert(std::make_pair("noreg", 0));
Alex Lorenzf3db51de2015-06-23 16:35:26 +00001566 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1567 assert(TRI && "Expected target register info");
1568 for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
1569 bool WasInserted =
1570 Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
1571 .second;
1572 (void)WasInserted;
1573 assert(WasInserted && "Expected registers to be unique case-insensitively");
1574 }
1575}
1576
1577bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
1578 initNames2Regs();
1579 auto RegInfo = Names2Regs.find(RegName);
1580 if (RegInfo == Names2Regs.end())
1581 return true;
1582 Reg = RegInfo->getValue();
1583 return false;
1584}
1585
Alex Lorenz8f6f4282015-06-29 16:57:06 +00001586void MIParser::initNames2RegMasks() {
1587 if (!Names2RegMasks.empty())
1588 return;
1589 const auto *TRI = MF.getSubtarget().getRegisterInfo();
1590 assert(TRI && "Expected target register info");
1591 ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
1592 ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
1593 assert(RegMasks.size() == RegMaskNames.size());
1594 for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
1595 Names2RegMasks.insert(
1596 std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
1597}
1598
1599const uint32_t *MIParser::getRegMask(StringRef Identifier) {
1600 initNames2RegMasks();
1601 auto RegMaskInfo = Names2RegMasks.find(Identifier);
1602 if (RegMaskInfo == Names2RegMasks.end())
1603 return nullptr;
1604 return RegMaskInfo->getValue();
1605}
1606
Alex Lorenz2eacca82015-07-13 23:24:34 +00001607void MIParser::initNames2SubRegIndices() {
1608 if (!Names2SubRegIndices.empty())
1609 return;
1610 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1611 for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
1612 Names2SubRegIndices.insert(
1613 std::make_pair(StringRef(TRI->getSubRegIndexName(I)).lower(), I));
1614}
1615
1616unsigned MIParser::getSubRegIndex(StringRef Name) {
1617 initNames2SubRegIndices();
1618 auto SubRegInfo = Names2SubRegIndices.find(Name);
1619 if (SubRegInfo == Names2SubRegIndices.end())
1620 return 0;
1621 return SubRegInfo->getValue();
1622}
1623
Alex Lorenzcba8c5f2015-08-06 23:57:04 +00001624static void initSlots2BasicBlocks(
1625 const Function &F,
1626 DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
1627 ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
Alex Lorenz8a1915b2015-07-27 22:42:41 +00001628 MST.incorporateFunction(F);
1629 for (auto &BB : F) {
1630 if (BB.hasName())
1631 continue;
1632 int Slot = MST.getLocalSlot(&BB);
1633 if (Slot == -1)
1634 continue;
1635 Slots2BasicBlocks.insert(std::make_pair(unsigned(Slot), &BB));
1636 }
1637}
1638
Alex Lorenzcba8c5f2015-08-06 23:57:04 +00001639static const BasicBlock *getIRBlockFromSlot(
1640 unsigned Slot,
1641 const DenseMap<unsigned, const BasicBlock *> &Slots2BasicBlocks) {
Alex Lorenz8a1915b2015-07-27 22:42:41 +00001642 auto BlockInfo = Slots2BasicBlocks.find(Slot);
1643 if (BlockInfo == Slots2BasicBlocks.end())
1644 return nullptr;
1645 return BlockInfo->second;
1646}
1647
Alex Lorenzcba8c5f2015-08-06 23:57:04 +00001648const BasicBlock *MIParser::getIRBlock(unsigned Slot) {
1649 if (Slots2BasicBlocks.empty())
1650 initSlots2BasicBlocks(*MF.getFunction(), Slots2BasicBlocks);
1651 return getIRBlockFromSlot(Slot, Slots2BasicBlocks);
1652}
1653
1654const BasicBlock *MIParser::getIRBlock(unsigned Slot, const Function &F) {
1655 if (&F == MF.getFunction())
1656 return getIRBlock(Slot);
1657 DenseMap<unsigned, const BasicBlock *> CustomSlots2BasicBlocks;
1658 initSlots2BasicBlocks(F, CustomSlots2BasicBlocks);
1659 return getIRBlockFromSlot(Slot, CustomSlots2BasicBlocks);
1660}
1661
Alex Lorenzef5c1962015-07-28 23:02:45 +00001662void MIParser::initNames2TargetIndices() {
1663 if (!Names2TargetIndices.empty())
1664 return;
1665 const auto *TII = MF.getSubtarget().getInstrInfo();
1666 assert(TII && "Expected target instruction info");
1667 auto Indices = TII->getSerializableTargetIndices();
1668 for (const auto &I : Indices)
1669 Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
1670}
1671
1672bool MIParser::getTargetIndex(StringRef Name, int &Index) {
1673 initNames2TargetIndices();
1674 auto IndexInfo = Names2TargetIndices.find(Name);
1675 if (IndexInfo == Names2TargetIndices.end())
1676 return true;
1677 Index = IndexInfo->second;
1678 return false;
1679}
1680
Alex Lorenz49873a82015-08-06 00:44:07 +00001681void MIParser::initNames2DirectTargetFlags() {
1682 if (!Names2DirectTargetFlags.empty())
1683 return;
1684 const auto *TII = MF.getSubtarget().getInstrInfo();
1685 assert(TII && "Expected target instruction info");
1686 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
1687 for (const auto &I : Flags)
1688 Names2DirectTargetFlags.insert(
1689 std::make_pair(StringRef(I.second), I.first));
1690}
1691
1692bool MIParser::getDirectTargetFlag(StringRef Name, unsigned &Flag) {
1693 initNames2DirectTargetFlags();
1694 auto FlagInfo = Names2DirectTargetFlags.find(Name);
1695 if (FlagInfo == Names2DirectTargetFlags.end())
1696 return true;
1697 Flag = FlagInfo->second;
1698 return false;
1699}
1700
Alex Lorenz5022f6b2015-08-13 23:10:16 +00001701bool llvm::parseMachineBasicBlockDefinitions(MachineFunction &MF, StringRef Src,
1702 PerFunctionMIParsingState &PFS,
1703 const SlotMapping &IRSlots,
1704 SMDiagnostic &Error) {
1705 SourceMgr SM;
1706 SM.AddNewSourceBuffer(
1707 MemoryBuffer::getMemBuffer(Src, "", /*RequiresNullTerminator=*/false),
1708 SMLoc());
1709 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1710 .parseBasicBlockDefinitions(PFS.MBBSlots);
1711}
1712
1713bool llvm::parseMachineInstructions(MachineFunction &MF, StringRef Src,
1714 const PerFunctionMIParsingState &PFS,
1715 const SlotMapping &IRSlots,
1716 SMDiagnostic &Error) {
1717 SourceMgr SM;
1718 SM.AddNewSourceBuffer(
1719 MemoryBuffer::getMemBuffer(Src, "", /*RequiresNullTerminator=*/false),
1720 SMLoc());
1721 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseBasicBlocks();
Alex Lorenz8e0a1b42015-06-22 17:02:30 +00001722}
Alex Lorenzf09df002015-06-30 18:16:42 +00001723
Alex Lorenz7a503fa2015-07-07 17:46:43 +00001724bool llvm::parseMBBReference(MachineBasicBlock *&MBB, SourceMgr &SM,
1725 MachineFunction &MF, StringRef Src,
1726 const PerFunctionMIParsingState &PFS,
1727 const SlotMapping &IRSlots, SMDiagnostic &Error) {
Alex Lorenz1ea60892015-07-27 20:29:27 +00001728 return MIParser(SM, MF, Error, Src, PFS, IRSlots).parseStandaloneMBB(MBB);
Alex Lorenzf09df002015-06-30 18:16:42 +00001729}
Alex Lorenz9fab3702015-07-14 21:24:41 +00001730
1731bool llvm::parseNamedRegisterReference(unsigned &Reg, SourceMgr &SM,
1732 MachineFunction &MF, StringRef Src,
1733 const PerFunctionMIParsingState &PFS,
1734 const SlotMapping &IRSlots,
1735 SMDiagnostic &Error) {
Alex Lorenz1ea60892015-07-27 20:29:27 +00001736 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1737 .parseStandaloneNamedRegister(Reg);
Alex Lorenz9fab3702015-07-14 21:24:41 +00001738}
Alex Lorenz12045a42015-07-27 17:42:45 +00001739
1740bool llvm::parseVirtualRegisterReference(unsigned &Reg, SourceMgr &SM,
1741 MachineFunction &MF, StringRef Src,
1742 const PerFunctionMIParsingState &PFS,
1743 const SlotMapping &IRSlots,
1744 SMDiagnostic &Error) {
1745 return MIParser(SM, MF, Error, Src, PFS, IRSlots)
1746 .parseStandaloneVirtualRegister(Reg);
1747}