LLVM 20.0.0git
TGLexer.cpp
Go to the documentation of this file.
1//===- TGLexer.cpp - Lexer for TableGen -----------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Implement the Lexer for TableGen.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TGLexer.h"
14#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/Twine.h"
18#include "llvm/Config/config.h" // for strtoull()/strtoll() define
22#include "llvm/TableGen/Error.h"
23#include <algorithm>
24#include <cerrno>
25#include <cstdint>
26#include <cstdio>
27#include <cstdlib>
28#include <cstring>
29
30using namespace llvm;
31
32namespace {
33// A list of supported preprocessing directives with their
34// internal token kinds and names.
35struct PreprocessorDir {
38};
39} // end anonymous namespace
40
41/// Returns true if `C` is a valid character in an identifier. If `First` is
42/// true, returns true if `C` is a valid first character of an identifier,
43/// else returns true if `C` is a valid non-first character of an identifier.
44/// Identifiers match the following regular expression:
45/// [a-zA-Z_][0-9a-zA-Z_]*
46static bool isValidIDChar(char C, bool First) {
47 if (C == '_' || isAlpha(C))
48 return true;
49 return !First && isDigit(C);
50}
51
52constexpr PreprocessorDir PreprocessorDirs[] = {{tgtok::Ifdef, "ifdef"},
53 {tgtok::Ifndef, "ifndef"},
54 {tgtok::Else, "else"},
55 {tgtok::Endif, "endif"},
56 {tgtok::Define, "define"}};
57
58// Returns a pointer past the end of a valid macro name at the start of `Str`.
59// Valid macro names match the regular expression [a-zA-Z_][0-9a-zA-Z_]*.
60static const char *lexMacroName(StringRef Str) {
61 assert(!Str.empty());
62
63 // Macro names start with [a-zA-Z_].
64 const char *Next = Str.begin();
65 if (!isValidIDChar(*Next, /*First=*/true))
66 return Next;
67 // Eat the first character of the name.
68 ++Next;
69
70 // Match the rest of the identifier regex: [0-9a-zA-Z_]*
71 const char *End = Str.end();
72 while (Next != End && isValidIDChar(*Next, /*First=*/false))
73 ++Next;
74 return Next;
75}
76
78 CurBuffer = SrcMgr.getMainFileID();
79 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
80 CurPtr = CurBuf.begin();
81 TokStart = nullptr;
82
83 // Pretend that we enter the "top-level" include file.
84 PrepIncludeStack.push_back(
85 std::make_unique<std::vector<PreprocessorControlDesc>>());
86
87 // Add all macros defined on the command line to the DefinedMacros set.
88 // Check invalid macro names and print fatal error if we find one.
89 for (StringRef MacroName : Macros) {
90 const char *End = lexMacroName(MacroName);
91 if (End != MacroName.end())
92 PrintFatalError("invalid macro name `" + MacroName +
93 "` specified on command line");
94
95 DefinedMacros.insert(MacroName);
96 }
97}
98
100 return SMLoc::getFromPointer(TokStart);
101}
102
104 return {getLoc(), SMLoc::getFromPointer(CurPtr)};
105}
106
107/// ReturnError - Set the error to the specified string at the specified
108/// location. This is defined to always return tgtok::Error.
109tgtok::TokKind TGLexer::ReturnError(SMLoc Loc, const Twine &Msg) {
110 PrintError(Loc, Msg);
111 return tgtok::Error;
112}
113
114tgtok::TokKind TGLexer::ReturnError(const char *Loc, const Twine &Msg) {
115 return ReturnError(SMLoc::getFromPointer(Loc), Msg);
116}
117
118bool TGLexer::processEOF() {
119 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
120 if (ParentIncludeLoc != SMLoc()) {
121 // If prepExitInclude() detects a problem with the preprocessing
122 // control stack, it will return false. Pretend that we reached
123 // the final EOF and stop lexing more tokens by returning false
124 // to LexToken().
125 if (!prepExitInclude(false))
126 return false;
127
128 CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
129 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
130 CurPtr = ParentIncludeLoc.getPointer();
131 // Make sure TokStart points into the parent file's buffer.
132 // LexToken() assigns to it before calling getNextChar(),
133 // so it is pointing into the included file now.
134 TokStart = CurPtr;
135 return true;
136 }
137
138 // Pretend that we exit the "top-level" include file.
139 // Note that in case of an error (e.g. control stack imbalance)
140 // the routine will issue a fatal error.
141 prepExitInclude(true);
142 return false;
143}
144
145int TGLexer::getNextChar() {
146 char CurChar = *CurPtr++;
147 switch (CurChar) {
148 default:
149 return (unsigned char)CurChar;
150
151 case 0: {
152 // A NUL character in the stream is either the end of the current buffer or
153 // a spurious NUL in the file. Disambiguate that here.
154 if (CurPtr - 1 == CurBuf.end()) {
155 --CurPtr; // Arrange for another call to return EOF again.
156 return EOF;
157 }
159 "NUL character is invalid in source; treated as space");
160 return ' ';
161 }
162
163 case '\n':
164 case '\r':
165 // Handle the newline character by ignoring it and incrementing the line
166 // count. However, be careful about 'dos style' files with \n\r in them.
167 // Only treat a \n\r or \r\n as a single line.
168 if ((*CurPtr == '\n' || (*CurPtr == '\r')) &&
169 *CurPtr != CurChar)
170 ++CurPtr; // Eat the two char newline sequence.
171 return '\n';
172 }
173}
174
175int TGLexer::peekNextChar(int Index) const {
176 return *(CurPtr + Index);
177}
178
179tgtok::TokKind TGLexer::LexToken(bool FileOrLineStart) {
180 TokStart = CurPtr;
181 // This always consumes at least one character.
182 int CurChar = getNextChar();
183
184 switch (CurChar) {
185 default:
186 // Handle letters: [a-zA-Z_]
187 if (isValidIDChar(CurChar, /*First=*/true))
188 return LexIdentifier();
189
190 // Unknown character, emit an error.
191 return ReturnError(TokStart, "unexpected character");
192 case EOF:
193 // Lex next token, if we just left an include file.
194 // Note that leaving an include file means that the next
195 // symbol is located at the end of the 'include "..."'
196 // construct, so LexToken() is called with default
197 // false parameter.
198 if (processEOF())
199 return LexToken();
200
201 // Return EOF denoting the end of lexing.
202 return tgtok::Eof;
203
204 case ':': return tgtok::colon;
205 case ';': return tgtok::semi;
206 case ',': return tgtok::comma;
207 case '<': return tgtok::less;
208 case '>': return tgtok::greater;
209 case ']': return tgtok::r_square;
210 case '{': return tgtok::l_brace;
211 case '}': return tgtok::r_brace;
212 case '(': return tgtok::l_paren;
213 case ')': return tgtok::r_paren;
214 case '=': return tgtok::equal;
215 case '?': return tgtok::question;
216 case '#':
217 if (FileOrLineStart) {
218 tgtok::TokKind Kind = prepIsDirective();
219 if (Kind != tgtok::Error)
220 return lexPreprocessor(Kind);
221 }
222
223 return tgtok::paste;
224
225 // The period is a separate case so we can recognize the "..."
226 // range punctuator.
227 case '.':
228 if (peekNextChar(0) == '.') {
229 ++CurPtr; // Eat second dot.
230 if (peekNextChar(0) == '.') {
231 ++CurPtr; // Eat third dot.
232 return tgtok::dotdotdot;
233 }
234 return ReturnError(TokStart, "invalid '..' punctuation");
235 }
236 return tgtok::dot;
237
238 case '\r':
239 PrintFatalError("getNextChar() must never return '\r'");
240 return tgtok::Error;
241
242 case ' ':
243 case '\t':
244 // Ignore whitespace.
245 return LexToken(FileOrLineStart);
246 case '\n':
247 // Ignore whitespace, and identify the new line.
248 return LexToken(true);
249 case '/':
250 // If this is the start of a // comment, skip until the end of the line or
251 // the end of the buffer.
252 if (*CurPtr == '/')
253 SkipBCPLComment();
254 else if (*CurPtr == '*') {
255 if (SkipCComment())
256 return tgtok::Error;
257 } else // Otherwise, this is an error.
258 return ReturnError(TokStart, "unexpected character");
259 return LexToken(FileOrLineStart);
260 case '-': case '+':
261 case '0': case '1': case '2': case '3': case '4': case '5': case '6':
262 case '7': case '8': case '9': {
263 int NextChar = 0;
264 if (isDigit(CurChar)) {
265 // Allow identifiers to start with a number if it is followed by
266 // an identifier. This can happen with paste operations like
267 // foo#8i.
268 int i = 0;
269 do {
270 NextChar = peekNextChar(i++);
271 } while (isDigit(NextChar));
272
273 if (NextChar == 'x' || NextChar == 'b') {
274 // If this is [0-9]b[01] or [0-9]x[0-9A-fa-f] this is most
275 // likely a number.
276 int NextNextChar = peekNextChar(i);
277 switch (NextNextChar) {
278 default:
279 break;
280 case '0': case '1':
281 if (NextChar == 'b')
282 return LexNumber();
283 [[fallthrough]];
284 case '2': case '3': case '4': case '5':
285 case '6': case '7': case '8': case '9':
286 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
287 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
288 if (NextChar == 'x')
289 return LexNumber();
290 break;
291 }
292 }
293 }
294
295 if (isValidIDChar(NextChar, /*First=*/true))
296 return LexIdentifier();
297
298 return LexNumber();
299 }
300 case '"': return LexString();
301 case '$': return LexVarName();
302 case '[': return LexBracket();
303 case '!': return LexExclaim();
304 }
305}
306
307/// LexString - Lex "[^"]*"
308tgtok::TokKind TGLexer::LexString() {
309 const char *StrStart = CurPtr;
310
311 CurStrVal = "";
312
313 while (*CurPtr != '"') {
314 // If we hit the end of the buffer, report an error.
315 if (*CurPtr == 0 && CurPtr == CurBuf.end())
316 return ReturnError(StrStart, "end of file in string literal");
317
318 if (*CurPtr == '\n' || *CurPtr == '\r')
319 return ReturnError(StrStart, "end of line in string literal");
320
321 if (*CurPtr != '\\') {
322 CurStrVal += *CurPtr++;
323 continue;
324 }
325
326 ++CurPtr;
327
328 switch (*CurPtr) {
329 case '\\': case '\'': case '"':
330 // These turn into their literal character.
331 CurStrVal += *CurPtr++;
332 break;
333 case 't':
334 CurStrVal += '\t';
335 ++CurPtr;
336 break;
337 case 'n':
338 CurStrVal += '\n';
339 ++CurPtr;
340 break;
341
342 case '\n':
343 case '\r':
344 return ReturnError(CurPtr, "escaped newlines not supported in tblgen");
345
346 // If we hit the end of the buffer, report an error.
347 case '\0':
348 if (CurPtr == CurBuf.end())
349 return ReturnError(StrStart, "end of file in string literal");
350 [[fallthrough]];
351 default:
352 return ReturnError(CurPtr, "invalid escape in string literal");
353 }
354 }
355
356 ++CurPtr;
357 return tgtok::StrVal;
358}
359
360tgtok::TokKind TGLexer::LexVarName() {
361 if (!isValidIDChar(CurPtr[0], /*First=*/true))
362 return ReturnError(TokStart, "invalid variable name");
363
364 // Otherwise, we're ok, consume the rest of the characters.
365 const char *VarNameStart = CurPtr++;
366
367 while (isValidIDChar(*CurPtr, /*First=*/false))
368 ++CurPtr;
369
370 CurStrVal.assign(VarNameStart, CurPtr);
371 return tgtok::VarName;
372}
373
374tgtok::TokKind TGLexer::LexIdentifier() {
375 // The first letter is [a-zA-Z_].
376 const char *IdentStart = TokStart;
377
378 // Match the rest of the identifier regex: [0-9a-zA-Z_]*
379 while (isValidIDChar(*CurPtr, /*First=*/false))
380 ++CurPtr;
381
382 // Check to see if this identifier is a reserved keyword.
383 StringRef Str(IdentStart, CurPtr-IdentStart);
384
386 .Case("int", tgtok::Int)
387 .Case("bit", tgtok::Bit)
388 .Case("bits", tgtok::Bits)
389 .Case("string", tgtok::String)
390 .Case("list", tgtok::List)
391 .Case("code", tgtok::Code)
392 .Case("dag", tgtok::Dag)
393 .Case("class", tgtok::Class)
394 .Case("def", tgtok::Def)
395 .Case("true", tgtok::TrueVal)
396 .Case("false", tgtok::FalseVal)
397 .Case("foreach", tgtok::Foreach)
398 .Case("defm", tgtok::Defm)
399 .Case("defset", tgtok::Defset)
400 .Case("deftype", tgtok::Deftype)
401 .Case("multiclass", tgtok::MultiClass)
402 .Case("field", tgtok::Field)
403 .Case("let", tgtok::Let)
404 .Case("in", tgtok::In)
405 .Case("defvar", tgtok::Defvar)
406 .Case("include", tgtok::Include)
407 .Case("if", tgtok::If)
408 .Case("then", tgtok::Then)
409 .Case("else", tgtok::ElseKW)
410 .Case("assert", tgtok::Assert)
411 .Case("dump", tgtok::Dump)
413
414 // A couple of tokens require special processing.
415 switch (Kind) {
416 case tgtok::Include:
417 if (LexInclude()) return tgtok::Error;
418 return Lex();
419 case tgtok::Id:
420 CurStrVal.assign(Str.begin(), Str.end());
421 break;
422 default:
423 break;
424 }
425
426 return Kind;
427}
428
429/// LexInclude - We just read the "include" token. Get the string token that
430/// comes next and enter the include.
431bool TGLexer::LexInclude() {
432 // The token after the include must be a string.
433 tgtok::TokKind Tok = LexToken();
434 if (Tok == tgtok::Error) return true;
435 if (Tok != tgtok::StrVal) {
436 PrintError(getLoc(), "expected filename after include");
437 return true;
438 }
439
440 // Get the string.
441 std::string Filename = CurStrVal;
442 std::string IncludedFile;
443
444 CurBuffer = SrcMgr.AddIncludeFile(Filename, SMLoc::getFromPointer(CurPtr),
445 IncludedFile);
446 if (!CurBuffer) {
447 PrintError(getLoc(), "could not find include file '" + Filename + "'");
448 return true;
449 }
450
451 Dependencies.insert(IncludedFile);
452 // Save the line number and lex buffer of the includer.
453 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
454 CurPtr = CurBuf.begin();
455
456 PrepIncludeStack.push_back(
457 std::make_unique<std::vector<PreprocessorControlDesc>>());
458 return false;
459}
460
461/// SkipBCPLComment - Skip over the comment by finding the next CR or LF.
462/// Or we may end up at the end of the buffer.
463void TGLexer::SkipBCPLComment() {
464 ++CurPtr; // skip the second slash.
465 auto EOLPos = CurBuf.find_first_of("\r\n", CurPtr - CurBuf.data());
466 CurPtr = (EOLPos == StringRef::npos) ? CurBuf.end() : CurBuf.data() + EOLPos;
467}
468
469/// SkipCComment - This skips C-style /**/ comments. The only difference from C
470/// is that we allow nesting.
471bool TGLexer::SkipCComment() {
472 ++CurPtr; // skip the star.
473 unsigned CommentDepth = 1;
474
475 while (true) {
476 int CurChar = getNextChar();
477 switch (CurChar) {
478 case EOF:
479 PrintError(TokStart, "unterminated comment");
480 return true;
481 case '*':
482 // End of the comment?
483 if (CurPtr[0] != '/') break;
484
485 ++CurPtr; // End the */.
486 if (--CommentDepth == 0)
487 return false;
488 break;
489 case '/':
490 // Start of a nested comment?
491 if (CurPtr[0] != '*') break;
492 ++CurPtr;
493 ++CommentDepth;
494 break;
495 }
496 }
497}
498
499/// LexNumber - Lex:
500/// [-+]?[0-9]+
501/// 0x[0-9a-fA-F]+
502/// 0b[01]+
503tgtok::TokKind TGLexer::LexNumber() {
504 unsigned Base = 0;
505 const char *NumStart;
506
507 // Check if it's a hex or a binary value.
508 if (CurPtr[-1] == '0') {
509 NumStart = CurPtr + 1;
510 if (CurPtr[0] == 'x') {
511 Base = 16;
512 do
513 ++CurPtr;
514 while (isHexDigit(CurPtr[0]));
515 } else if (CurPtr[0] == 'b') {
516 Base = 2;
517 do
518 ++CurPtr;
519 while (CurPtr[0] == '0' || CurPtr[0] == '1');
520 }
521 }
522
523 // For a hex or binary value, we always convert it to an unsigned value.
524 bool IsMinus = false;
525
526 // Check if it's a decimal value.
527 if (Base == 0) {
528 // Check for a sign without a digit.
529 if (!isDigit(CurPtr[0])) {
530 if (CurPtr[-1] == '-')
531 return tgtok::minus;
532 else if (CurPtr[-1] == '+')
533 return tgtok::plus;
534 }
535
536 Base = 10;
537 NumStart = TokStart;
538 IsMinus = CurPtr[-1] == '-';
539
540 while (isDigit(CurPtr[0]))
541 ++CurPtr;
542 }
543
544 // Requires at least one digit.
545 if (CurPtr == NumStart)
546 return ReturnError(TokStart, "invalid number");
547
548 errno = 0;
549 if (IsMinus)
550 CurIntVal = strtoll(NumStart, nullptr, Base);
551 else
552 CurIntVal = strtoull(NumStart, nullptr, Base);
553
554 if (errno == EINVAL)
555 return ReturnError(TokStart, "invalid number");
556 if (errno == ERANGE)
557 return ReturnError(TokStart, "number out of range");
558
559 return Base == 2 ? tgtok::BinaryIntVal : tgtok::IntVal;
560}
561
562/// LexBracket - We just read '['. If this is a code block, return it,
563/// otherwise return the bracket. Match: '[' and '[{ ( [^}]+ | }[^]] )* }]'
564tgtok::TokKind TGLexer::LexBracket() {
565 if (CurPtr[0] != '{')
566 return tgtok::l_square;
567 ++CurPtr;
568 const char *CodeStart = CurPtr;
569 while (true) {
570 int Char = getNextChar();
571 if (Char == EOF) break;
572
573 if (Char != '}') continue;
574
575 Char = getNextChar();
576 if (Char == EOF) break;
577 if (Char == ']') {
578 CurStrVal.assign(CodeStart, CurPtr-2);
579 return tgtok::CodeFragment;
580 }
581 }
582
583 return ReturnError(CodeStart - 2, "unterminated code block");
584}
585
586/// LexExclaim - Lex '!' and '![a-zA-Z]+'.
587tgtok::TokKind TGLexer::LexExclaim() {
588 if (!isAlpha(*CurPtr))
589 return ReturnError(CurPtr - 1, "invalid \"!operator\"");
590
591 const char *Start = CurPtr++;
592 while (isAlpha(*CurPtr))
593 ++CurPtr;
594
595 // Check to see which operator this is.
597 StringSwitch<tgtok::TokKind>(StringRef(Start, CurPtr - Start))
598 .Case("eq", tgtok::XEq)
599 .Case("ne", tgtok::XNe)
600 .Case("le", tgtok::XLe)
601 .Case("lt", tgtok::XLt)
602 .Case("ge", tgtok::XGe)
603 .Case("gt", tgtok::XGt)
604 .Case("if", tgtok::XIf)
605 .Case("cond", tgtok::XCond)
606 .Case("isa", tgtok::XIsA)
607 .Case("head", tgtok::XHead)
608 .Case("tail", tgtok::XTail)
609 .Case("size", tgtok::XSize)
610 .Case("con", tgtok::XConcat)
611 .Case("dag", tgtok::XDag)
612 .Case("add", tgtok::XADD)
613 .Case("sub", tgtok::XSUB)
614 .Case("mul", tgtok::XMUL)
615 .Case("div", tgtok::XDIV)
616 .Case("not", tgtok::XNOT)
617 .Case("logtwo", tgtok::XLOG2)
618 .Case("and", tgtok::XAND)
619 .Case("or", tgtok::XOR)
620 .Case("xor", tgtok::XXOR)
621 .Case("shl", tgtok::XSHL)
622 .Case("sra", tgtok::XSRA)
623 .Case("srl", tgtok::XSRL)
624 .Case("cast", tgtok::XCast)
625 .Case("empty", tgtok::XEmpty)
626 .Case("subst", tgtok::XSubst)
627 .Case("foldl", tgtok::XFoldl)
628 .Case("foreach", tgtok::XForEach)
629 .Case("filter", tgtok::XFilter)
630 .Case("listconcat", tgtok::XListConcat)
631 .Case("listflatten", tgtok::XListFlatten)
632 .Case("listsplat", tgtok::XListSplat)
633 .Case("listremove", tgtok::XListRemove)
634 .Case("range", tgtok::XRange)
635 .Case("strconcat", tgtok::XStrConcat)
636 .Case("initialized", tgtok::XInitialized)
637 .Case("interleave", tgtok::XInterleave)
638 .Case("substr", tgtok::XSubstr)
639 .Case("find", tgtok::XFind)
640 .Cases("setdagop", "setop", tgtok::XSetDagOp) // !setop is deprecated.
641 .Cases("getdagop", "getop", tgtok::XGetDagOp) // !getop is deprecated.
642 .Case("getdagarg", tgtok::XGetDagArg)
643 .Case("getdagname", tgtok::XGetDagName)
644 .Case("setdagarg", tgtok::XSetDagArg)
645 .Case("setdagname", tgtok::XSetDagName)
646 .Case("exists", tgtok::XExists)
647 .Case("tolower", tgtok::XToLower)
648 .Case("toupper", tgtok::XToUpper)
649 .Case("repr", tgtok::XRepr)
651
652 return Kind != tgtok::Error ? Kind
653 : ReturnError(Start - 1, "unknown operator");
654}
655
656bool TGLexer::prepExitInclude(bool IncludeStackMustBeEmpty) {
657 // Report an error, if preprocessor control stack for the current
658 // file is not empty.
659 if (!PrepIncludeStack.back()->empty()) {
660 prepReportPreprocessorStackError();
661
662 return false;
663 }
664
665 // Pop the preprocessing controls from the include stack.
666 if (PrepIncludeStack.empty()) {
667 PrintFatalError("preprocessor include stack is empty");
668 }
669
670 PrepIncludeStack.pop_back();
671
672 if (IncludeStackMustBeEmpty) {
673 if (!PrepIncludeStack.empty())
674 PrintFatalError("preprocessor include stack is not empty");
675 } else {
676 if (PrepIncludeStack.empty())
677 PrintFatalError("preprocessor include stack is empty");
678 }
679
680 return true;
681}
682
683tgtok::TokKind TGLexer::prepIsDirective() const {
684 for (const auto [Kind, Word] : PreprocessorDirs) {
685 if (StringRef(CurPtr, Word.size()) != Word)
686 continue;
687 int NextChar = peekNextChar(Word.size());
688
689 // Check for whitespace after the directive. If there is no whitespace,
690 // then we do not recognize it as a preprocessing directive.
691
692 // New line and EOF may follow only #else/#endif. It will be reported
693 // as an error for #ifdef/#define after the call to prepLexMacroName().
694 if (NextChar == ' ' || NextChar == '\t' || NextChar == EOF ||
695 NextChar == '\n' ||
696 // It looks like TableGen does not support '\r' as the actual
697 // carriage return, e.g. getNextChar() treats a single '\r'
698 // as '\n'. So we do the same here.
699 NextChar == '\r')
700 return Kind;
701
702 // Allow comments after some directives, e.g.:
703 // #else// OR #else/**/
704 // #endif// OR #endif/**/
705 //
706 // Note that we do allow comments after #ifdef/#define here, e.g.
707 // #ifdef/**/ AND #ifdef//
708 // #define/**/ AND #define//
709 //
710 // These cases will be reported as incorrect after calling
711 // prepLexMacroName(). We could have supported C-style comments
712 // after #ifdef/#define, but this would complicate the code
713 // for little benefit.
714 if (NextChar == '/') {
715 NextChar = peekNextChar(Word.size() + 1);
716
717 if (NextChar == '*' || NextChar == '/')
718 return Kind;
719
720 // Pretend that we do not recognize the directive.
721 }
722 }
723
724 return tgtok::Error;
725}
726
727bool TGLexer::prepEatPreprocessorDirective(tgtok::TokKind Kind) {
728 TokStart = CurPtr;
729
730 for (const auto [PKind, PWord] : PreprocessorDirs)
731 if (PKind == Kind) {
732 // Advance CurPtr to the end of the preprocessing word.
733 CurPtr += PWord.size();
734 return true;
735 }
736
737 PrintFatalError("unsupported preprocessing token in "
738 "prepEatPreprocessorDirective()");
739 return false;
740}
741
742tgtok::TokKind TGLexer::lexPreprocessor(tgtok::TokKind Kind,
743 bool ReturnNextLiveToken) {
744 // We must be looking at a preprocessing directive. Eat it!
745 if (!prepEatPreprocessorDirective(Kind))
746 PrintFatalError("lexPreprocessor() called for unknown "
747 "preprocessor directive");
748
749 if (Kind == tgtok::Ifdef || Kind == tgtok::Ifndef) {
750 StringRef MacroName = prepLexMacroName();
751 StringRef IfTokName = Kind == tgtok::Ifdef ? "#ifdef" : "#ifndef";
752 if (MacroName.empty())
753 return ReturnError(TokStart, "expected macro name after " + IfTokName);
754
755 bool MacroIsDefined = DefinedMacros.count(MacroName) != 0;
756
757 // Canonicalize ifndef's MacroIsDefined to its ifdef equivalent.
758 if (Kind == tgtok::Ifndef)
759 MacroIsDefined = !MacroIsDefined;
760
761 // Regardless of whether we are processing tokens or not,
762 // we put the #ifdef control on stack.
763 // Note that MacroIsDefined has been canonicalized against ifdef.
764 PrepIncludeStack.back()->push_back(
765 {tgtok::Ifdef, MacroIsDefined, SMLoc::getFromPointer(TokStart)});
766
767 if (!prepSkipDirectiveEnd())
768 return ReturnError(CurPtr, "only comments are supported after " +
769 IfTokName + " NAME");
770
771 // If we were not processing tokens before this #ifdef,
772 // then just return back to the lines skipping code.
773 if (!ReturnNextLiveToken)
774 return Kind;
775
776 // If we were processing tokens before this #ifdef,
777 // and the macro is defined, then just return the next token.
778 if (MacroIsDefined)
779 return LexToken();
780
781 // We were processing tokens before this #ifdef, and the macro
782 // is not defined, so we have to start skipping the lines.
783 // If the skipping is successful, it will return the token following
784 // either #else or #endif corresponding to this #ifdef.
785 if (prepSkipRegion(ReturnNextLiveToken))
786 return LexToken();
787
788 return tgtok::Error;
789 } else if (Kind == tgtok::Else) {
790 // Check if this #else is correct before calling prepSkipDirectiveEnd(),
791 // which will move CurPtr away from the beginning of #else.
792 if (PrepIncludeStack.back()->empty())
793 return ReturnError(TokStart, "#else without #ifdef or #ifndef");
794
795 PreprocessorControlDesc IfdefEntry = PrepIncludeStack.back()->back();
796
797 if (IfdefEntry.Kind != tgtok::Ifdef) {
798 PrintError(TokStart, "double #else");
799 return ReturnError(IfdefEntry.SrcPos, "previous #else is here");
800 }
801
802 // Replace the corresponding #ifdef's control with its negation
803 // on the control stack.
804 PrepIncludeStack.back()->pop_back();
805 PrepIncludeStack.back()->push_back(
806 {Kind, !IfdefEntry.IsDefined, SMLoc::getFromPointer(TokStart)});
807
808 if (!prepSkipDirectiveEnd())
809 return ReturnError(CurPtr, "only comments are supported after #else");
810
811 // If we were processing tokens before this #else,
812 // we have to start skipping lines until the matching #endif.
813 if (ReturnNextLiveToken) {
814 if (prepSkipRegion(ReturnNextLiveToken))
815 return LexToken();
816
817 return tgtok::Error;
818 }
819
820 // Return to the lines skipping code.
821 return Kind;
822 } else if (Kind == tgtok::Endif) {
823 // Check if this #endif is correct before calling prepSkipDirectiveEnd(),
824 // which will move CurPtr away from the beginning of #endif.
825 if (PrepIncludeStack.back()->empty())
826 return ReturnError(TokStart, "#endif without #ifdef");
827
828 auto &IfdefOrElseEntry = PrepIncludeStack.back()->back();
829
830 if (IfdefOrElseEntry.Kind != tgtok::Ifdef &&
831 IfdefOrElseEntry.Kind != tgtok::Else) {
832 PrintFatalError("invalid preprocessor control on the stack");
833 return tgtok::Error;
834 }
835
836 if (!prepSkipDirectiveEnd())
837 return ReturnError(CurPtr, "only comments are supported after #endif");
838
839 PrepIncludeStack.back()->pop_back();
840
841 // If we were processing tokens before this #endif, then
842 // we should continue it.
843 if (ReturnNextLiveToken) {
844 return LexToken();
845 }
846
847 // Return to the lines skipping code.
848 return Kind;
849 } else if (Kind == tgtok::Define) {
850 StringRef MacroName = prepLexMacroName();
851 if (MacroName.empty())
852 return ReturnError(TokStart, "expected macro name after #define");
853
854 if (!DefinedMacros.insert(MacroName).second)
856 "duplicate definition of macro: " + Twine(MacroName));
857
858 if (!prepSkipDirectiveEnd())
859 return ReturnError(CurPtr,
860 "only comments are supported after #define NAME");
861
862 if (!ReturnNextLiveToken) {
863 PrintFatalError("#define must be ignored during the lines skipping");
864 return tgtok::Error;
865 }
866
867 return LexToken();
868 }
869
870 PrintFatalError("preprocessing directive is not supported");
871 return tgtok::Error;
872}
873
874bool TGLexer::prepSkipRegion(bool MustNeverBeFalse) {
875 if (!MustNeverBeFalse)
876 PrintFatalError("invalid recursion.");
877
878 do {
879 // Skip all symbols to the line end.
880 while (*CurPtr != '\n')
881 ++CurPtr;
882
883 // Find the first non-whitespace symbol in the next line(s).
884 if (!prepSkipLineBegin())
885 return false;
886
887 // If the first non-blank/comment symbol on the line is '#',
888 // it may be a start of preprocessing directive.
889 //
890 // If it is not '#' just go to the next line.
891 if (*CurPtr == '#')
892 ++CurPtr;
893 else
894 continue;
895
896 tgtok::TokKind Kind = prepIsDirective();
897
898 // If we did not find a preprocessing directive or it is #define,
899 // then just skip to the next line. We do not have to do anything
900 // for #define in the line-skipping mode.
901 if (Kind == tgtok::Error || Kind == tgtok::Define)
902 continue;
903
904 tgtok::TokKind ProcessedKind = lexPreprocessor(Kind, false);
905
906 // If lexPreprocessor() encountered an error during lexing this
907 // preprocessor idiom, then return false to the calling lexPreprocessor().
908 // This will force tgtok::Error to be returned to the tokens processing.
909 if (ProcessedKind == tgtok::Error)
910 return false;
911
912 if (Kind != ProcessedKind)
913 PrintFatalError("prepIsDirective() and lexPreprocessor() "
914 "returned different token kinds");
915
916 // If this preprocessing directive enables tokens processing,
917 // then return to the lexPreprocessor() and get to the next token.
918 // We can move from line-skipping mode to processing tokens only
919 // due to #else or #endif.
920 if (prepIsProcessingEnabled()) {
921 if (Kind != tgtok::Else && Kind != tgtok::Endif) {
922 PrintFatalError("tokens processing was enabled by an unexpected "
923 "preprocessing directive");
924 return false;
925 }
926
927 return true;
928 }
929 } while (CurPtr != CurBuf.end());
930
931 // We have reached the end of the file, but never left the lines-skipping
932 // mode. This means there is no matching #endif.
933 prepReportPreprocessorStackError();
934 return false;
935}
936
937StringRef TGLexer::prepLexMacroName() {
938 // Skip whitespaces between the preprocessing directive and the macro name.
939 while (*CurPtr == ' ' || *CurPtr == '\t')
940 ++CurPtr;
941
942 TokStart = CurPtr;
943 CurPtr = lexMacroName(StringRef(CurPtr, CurBuf.end() - CurPtr));
944 return StringRef(TokStart, CurPtr - TokStart);
945}
946
947bool TGLexer::prepSkipLineBegin() {
948 while (CurPtr != CurBuf.end()) {
949 switch (*CurPtr) {
950 case ' ':
951 case '\t':
952 case '\n':
953 case '\r':
954 break;
955
956 case '/': {
957 int NextChar = peekNextChar(1);
958 if (NextChar == '*') {
959 // Skip C-style comment.
960 // Note that we do not care about skipping the C++-style comments.
961 // If the line contains "//", it may not contain any processable
962 // preprocessing directive. Just return CurPtr pointing to
963 // the first '/' in this case. We also do not care about
964 // incorrect symbols after the first '/' - we are in lines-skipping
965 // mode, so incorrect code is allowed to some extent.
966
967 // Set TokStart to the beginning of the comment to enable proper
968 // diagnostic printing in case of error in SkipCComment().
969 TokStart = CurPtr;
970
971 // CurPtr must point to '*' before call to SkipCComment().
972 ++CurPtr;
973 if (SkipCComment())
974 return false;
975 } else {
976 // CurPtr points to the non-whitespace '/'.
977 return true;
978 }
979
980 // We must not increment CurPtr after the comment was lexed.
981 continue;
982 }
983
984 default:
985 return true;
986 }
987
988 ++CurPtr;
989 }
990
991 // We have reached the end of the file. Return to the lines skipping
992 // code, and allow it to handle the EOF as needed.
993 return true;
994}
995
996bool TGLexer::prepSkipDirectiveEnd() {
997 while (CurPtr != CurBuf.end()) {
998 switch (*CurPtr) {
999 case ' ':
1000 case '\t':
1001 break;
1002
1003 case '\n':
1004 case '\r':
1005 return true;
1006
1007 case '/': {
1008 int NextChar = peekNextChar(1);
1009 if (NextChar == '/') {
1010 // Skip C++-style comment.
1011 // We may just return true now, but let's skip to the line/buffer end
1012 // to simplify the method specification.
1013 ++CurPtr;
1014 SkipBCPLComment();
1015 } else if (NextChar == '*') {
1016 // When we are skipping C-style comment at the end of a preprocessing
1017 // directive, we can skip several lines. If any meaningful TD token
1018 // follows the end of the C-style comment on the same line, it will
1019 // be considered as an invalid usage of TD token.
1020 // For example, we want to forbid usages like this one:
1021 // #define MACRO class Class {}
1022 // But with C-style comments we also disallow the following:
1023 // #define MACRO /* This macro is used
1024 // to ... */ class Class {}
1025 // One can argue that this should be allowed, but it does not seem
1026 // to be worth of the complication. Moreover, this matches
1027 // the C preprocessor behavior.
1028
1029 // Set TokStart to the beginning of the comment to enable proper
1030 // diagnostic printer in case of error in SkipCComment().
1031 TokStart = CurPtr;
1032 ++CurPtr;
1033 if (SkipCComment())
1034 return false;
1035 } else {
1036 TokStart = CurPtr;
1037 PrintError(CurPtr, "unexpected character");
1038 return false;
1039 }
1040
1041 // We must not increment CurPtr after the comment was lexed.
1042 continue;
1043 }
1044
1045 default:
1046 // Do not allow any non-whitespaces after the directive.
1047 TokStart = CurPtr;
1048 return false;
1049 }
1050
1051 ++CurPtr;
1052 }
1053
1054 return true;
1055}
1056
1057bool TGLexer::prepIsProcessingEnabled() {
1058 for (const PreprocessorControlDesc &I :
1059 llvm::reverse(*PrepIncludeStack.back()))
1060 if (!I.IsDefined)
1061 return false;
1062
1063 return true;
1064}
1065
1066void TGLexer::prepReportPreprocessorStackError() {
1067 if (PrepIncludeStack.back()->empty())
1068 PrintFatalError("prepReportPreprocessorStackError() called with "
1069 "empty control stack");
1070
1071 auto &PrepControl = PrepIncludeStack.back()->back();
1072 PrintError(CurBuf.end(), "reached EOF without matching #endif");
1073 PrintError(PrepControl.SrcPos, "the latest preprocessor control is here");
1074
1075 TokStart = CurPtr;
1076}
bool End
Definition: ELF_riscv.cpp:480
#define I(x, y, z)
Definition: MD5.cpp:58
static bool isDigit(const char C)
static bool isHexDigit(const char C)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some functions that are useful when dealing with strings.
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
constexpr PreprocessorDir PreprocessorDirs[]
Definition: TGLexer.cpp:52
static bool isValidIDChar(char C, bool First)
Returns true if C is a valid character in an identifier.
Definition: TGLexer.cpp:46
static const char * lexMacroName(StringRef Str)
Definition: TGLexer.cpp:60
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
StringRef getBuffer() const
Definition: MemoryBuffer.h:70
Represents a location in source code.
Definition: SMLoc.h:23
static SMLoc getFromPointer(const char *Ptr)
Definition: SMLoc.h:36
constexpr const char * getPointer() const
Definition: SMLoc.h:34
Represents a range in source code.
Definition: SMLoc.h:48
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition: SourceMgr.h:31
unsigned getMainFileID() const
Definition: SourceMgr.h:132
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition: SourceMgr.h:125
SMLoc getParentIncludeLoc(unsigned i) const
Definition: SourceMgr.h:137
unsigned FindBufferContainingLoc(SMLoc Loc) const
Return the ID of the buffer containing the specified location.
Definition: SourceMgr.cpp:73
unsigned AddIncludeFile(const std::string &Filename, SMLoc IncludeLoc, std::string &IncludedFile)
Search for a file with the specified name in the current directory or in one of the IncludeDirs.
Definition: SourceMgr.cpp:41
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:276
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
iterator begin() const
Definition: StringRef.h:116
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:144
size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition: StringRef.h:377
iterator end() const
Definition: StringRef.h:118
static constexpr size_t npos
Definition: StringRef.h:53
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition: StringSet.h:38
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:69
R Default(T Value)
Definition: StringSwitch.h:182
StringSwitch & Cases(StringLiteral S0, StringLiteral S1, T Value)
Definition: StringSwitch.h:90
SMRange getLocRange() const
Definition: TGLexer.cpp:103
tgtok::TokKind Lex()
Definition: TGLexer.h:215
SMLoc getLoc() const
Definition: TGLexer.cpp:99
TGLexer(SourceMgr &SrcMgr, ArrayRef< std::string > Macros)
Definition: TGLexer.cpp:77
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
support::ulittle32_t Word
Definition: IRSymtab.h:52
@ r_square
Definition: TGLexer.h:41
@ XListSplat
Definition: TGLexer.h:124
@ XSetDagArg
Definition: TGLexer.h:158
@ XGetDagName
Definition: TGLexer.h:157
@ l_square
Definition: TGLexer.h:40
@ CodeFragment
Definition: TGLexer.h:168
@ XInterleave
Definition: TGLexer.h:126
@ MultiClass
Definition: TGLexer.h:104
@ BinaryIntVal
Definition: TGLexer.h:66
@ XSetDagName
Definition: TGLexer.h:159
@ XGetDagArg
Definition: TGLexer.h:156
@ XListConcat
Definition: TGLexer.h:122
@ XInitialized
Definition: TGLexer.h:138
@ XStrConcat
Definition: TGLexer.h:125
@ XListFlatten
Definition: TGLexer.h:123
@ FalseVal
Definition: TGLexer.h:59
@ dotdotdot
Definition: TGLexer.h:55
@ question
Definition: TGLexer.h:53
@ XListRemove
Definition: TGLexer.h:152
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void PrintFatalError(const Twine &Msg)
Definition: Error.cpp:132
void PrintError(const Twine &Msg)
Definition: Error.cpp:104
SourceMgr SrcMgr
Definition: Error.cpp:24
void PrintWarning(const Twine &Msg)
Definition: Error.cpp:92
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:420
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.