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