MIR Serialization: Serialize global address machine operands.
[oota-llvm.git] / lib / CodeGen / MIRParser / MIParser.cpp
1 //===- MIParser.cpp - Machine instructions parser implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the parsing of machine instructions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "MIParser.h"
15 #include "MILexer.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/AsmParser/SlotMapping.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include "llvm/Target/TargetSubtargetInfo.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26
27 using namespace llvm;
28
29 namespace {
30
31 class MIParser {
32   SourceMgr &SM;
33   MachineFunction &MF;
34   SMDiagnostic &Error;
35   StringRef Source, CurrentSource;
36   MIToken Token;
37   /// Maps from basic block numbers to MBBs.
38   const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots;
39   /// Maps from indices to unnamed global values and metadata nodes.
40   const SlotMapping &IRSlots;
41   /// Maps from instruction names to op codes.
42   StringMap<unsigned> Names2InstrOpCodes;
43   /// Maps from register names to registers.
44   StringMap<unsigned> Names2Regs;
45
46 public:
47   MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
48            StringRef Source,
49            const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
50            const SlotMapping &IRSlots);
51
52   void lex();
53
54   /// Report an error at the current location with the given message.
55   ///
56   /// This function always return true.
57   bool error(const Twine &Msg);
58
59   /// Report an error at the given location with the given message.
60   ///
61   /// This function always return true.
62   bool error(StringRef::iterator Loc, const Twine &Msg);
63
64   MachineInstr *parse();
65
66   bool parseRegister(unsigned &Reg);
67   bool parseRegisterOperand(MachineOperand &Dest, bool IsDef = false);
68   bool parseImmediateOperand(MachineOperand &Dest);
69   bool parseMBBOperand(MachineOperand &Dest);
70   bool parseGlobalAddressOperand(MachineOperand &Dest);
71   bool parseMachineOperand(MachineOperand &Dest);
72
73 private:
74   /// Convert the integer literal in the current token into an unsigned integer.
75   ///
76   /// Return true if an error occurred.
77   bool getUnsigned(unsigned &Result);
78
79   void initNames2InstrOpCodes();
80
81   /// Try to convert an instruction name to an opcode. Return true if the
82   /// instruction name is invalid.
83   bool parseInstrName(StringRef InstrName, unsigned &OpCode);
84
85   bool parseInstruction(unsigned &OpCode);
86
87   void initNames2Regs();
88
89   /// Try to convert a register name to a register number. Return true if the
90   /// register name is invalid.
91   bool getRegisterByName(StringRef RegName, unsigned &Reg);
92 };
93
94 } // end anonymous namespace
95
96 MIParser::MIParser(SourceMgr &SM, MachineFunction &MF, SMDiagnostic &Error,
97                    StringRef Source,
98                    const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
99                    const SlotMapping &IRSlots)
100     : SM(SM), MF(MF), Error(Error), Source(Source), CurrentSource(Source),
101       Token(MIToken::Error, StringRef()), MBBSlots(MBBSlots), IRSlots(IRSlots) {
102 }
103
104 void MIParser::lex() {
105   CurrentSource = lexMIToken(
106       CurrentSource, Token,
107       [this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
108 }
109
110 bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
111
112 bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
113   // TODO: Get the proper location in the MIR file, not just a location inside
114   // the string.
115   assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
116   Error = SMDiagnostic(
117       SM, SMLoc(),
118       SM.getMemoryBuffer(SM.getMainFileID())->getBufferIdentifier(), 1,
119       Loc - Source.data(), SourceMgr::DK_Error, Msg.str(), Source, None, None);
120   return true;
121 }
122
123 MachineInstr *MIParser::parse() {
124   lex();
125
126   // Parse any register operands before '='
127   // TODO: Allow parsing of multiple operands before '='
128   MachineOperand MO = MachineOperand::CreateImm(0);
129   SmallVector<MachineOperand, 8> Operands;
130   if (Token.isRegister()) {
131     if (parseRegisterOperand(MO, /*IsDef=*/true))
132       return nullptr;
133     Operands.push_back(MO);
134     if (Token.isNot(MIToken::equal)) {
135       error("expected '='");
136       return nullptr;
137     }
138     lex();
139   }
140
141   unsigned OpCode;
142   if (Token.isError() || parseInstruction(OpCode))
143     return nullptr;
144
145   // TODO: Parse the instruction flags and memory operands.
146
147   // Parse the remaining machine operands.
148   while (Token.isNot(MIToken::Eof)) {
149     if (parseMachineOperand(MO))
150       return nullptr;
151     Operands.push_back(MO);
152     if (Token.is(MIToken::Eof))
153       break;
154     if (Token.isNot(MIToken::comma)) {
155       error("expected ',' before the next machine operand");
156       return nullptr;
157     }
158     lex();
159   }
160
161   const auto &MCID = MF.getSubtarget().getInstrInfo()->get(OpCode);
162
163   // Verify machine operands.
164   if (!MCID.isVariadic()) {
165     for (size_t I = 0, E = Operands.size(); I < E; ++I) {
166       if (I < MCID.getNumOperands())
167         continue;
168       // Mark this register as implicit to prevent an assertion when it's added
169       // to an instruction. This is a temporary workaround until the implicit
170       // register flag can be parsed.
171       Operands[I].setImplicit();
172     }
173   }
174
175   // TODO: Determine the implicit behaviour when implicit register flags are
176   // parsed.
177   auto *MI = MF.CreateMachineInstr(MCID, DebugLoc(), /*NoImplicit=*/true);
178   for (const auto &Operand : Operands)
179     MI->addOperand(MF, Operand);
180   return MI;
181 }
182
183 bool MIParser::parseInstruction(unsigned &OpCode) {
184   if (Token.isNot(MIToken::Identifier))
185     return error("expected a machine instruction");
186   StringRef InstrName = Token.stringValue();
187   if (parseInstrName(InstrName, OpCode))
188     return error(Twine("unknown machine instruction name '") + InstrName + "'");
189   lex();
190   return false;
191 }
192
193 bool MIParser::parseRegister(unsigned &Reg) {
194   switch (Token.kind()) {
195   case MIToken::underscore:
196     Reg = 0;
197     break;
198   case MIToken::NamedRegister: {
199     StringRef Name = Token.stringValue();
200     if (getRegisterByName(Name, Reg))
201       return error(Twine("unknown register name '") + Name + "'");
202     break;
203   }
204   // TODO: Parse other register kinds.
205   default:
206     llvm_unreachable("The current token should be a register");
207   }
208   return false;
209 }
210
211 bool MIParser::parseRegisterOperand(MachineOperand &Dest, bool IsDef) {
212   unsigned Reg;
213   // TODO: Parse register flags.
214   if (parseRegister(Reg))
215     return true;
216   lex();
217   // TODO: Parse subregister.
218   Dest = MachineOperand::CreateReg(Reg, IsDef);
219   return false;
220 }
221
222 bool MIParser::parseImmediateOperand(MachineOperand &Dest) {
223   assert(Token.is(MIToken::IntegerLiteral));
224   const APSInt &Int = Token.integerValue();
225   if (Int.getMinSignedBits() > 64)
226     // TODO: Replace this with an error when we can parse CIMM Machine Operands.
227     llvm_unreachable("Can't parse large integer literals yet!");
228   Dest = MachineOperand::CreateImm(Int.getExtValue());
229   lex();
230   return false;
231 }
232
233 bool MIParser::getUnsigned(unsigned &Result) {
234   assert(Token.hasIntegerValue() && "Expected a token with an integer value");
235   const uint64_t Limit = uint64_t(std::numeric_limits<unsigned>::max()) + 1;
236   uint64_t Val64 = Token.integerValue().getLimitedValue(Limit);
237   if (Val64 == Limit)
238     return error("expected 32-bit integer (too large)");
239   Result = Val64;
240   return false;
241 }
242
243 bool MIParser::parseMBBOperand(MachineOperand &Dest) {
244   assert(Token.is(MIToken::MachineBasicBlock));
245   unsigned Number;
246   if (getUnsigned(Number))
247     return true;
248   auto MBBInfo = MBBSlots.find(Number);
249   if (MBBInfo == MBBSlots.end())
250     return error(Twine("use of undefined machine basic block #") +
251                  Twine(Number));
252   MachineBasicBlock *MBB = MBBInfo->second;
253   if (!Token.stringValue().empty() && Token.stringValue() != MBB->getName())
254     return error(Twine("the name of machine basic block #") + Twine(Number) +
255                  " isn't '" + Token.stringValue() + "'");
256   Dest = MachineOperand::CreateMBB(MBB);
257   lex();
258   return false;
259 }
260
261 bool MIParser::parseGlobalAddressOperand(MachineOperand &Dest) {
262   switch (Token.kind()) {
263   case MIToken::NamedGlobalValue: {
264     auto Name = Token.stringValue();
265     const Module *M = MF.getFunction()->getParent();
266     if (const auto *GV = M->getNamedValue(Name)) {
267       Dest = MachineOperand::CreateGA(GV, /*Offset=*/0);
268       break;
269     }
270     return error(Twine("use of undefined global value '@") + Name + "'");
271   }
272   case MIToken::GlobalValue: {
273     unsigned GVIdx;
274     if (getUnsigned(GVIdx))
275       return true;
276     if (GVIdx >= IRSlots.GlobalValues.size())
277       return error(Twine("use of undefined global value '@") + Twine(GVIdx) +
278                    "'");
279     Dest = MachineOperand::CreateGA(IRSlots.GlobalValues[GVIdx],
280                                     /*Offset=*/0);
281     break;
282   }
283   default:
284     llvm_unreachable("The current token should be a global value");
285   }
286   // TODO: Parse offset and target flags.
287   lex();
288   return false;
289 }
290
291 bool MIParser::parseMachineOperand(MachineOperand &Dest) {
292   switch (Token.kind()) {
293   case MIToken::underscore:
294   case MIToken::NamedRegister:
295     return parseRegisterOperand(Dest);
296   case MIToken::IntegerLiteral:
297     return parseImmediateOperand(Dest);
298   case MIToken::MachineBasicBlock:
299     return parseMBBOperand(Dest);
300   case MIToken::GlobalValue:
301   case MIToken::NamedGlobalValue:
302     return parseGlobalAddressOperand(Dest);
303   case MIToken::Error:
304     return true;
305   default:
306     // TODO: parse the other machine operands.
307     return error("expected a machine operand");
308   }
309   return false;
310 }
311
312 void MIParser::initNames2InstrOpCodes() {
313   if (!Names2InstrOpCodes.empty())
314     return;
315   const auto *TII = MF.getSubtarget().getInstrInfo();
316   assert(TII && "Expected target instruction info");
317   for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
318     Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
319 }
320
321 bool MIParser::parseInstrName(StringRef InstrName, unsigned &OpCode) {
322   initNames2InstrOpCodes();
323   auto InstrInfo = Names2InstrOpCodes.find(InstrName);
324   if (InstrInfo == Names2InstrOpCodes.end())
325     return true;
326   OpCode = InstrInfo->getValue();
327   return false;
328 }
329
330 void MIParser::initNames2Regs() {
331   if (!Names2Regs.empty())
332     return;
333   // The '%noreg' register is the register 0.
334   Names2Regs.insert(std::make_pair("noreg", 0));
335   const auto *TRI = MF.getSubtarget().getRegisterInfo();
336   assert(TRI && "Expected target register info");
337   for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
338     bool WasInserted =
339         Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
340             .second;
341     (void)WasInserted;
342     assert(WasInserted && "Expected registers to be unique case-insensitively");
343   }
344 }
345
346 bool MIParser::getRegisterByName(StringRef RegName, unsigned &Reg) {
347   initNames2Regs();
348   auto RegInfo = Names2Regs.find(RegName);
349   if (RegInfo == Names2Regs.end())
350     return true;
351   Reg = RegInfo->getValue();
352   return false;
353 }
354
355 MachineInstr *
356 llvm::parseMachineInstr(SourceMgr &SM, MachineFunction &MF, StringRef Src,
357                         const DenseMap<unsigned, MachineBasicBlock *> &MBBSlots,
358                         const SlotMapping &IRSlots, SMDiagnostic &Error) {
359   return MIParser(SM, MF, Error, Src, MBBSlots, IRSlots).parse();
360 }