MIR Serialization: Serialize the 'volatile' machine memory operand flag.
[oota-llvm.git] / lib / CodeGen / MIRParser / MILexer.cpp
1 //===- MILexer.cpp - Machine instructions lexer 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 lexing of machine instructions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "MILexer.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include <cctype>
19
20 using namespace llvm;
21
22 namespace {
23
24 /// This class provides a way to iterate and get characters from the source
25 /// string.
26 class Cursor {
27   const char *Ptr;
28   const char *End;
29
30 public:
31   Cursor(NoneType) : Ptr(nullptr), End(nullptr) {}
32
33   explicit Cursor(StringRef Str) {
34     Ptr = Str.data();
35     End = Ptr + Str.size();
36   }
37
38   bool isEOF() const { return Ptr == End; }
39
40   char peek(int I = 0) const { return End - Ptr <= I ? 0 : Ptr[I]; }
41
42   void advance(unsigned I = 1) { Ptr += I; }
43
44   StringRef remaining() const { return StringRef(Ptr, End - Ptr); }
45
46   StringRef upto(Cursor C) const {
47     assert(C.Ptr >= Ptr && C.Ptr <= End);
48     return StringRef(Ptr, C.Ptr - Ptr);
49   }
50
51   StringRef::iterator location() const { return Ptr; }
52
53   operator bool() const { return Ptr != nullptr; }
54 };
55
56 } // end anonymous namespace
57
58 /// Skip the leading whitespace characters and return the updated cursor.
59 static Cursor skipWhitespace(Cursor C) {
60   while (isspace(C.peek()))
61     C.advance();
62   return C;
63 }
64
65 /// Return true if the given character satisfies the following regular
66 /// expression: [-a-zA-Z$._0-9]
67 static bool isIdentifierChar(char C) {
68   return isalpha(C) || isdigit(C) || C == '_' || C == '-' || C == '.' ||
69          C == '$';
70 }
71
72 void MIToken::unescapeQuotedStringValue(std::string &Str) const {
73   assert(isStringValueQuoted() && "String value isn't quoted");
74   StringRef Value = Range.drop_front(StringOffset);
75   assert(Value.front() == '"' && Value.back() == '"');
76   Cursor C = Cursor(Value.substr(1, Value.size() - 2));
77
78   Str.clear();
79   Str.reserve(C.remaining().size());
80   while (!C.isEOF()) {
81     char Char = C.peek();
82     if (Char == '\\') {
83       if (C.peek(1) == '\\') {
84         // Two '\' become one
85         Str += '\\';
86         C.advance(2);
87         continue;
88       }
89       if (isxdigit(C.peek(1)) && isxdigit(C.peek(2))) {
90         Str += hexDigitValue(C.peek(1)) * 16 + hexDigitValue(C.peek(2));
91         C.advance(3);
92         continue;
93       }
94     }
95     Str += Char;
96     C.advance();
97   }
98 }
99
100 /// Lex a string constant using the following regular expression: \"[^\"]*\"
101 static Cursor lexStringConstant(
102     Cursor C,
103     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
104   assert(C.peek() == '"');
105   for (C.advance(); C.peek() != '"'; C.advance()) {
106     if (C.isEOF()) {
107       ErrorCallback(
108           C.location(),
109           "end of machine instruction reached before the closing '\"'");
110       return None;
111     }
112   }
113   C.advance();
114   return C;
115 }
116
117 static Cursor lexName(
118     Cursor C, MIToken &Token, MIToken::TokenKind Type,
119     MIToken::TokenKind QuotedType, unsigned PrefixLength,
120     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
121   auto Range = C;
122   C.advance(PrefixLength);
123   if (C.peek() == '"') {
124     if (Cursor R = lexStringConstant(C, ErrorCallback)) {
125       Token = MIToken(QuotedType, Range.upto(R), PrefixLength);
126       return R;
127     }
128     Token = MIToken(MIToken::Error, Range.remaining());
129     return Range;
130   }
131   while (isIdentifierChar(C.peek()))
132     C.advance();
133   Token = MIToken(Type, Range.upto(C), PrefixLength);
134   return C;
135 }
136
137 static MIToken::TokenKind getIdentifierKind(StringRef Identifier) {
138   return StringSwitch<MIToken::TokenKind>(Identifier)
139       .Case("_", MIToken::underscore)
140       .Case("implicit", MIToken::kw_implicit)
141       .Case("implicit-def", MIToken::kw_implicit_define)
142       .Case("dead", MIToken::kw_dead)
143       .Case("killed", MIToken::kw_killed)
144       .Case("undef", MIToken::kw_undef)
145       .Case("frame-setup", MIToken::kw_frame_setup)
146       .Case("debug-location", MIToken::kw_debug_location)
147       .Case(".cfi_offset", MIToken::kw_cfi_offset)
148       .Case(".cfi_def_cfa_register", MIToken::kw_cfi_def_cfa_register)
149       .Case(".cfi_def_cfa_offset", MIToken::kw_cfi_def_cfa_offset)
150       .Case(".cfi_def_cfa", MIToken::kw_cfi_def_cfa)
151       .Case("blockaddress", MIToken::kw_blockaddress)
152       .Case("target-index", MIToken::kw_target_index)
153       .Case("half", MIToken::kw_half)
154       .Case("float", MIToken::kw_float)
155       .Case("double", MIToken::kw_double)
156       .Case("x86_fp80", MIToken::kw_x86_fp80)
157       .Case("fp128", MIToken::kw_fp128)
158       .Case("ppc_fp128", MIToken::kw_ppc_fp128)
159       .Case("volatile", MIToken::kw_volatile)
160       .Default(MIToken::Identifier);
161 }
162
163 static Cursor maybeLexIdentifier(Cursor C, MIToken &Token) {
164   if (!isalpha(C.peek()) && C.peek() != '_' && C.peek() != '.')
165     return None;
166   auto Range = C;
167   while (isIdentifierChar(C.peek()))
168     C.advance();
169   auto Identifier = Range.upto(C);
170   Token = MIToken(getIdentifierKind(Identifier), Identifier);
171   return C;
172 }
173
174 static Cursor maybeLexMachineBasicBlock(
175     Cursor C, MIToken &Token,
176     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
177   if (!C.remaining().startswith("%bb."))
178     return None;
179   auto Range = C;
180   C.advance(4); // Skip '%bb.'
181   if (!isdigit(C.peek())) {
182     Token = MIToken(MIToken::Error, C.remaining());
183     ErrorCallback(C.location(), "expected a number after '%bb.'");
184     return C;
185   }
186   auto NumberRange = C;
187   while (isdigit(C.peek()))
188     C.advance();
189   StringRef Number = NumberRange.upto(C);
190   unsigned StringOffset = 4 + Number.size(); // Drop '%bb.<id>'
191   if (C.peek() == '.') {
192     C.advance(); // Skip '.'
193     ++StringOffset;
194     while (isIdentifierChar(C.peek()))
195       C.advance();
196   }
197   Token = MIToken(MIToken::MachineBasicBlock, Range.upto(C), APSInt(Number),
198                   StringOffset);
199   return C;
200 }
201
202 static Cursor maybeLexIndex(Cursor C, MIToken &Token, StringRef Rule,
203                             MIToken::TokenKind Kind) {
204   if (!C.remaining().startswith(Rule) || !isdigit(C.peek(Rule.size())))
205     return None;
206   auto Range = C;
207   C.advance(Rule.size());
208   auto NumberRange = C;
209   while (isdigit(C.peek()))
210     C.advance();
211   Token = MIToken(Kind, Range.upto(C), APSInt(NumberRange.upto(C)));
212   return C;
213 }
214
215 static Cursor maybeLexIndexAndName(Cursor C, MIToken &Token, StringRef Rule,
216                                    MIToken::TokenKind Kind) {
217   if (!C.remaining().startswith(Rule) || !isdigit(C.peek(Rule.size())))
218     return None;
219   auto Range = C;
220   C.advance(Rule.size());
221   auto NumberRange = C;
222   while (isdigit(C.peek()))
223     C.advance();
224   StringRef Number = NumberRange.upto(C);
225   unsigned StringOffset = Rule.size() + Number.size();
226   if (C.peek() == '.') {
227     C.advance();
228     ++StringOffset;
229     while (isIdentifierChar(C.peek()))
230       C.advance();
231   }
232   Token = MIToken(Kind, Range.upto(C), APSInt(Number), StringOffset);
233   return C;
234 }
235
236 static Cursor maybeLexJumpTableIndex(Cursor C, MIToken &Token) {
237   return maybeLexIndex(C, Token, "%jump-table.", MIToken::JumpTableIndex);
238 }
239
240 static Cursor maybeLexStackObject(Cursor C, MIToken &Token) {
241   return maybeLexIndexAndName(C, Token, "%stack.", MIToken::StackObject);
242 }
243
244 static Cursor maybeLexFixedStackObject(Cursor C, MIToken &Token) {
245   return maybeLexIndex(C, Token, "%fixed-stack.", MIToken::FixedStackObject);
246 }
247
248 static Cursor maybeLexConstantPoolItem(Cursor C, MIToken &Token) {
249   return maybeLexIndex(C, Token, "%const.", MIToken::ConstantPoolItem);
250 }
251
252 static Cursor maybeLexIRBlock(
253     Cursor C, MIToken &Token,
254     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
255   const StringRef Rule = "%ir-block.";
256   if (!C.remaining().startswith(Rule))
257     return None;
258   if (isdigit(C.peek(Rule.size())))
259     return maybeLexIndex(C, Token, Rule, MIToken::IRBlock);
260   return lexName(C, Token, MIToken::NamedIRBlock, MIToken::QuotedNamedIRBlock,
261                  Rule.size(), ErrorCallback);
262 }
263
264 static Cursor maybeLexIRValue(
265     Cursor C, MIToken &Token,
266     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
267   const StringRef Rule = "%ir.";
268   if (!C.remaining().startswith(Rule))
269     return None;
270   return lexName(C, Token, MIToken::NamedIRValue, MIToken::QuotedNamedIRValue,
271                  Rule.size(), ErrorCallback);
272 }
273
274 static Cursor lexVirtualRegister(Cursor C, MIToken &Token) {
275   auto Range = C;
276   C.advance(); // Skip '%'
277   auto NumberRange = C;
278   while (isdigit(C.peek()))
279     C.advance();
280   Token = MIToken(MIToken::VirtualRegister, Range.upto(C),
281                   APSInt(NumberRange.upto(C)));
282   return C;
283 }
284
285 static Cursor maybeLexRegister(Cursor C, MIToken &Token) {
286   if (C.peek() != '%')
287     return None;
288   if (isdigit(C.peek(1)))
289     return lexVirtualRegister(C, Token);
290   auto Range = C;
291   C.advance(); // Skip '%'
292   while (isIdentifierChar(C.peek()))
293     C.advance();
294   Token = MIToken(MIToken::NamedRegister, Range.upto(C),
295                   /*StringOffset=*/1); // Drop the '%'
296   return C;
297 }
298
299 static Cursor maybeLexGlobalValue(
300     Cursor C, MIToken &Token,
301     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
302   if (C.peek() != '@')
303     return None;
304   if (!isdigit(C.peek(1)))
305     return lexName(C, Token, MIToken::NamedGlobalValue,
306                    MIToken::QuotedNamedGlobalValue, /*PrefixLength=*/1,
307                    ErrorCallback);
308   auto Range = C;
309   C.advance(1); // Skip the '@'
310   auto NumberRange = C;
311   while (isdigit(C.peek()))
312     C.advance();
313   Token =
314       MIToken(MIToken::GlobalValue, Range.upto(C), APSInt(NumberRange.upto(C)));
315   return C;
316 }
317
318 static Cursor maybeLexExternalSymbol(
319     Cursor C, MIToken &Token,
320     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
321   if (C.peek() != '$')
322     return None;
323   return lexName(C, Token, MIToken::ExternalSymbol,
324                  MIToken::QuotedExternalSymbol,
325                  /*PrefixLength=*/1, ErrorCallback);
326 }
327
328 static bool isValidHexFloatingPointPrefix(char C) {
329   return C == 'H' || C == 'K' || C == 'L' || C == 'M';
330 }
331
332 static Cursor maybeLexHexFloatingPointLiteral(Cursor C, MIToken &Token) {
333   if (C.peek() != '0' || C.peek(1) != 'x')
334     return None;
335   Cursor Range = C;
336   C.advance(2); // Skip '0x'
337   if (isValidHexFloatingPointPrefix(C.peek()))
338     C.advance();
339   while (isxdigit(C.peek()))
340     C.advance();
341   Token = MIToken(MIToken::FloatingPointLiteral, Range.upto(C));
342   return C;
343 }
344
345 static Cursor lexFloatingPointLiteral(Cursor Range, Cursor C, MIToken &Token) {
346   C.advance();
347   // Skip over [0-9]*([eE][-+]?[0-9]+)?
348   while (isdigit(C.peek()))
349     C.advance();
350   if ((C.peek() == 'e' || C.peek() == 'E') &&
351       (isdigit(C.peek(1)) ||
352        ((C.peek(1) == '-' || C.peek(1) == '+') && isdigit(C.peek(2))))) {
353     C.advance(2);
354     while (isdigit(C.peek()))
355       C.advance();
356   }
357   Token = MIToken(MIToken::FloatingPointLiteral, Range.upto(C));
358   return C;
359 }
360
361 static Cursor maybeLexNumericalLiteral(Cursor C, MIToken &Token) {
362   if (!isdigit(C.peek()) && (C.peek() != '-' || !isdigit(C.peek(1))))
363     return None;
364   auto Range = C;
365   C.advance();
366   while (isdigit(C.peek()))
367     C.advance();
368   if (C.peek() == '.')
369     return lexFloatingPointLiteral(Range, C, Token);
370   StringRef StrVal = Range.upto(C);
371   Token = MIToken(MIToken::IntegerLiteral, StrVal, APSInt(StrVal));
372   return C;
373 }
374
375 static MIToken::TokenKind symbolToken(char C) {
376   switch (C) {
377   case ',':
378     return MIToken::comma;
379   case '=':
380     return MIToken::equal;
381   case ':':
382     return MIToken::colon;
383   case '!':
384     return MIToken::exclaim;
385   case '(':
386     return MIToken::lparen;
387   case ')':
388     return MIToken::rparen;
389   default:
390     return MIToken::Error;
391   }
392 }
393
394 static Cursor maybeLexSymbol(Cursor C, MIToken &Token) {
395   MIToken::TokenKind Kind;
396   unsigned Length = 1;
397   if (C.peek() == ':' && C.peek(1) == ':') {
398     Kind = MIToken::coloncolon;
399     Length = 2;
400   } else
401     Kind = symbolToken(C.peek());
402   if (Kind == MIToken::Error)
403     return None;
404   auto Range = C;
405   C.advance(Length);
406   Token = MIToken(Kind, Range.upto(C));
407   return C;
408 }
409
410 StringRef llvm::lexMIToken(
411     StringRef Source, MIToken &Token,
412     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
413   auto C = skipWhitespace(Cursor(Source));
414   if (C.isEOF()) {
415     Token = MIToken(MIToken::Eof, C.remaining());
416     return C.remaining();
417   }
418
419   if (Cursor R = maybeLexIdentifier(C, Token))
420     return R.remaining();
421   if (Cursor R = maybeLexMachineBasicBlock(C, Token, ErrorCallback))
422     return R.remaining();
423   if (Cursor R = maybeLexJumpTableIndex(C, Token))
424     return R.remaining();
425   if (Cursor R = maybeLexStackObject(C, Token))
426     return R.remaining();
427   if (Cursor R = maybeLexFixedStackObject(C, Token))
428     return R.remaining();
429   if (Cursor R = maybeLexConstantPoolItem(C, Token))
430     return R.remaining();
431   if (Cursor R = maybeLexIRBlock(C, Token, ErrorCallback))
432     return R.remaining();
433   if (Cursor R = maybeLexIRValue(C, Token, ErrorCallback))
434     return R.remaining();
435   if (Cursor R = maybeLexRegister(C, Token))
436     return R.remaining();
437   if (Cursor R = maybeLexGlobalValue(C, Token, ErrorCallback))
438     return R.remaining();
439   if (Cursor R = maybeLexExternalSymbol(C, Token, ErrorCallback))
440     return R.remaining();
441   if (Cursor R = maybeLexHexFloatingPointLiteral(C, Token))
442     return R.remaining();
443   if (Cursor R = maybeLexNumericalLiteral(C, Token))
444     return R.remaining();
445   if (Cursor R = maybeLexSymbol(C, Token))
446     return R.remaining();
447
448   Token = MIToken(MIToken::Error, C.remaining());
449   ErrorCallback(C.location(),
450                 Twine("unexpected character '") + Twine(C.peek()) + "'");
451   return C.remaining();
452 }