xref: /llvm-project-15.0.7/clang/lib/Lex/Lexer.cpp (revision fbff2faf)
1 //===- Lexer.cpp - C Language Family Lexer --------------------------------===//
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 Lexer and Token interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Lex/Lexer.h"
15 #include "UnicodeCharSets.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/Basic/IdentifierTable.h"
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TokenKinds.h"
22 #include "clang/Lex/LexDiagnostic.h"
23 #include "clang/Lex/LiteralSupport.h"
24 #include "clang/Lex/MultipleIncludeOpt.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Lex/PreprocessorOptions.h"
27 #include "clang/Lex/Token.h"
28 #include "clang/Basic/Diagnostic.h"
29 #include "clang/Basic/LLVM.h"
30 #include "clang/Basic/TokenKinds.h"
31 #include "llvm/ADT/None.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/StringSwitch.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/ConvertUTF.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/NativeFormatting.h"
41 #include "llvm/Support/UnicodeCharRanges.h"
42 #include <algorithm>
43 #include <cassert>
44 #include <cstddef>
45 #include <cstdint>
46 #include <cstring>
47 #include <string>
48 #include <tuple>
49 #include <utility>
50 
51 using namespace clang;
52 
53 //===----------------------------------------------------------------------===//
54 // Token Class Implementation
55 //===----------------------------------------------------------------------===//
56 
57 /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
58 bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
59   if (isAnnotation())
60     return false;
61   if (IdentifierInfo *II = getIdentifierInfo())
62     return II->getObjCKeywordID() == objcKey;
63   return false;
64 }
65 
66 /// getObjCKeywordID - Return the ObjC keyword kind.
67 tok::ObjCKeywordKind Token::getObjCKeywordID() const {
68   if (isAnnotation())
69     return tok::objc_not_keyword;
70   IdentifierInfo *specId = getIdentifierInfo();
71   return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
72 }
73 
74 //===----------------------------------------------------------------------===//
75 // Lexer Class Implementation
76 //===----------------------------------------------------------------------===//
77 
78 void Lexer::anchor() {}
79 
80 void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
81                       const char *BufEnd) {
82   BufferStart = BufStart;
83   BufferPtr = BufPtr;
84   BufferEnd = BufEnd;
85 
86   assert(BufEnd[0] == 0 &&
87          "We assume that the input buffer has a null character at the end"
88          " to simplify lexing!");
89 
90   // Check whether we have a BOM in the beginning of the buffer. If yes - act
91   // accordingly. Right now we support only UTF-8 with and without BOM, so, just
92   // skip the UTF-8 BOM if it's present.
93   if (BufferStart == BufferPtr) {
94     // Determine the size of the BOM.
95     StringRef Buf(BufferStart, BufferEnd - BufferStart);
96     size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
97       .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
98       .Default(0);
99 
100     // Skip the BOM.
101     BufferPtr += BOMLength;
102   }
103 
104   Is_PragmaLexer = false;
105   CurrentConflictMarkerState = CMK_None;
106 
107   // Start of the file is a start of line.
108   IsAtStartOfLine = true;
109   IsAtPhysicalStartOfLine = true;
110 
111   HasLeadingSpace = false;
112   HasLeadingEmptyMacro = false;
113 
114   // We are not after parsing a #.
115   ParsingPreprocessorDirective = false;
116 
117   // We are not after parsing #include.
118   ParsingFilename = false;
119 
120   // We are not in raw mode.  Raw mode disables diagnostics and interpretation
121   // of tokens (e.g. identifiers, thus disabling macro expansion).  It is used
122   // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
123   // or otherwise skipping over tokens.
124   LexingRawMode = false;
125 
126   // Default to not keeping comments.
127   ExtendedTokenMode = 0;
128 }
129 
130 /// Lexer constructor - Create a new lexer object for the specified buffer
131 /// with the specified preprocessor managing the lexing process.  This lexer
132 /// assumes that the associated file buffer and Preprocessor objects will
133 /// outlive it, so it doesn't take ownership of either of them.
134 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
135     : PreprocessorLexer(&PP, FID),
136       FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
137       LangOpts(PP.getLangOpts()) {
138   InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
139             InputFile->getBufferEnd());
140 
141   resetExtendedTokenMode();
142 }
143 
144 /// Lexer constructor - Create a new raw lexer object.  This object is only
145 /// suitable for calls to 'LexFromRawLexer'.  This lexer assumes that the text
146 /// range will outlive it, so it doesn't take ownership of it.
147 Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
148              const char *BufStart, const char *BufPtr, const char *BufEnd)
149     : FileLoc(fileloc), LangOpts(langOpts) {
150   InitLexer(BufStart, BufPtr, BufEnd);
151 
152   // We *are* in raw mode.
153   LexingRawMode = true;
154 }
155 
156 /// Lexer constructor - Create a new raw lexer object.  This object is only
157 /// suitable for calls to 'LexFromRawLexer'.  This lexer assumes that the text
158 /// range will outlive it, so it doesn't take ownership of it.
159 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
160              const SourceManager &SM, const LangOptions &langOpts)
161     : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
162             FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
163 
164 void Lexer::resetExtendedTokenMode() {
165   assert(PP && "Cannot reset token mode without a preprocessor");
166   if (LangOpts.TraditionalCPP)
167     SetKeepWhitespaceMode(true);
168   else
169     SetCommentRetentionState(PP->getCommentRetentionState());
170 }
171 
172 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
173 /// _Pragma expansion.  This has a variety of magic semantics that this method
174 /// sets up.  It returns a new'd Lexer that must be delete'd when done.
175 ///
176 /// On entrance to this routine, TokStartLoc is a macro location which has a
177 /// spelling loc that indicates the bytes to be lexed for the token and an
178 /// expansion location that indicates where all lexed tokens should be
179 /// "expanded from".
180 ///
181 /// TODO: It would really be nice to make _Pragma just be a wrapper around a
182 /// normal lexer that remaps tokens as they fly by.  This would require making
183 /// Preprocessor::Lex virtual.  Given that, we could just dump in a magic lexer
184 /// interface that could handle this stuff.  This would pull GetMappedTokenLoc
185 /// out of the critical path of the lexer!
186 ///
187 Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
188                                  SourceLocation ExpansionLocStart,
189                                  SourceLocation ExpansionLocEnd,
190                                  unsigned TokLen, Preprocessor &PP) {
191   SourceManager &SM = PP.getSourceManager();
192 
193   // Create the lexer as if we were going to lex the file normally.
194   FileID SpellingFID = SM.getFileID(SpellingLoc);
195   const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
196   Lexer *L = new Lexer(SpellingFID, InputFile, PP);
197 
198   // Now that the lexer is created, change the start/end locations so that we
199   // just lex the subsection of the file that we want.  This is lexing from a
200   // scratch buffer.
201   const char *StrData = SM.getCharacterData(SpellingLoc);
202 
203   L->BufferPtr = StrData;
204   L->BufferEnd = StrData+TokLen;
205   assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
206 
207   // Set the SourceLocation with the remapping information.  This ensures that
208   // GetMappedTokenLoc will remap the tokens as they are lexed.
209   L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
210                                      ExpansionLocStart,
211                                      ExpansionLocEnd, TokLen);
212 
213   // Ensure that the lexer thinks it is inside a directive, so that end \n will
214   // return an EOD token.
215   L->ParsingPreprocessorDirective = true;
216 
217   // This lexer really is for _Pragma.
218   L->Is_PragmaLexer = true;
219   return L;
220 }
221 
222 template <typename T> static void StringifyImpl(T &Str, char Quote) {
223   typename T::size_type i = 0, e = Str.size();
224   while (i < e) {
225     if (Str[i] == '\\' || Str[i] == Quote) {
226       Str.insert(Str.begin() + i, '\\');
227       i += 2;
228       ++e;
229     } else if (Str[i] == '\n' || Str[i] == '\r') {
230       // Replace '\r\n' and '\n\r' to '\\' followed by 'n'.
231       if ((i < e - 1) && (Str[i + 1] == '\n' || Str[i + 1] == '\r') &&
232           Str[i] != Str[i + 1]) {
233         Str[i] = '\\';
234         Str[i + 1] = 'n';
235       } else {
236         // Replace '\n' and '\r' to '\\' followed by 'n'.
237         Str[i] = '\\';
238         Str.insert(Str.begin() + i + 1, 'n');
239         ++e;
240       }
241       i += 2;
242     } else
243       ++i;
244   }
245 }
246 
247 std::string Lexer::Stringify(StringRef Str, bool Charify) {
248   std::string Result = Str;
249   char Quote = Charify ? '\'' : '"';
250   StringifyImpl(Result, Quote);
251   return Result;
252 }
253 
254 void Lexer::Stringify(SmallVectorImpl<char> &Str) { StringifyImpl(Str, '"'); }
255 
256 //===----------------------------------------------------------------------===//
257 // Token Spelling
258 //===----------------------------------------------------------------------===//
259 
260 /// \brief Slow case of getSpelling. Extract the characters comprising the
261 /// spelling of this token from the provided input buffer.
262 static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
263                               const LangOptions &LangOpts, char *Spelling) {
264   assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
265 
266   size_t Length = 0;
267   const char *BufEnd = BufPtr + Tok.getLength();
268 
269   if (tok::isStringLiteral(Tok.getKind())) {
270     // Munch the encoding-prefix and opening double-quote.
271     while (BufPtr < BufEnd) {
272       unsigned Size;
273       Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
274       BufPtr += Size;
275 
276       if (Spelling[Length - 1] == '"')
277         break;
278     }
279 
280     // Raw string literals need special handling; trigraph expansion and line
281     // splicing do not occur within their d-char-sequence nor within their
282     // r-char-sequence.
283     if (Length >= 2 &&
284         Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
285       // Search backwards from the end of the token to find the matching closing
286       // quote.
287       const char *RawEnd = BufEnd;
288       do --RawEnd; while (*RawEnd != '"');
289       size_t RawLength = RawEnd - BufPtr + 1;
290 
291       // Everything between the quotes is included verbatim in the spelling.
292       memcpy(Spelling + Length, BufPtr, RawLength);
293       Length += RawLength;
294       BufPtr += RawLength;
295 
296       // The rest of the token is lexed normally.
297     }
298   }
299 
300   while (BufPtr < BufEnd) {
301     unsigned Size;
302     Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
303     BufPtr += Size;
304   }
305 
306   assert(Length < Tok.getLength() &&
307          "NeedsCleaning flag set on token that didn't need cleaning!");
308   return Length;
309 }
310 
311 /// getSpelling() - Return the 'spelling' of this token.  The spelling of a
312 /// token are the characters used to represent the token in the source file
313 /// after trigraph expansion and escaped-newline folding.  In particular, this
314 /// wants to get the true, uncanonicalized, spelling of things like digraphs
315 /// UCNs, etc.
316 StringRef Lexer::getSpelling(SourceLocation loc,
317                              SmallVectorImpl<char> &buffer,
318                              const SourceManager &SM,
319                              const LangOptions &options,
320                              bool *invalid) {
321   // Break down the source location.
322   std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
323 
324   // Try to the load the file buffer.
325   bool invalidTemp = false;
326   StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
327   if (invalidTemp) {
328     if (invalid) *invalid = true;
329     return {};
330   }
331 
332   const char *tokenBegin = file.data() + locInfo.second;
333 
334   // Lex from the start of the given location.
335   Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
336               file.begin(), tokenBegin, file.end());
337   Token token;
338   lexer.LexFromRawLexer(token);
339 
340   unsigned length = token.getLength();
341 
342   // Common case:  no need for cleaning.
343   if (!token.needsCleaning())
344     return StringRef(tokenBegin, length);
345 
346   // Hard case, we need to relex the characters into the string.
347   buffer.resize(length);
348   buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
349   return StringRef(buffer.data(), buffer.size());
350 }
351 
352 /// getSpelling() - Return the 'spelling' of this token.  The spelling of a
353 /// token are the characters used to represent the token in the source file
354 /// after trigraph expansion and escaped-newline folding.  In particular, this
355 /// wants to get the true, uncanonicalized, spelling of things like digraphs
356 /// UCNs, etc.
357 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
358                                const LangOptions &LangOpts, bool *Invalid) {
359   assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
360 
361   bool CharDataInvalid = false;
362   const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
363                                                     &CharDataInvalid);
364   if (Invalid)
365     *Invalid = CharDataInvalid;
366   if (CharDataInvalid)
367     return {};
368 
369   // If this token contains nothing interesting, return it directly.
370   if (!Tok.needsCleaning())
371     return std::string(TokStart, TokStart + Tok.getLength());
372 
373   std::string Result;
374   Result.resize(Tok.getLength());
375   Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
376   return Result;
377 }
378 
379 /// getSpelling - This method is used to get the spelling of a token into a
380 /// preallocated buffer, instead of as an std::string.  The caller is required
381 /// to allocate enough space for the token, which is guaranteed to be at least
382 /// Tok.getLength() bytes long.  The actual length of the token is returned.
383 ///
384 /// Note that this method may do two possible things: it may either fill in
385 /// the buffer specified with characters, or it may *change the input pointer*
386 /// to point to a constant buffer with the data already in it (avoiding a
387 /// copy).  The caller is not allowed to modify the returned buffer pointer
388 /// if an internal buffer is returned.
389 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
390                             const SourceManager &SourceMgr,
391                             const LangOptions &LangOpts, bool *Invalid) {
392   assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
393 
394   const char *TokStart = nullptr;
395   // NOTE: this has to be checked *before* testing for an IdentifierInfo.
396   if (Tok.is(tok::raw_identifier))
397     TokStart = Tok.getRawIdentifier().data();
398   else if (!Tok.hasUCN()) {
399     if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
400       // Just return the string from the identifier table, which is very quick.
401       Buffer = II->getNameStart();
402       return II->getLength();
403     }
404   }
405 
406   // NOTE: this can be checked even after testing for an IdentifierInfo.
407   if (Tok.isLiteral())
408     TokStart = Tok.getLiteralData();
409 
410   if (!TokStart) {
411     // Compute the start of the token in the input lexer buffer.
412     bool CharDataInvalid = false;
413     TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
414     if (Invalid)
415       *Invalid = CharDataInvalid;
416     if (CharDataInvalid) {
417       Buffer = "";
418       return 0;
419     }
420   }
421 
422   // If this token contains nothing interesting, return it directly.
423   if (!Tok.needsCleaning()) {
424     Buffer = TokStart;
425     return Tok.getLength();
426   }
427 
428   // Otherwise, hard case, relex the characters into the string.
429   return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
430 }
431 
432 /// MeasureTokenLength - Relex the token at the specified location and return
433 /// its length in bytes in the input file.  If the token needs cleaning (e.g.
434 /// includes a trigraph or an escaped newline) then this count includes bytes
435 /// that are part of that.
436 unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
437                                    const SourceManager &SM,
438                                    const LangOptions &LangOpts) {
439   Token TheTok;
440   if (getRawToken(Loc, TheTok, SM, LangOpts))
441     return 0;
442   return TheTok.getLength();
443 }
444 
445 /// \brief Relex the token at the specified location.
446 /// \returns true if there was a failure, false on success.
447 bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
448                         const SourceManager &SM,
449                         const LangOptions &LangOpts,
450                         bool IgnoreWhiteSpace) {
451   // TODO: this could be special cased for common tokens like identifiers, ')',
452   // etc to make this faster, if it mattered.  Just look at StrData[0] to handle
453   // all obviously single-char tokens.  This could use
454   // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
455   // something.
456 
457   // If this comes from a macro expansion, we really do want the macro name, not
458   // the token this macro expanded to.
459   Loc = SM.getExpansionLoc(Loc);
460   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
461   bool Invalid = false;
462   StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
463   if (Invalid)
464     return true;
465 
466   const char *StrData = Buffer.data()+LocInfo.second;
467 
468   if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
469     return true;
470 
471   // Create a lexer starting at the beginning of this token.
472   Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
473                  Buffer.begin(), StrData, Buffer.end());
474   TheLexer.SetCommentRetentionState(true);
475   TheLexer.LexFromRawLexer(Result);
476   return false;
477 }
478 
479 /// Returns the pointer that points to the beginning of line that contains
480 /// the given offset, or null if the offset if invalid.
481 static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
482   const char *BufStart = Buffer.data();
483   if (Offset >= Buffer.size())
484     return nullptr;
485 
486   const char *LexStart = BufStart + Offset;
487   for (; LexStart != BufStart; --LexStart) {
488     if (isVerticalWhitespace(LexStart[0]) &&
489         !Lexer::isNewLineEscaped(BufStart, LexStart)) {
490       // LexStart should point at first character of logical line.
491       ++LexStart;
492       break;
493     }
494   }
495   return LexStart;
496 }
497 
498 static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
499                                               const SourceManager &SM,
500                                               const LangOptions &LangOpts) {
501   assert(Loc.isFileID());
502   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
503   if (LocInfo.first.isInvalid())
504     return Loc;
505 
506   bool Invalid = false;
507   StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
508   if (Invalid)
509     return Loc;
510 
511   // Back up from the current location until we hit the beginning of a line
512   // (or the buffer). We'll relex from that point.
513   const char *StrData = Buffer.data() + LocInfo.second;
514   const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
515   if (!LexStart || LexStart == StrData)
516     return Loc;
517 
518   // Create a lexer starting at the beginning of this token.
519   SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
520   Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
521                  Buffer.end());
522   TheLexer.SetCommentRetentionState(true);
523 
524   // Lex tokens until we find the token that contains the source location.
525   Token TheTok;
526   do {
527     TheLexer.LexFromRawLexer(TheTok);
528 
529     if (TheLexer.getBufferLocation() > StrData) {
530       // Lexing this token has taken the lexer past the source location we're
531       // looking for. If the current token encompasses our source location,
532       // return the beginning of that token.
533       if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
534         return TheTok.getLocation();
535 
536       // We ended up skipping over the source location entirely, which means
537       // that it points into whitespace. We're done here.
538       break;
539     }
540   } while (TheTok.getKind() != tok::eof);
541 
542   // We've passed our source location; just return the original source location.
543   return Loc;
544 }
545 
546 SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
547                                           const SourceManager &SM,
548                                           const LangOptions &LangOpts) {
549   if (Loc.isFileID())
550     return getBeginningOfFileToken(Loc, SM, LangOpts);
551 
552   if (!SM.isMacroArgExpansion(Loc))
553     return Loc;
554 
555   SourceLocation FileLoc = SM.getSpellingLoc(Loc);
556   SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
557   std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
558   std::pair<FileID, unsigned> BeginFileLocInfo =
559       SM.getDecomposedLoc(BeginFileLoc);
560   assert(FileLocInfo.first == BeginFileLocInfo.first &&
561          FileLocInfo.second >= BeginFileLocInfo.second);
562   return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
563 }
564 
565 namespace {
566 
567 enum PreambleDirectiveKind {
568   PDK_Skipped,
569   PDK_Unknown
570 };
571 
572 } // namespace
573 
574 PreambleBounds Lexer::ComputePreamble(StringRef Buffer,
575                                       const LangOptions &LangOpts,
576                                       unsigned MaxLines) {
577   // Create a lexer starting at the beginning of the file. Note that we use a
578   // "fake" file source location at offset 1 so that the lexer will track our
579   // position within the file.
580   const unsigned StartOffset = 1;
581   SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
582   Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
583                  Buffer.end());
584   TheLexer.SetCommentRetentionState(true);
585 
586   bool InPreprocessorDirective = false;
587   Token TheTok;
588   SourceLocation ActiveCommentLoc;
589 
590   unsigned MaxLineOffset = 0;
591   if (MaxLines) {
592     const char *CurPtr = Buffer.begin();
593     unsigned CurLine = 0;
594     while (CurPtr != Buffer.end()) {
595       char ch = *CurPtr++;
596       if (ch == '\n') {
597         ++CurLine;
598         if (CurLine == MaxLines)
599           break;
600       }
601     }
602     if (CurPtr != Buffer.end())
603       MaxLineOffset = CurPtr - Buffer.begin();
604   }
605 
606   do {
607     TheLexer.LexFromRawLexer(TheTok);
608 
609     if (InPreprocessorDirective) {
610       // If we've hit the end of the file, we're done.
611       if (TheTok.getKind() == tok::eof) {
612         break;
613       }
614 
615       // If we haven't hit the end of the preprocessor directive, skip this
616       // token.
617       if (!TheTok.isAtStartOfLine())
618         continue;
619 
620       // We've passed the end of the preprocessor directive, and will look
621       // at this token again below.
622       InPreprocessorDirective = false;
623     }
624 
625     // Keep track of the # of lines in the preamble.
626     if (TheTok.isAtStartOfLine()) {
627       unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
628 
629       // If we were asked to limit the number of lines in the preamble,
630       // and we're about to exceed that limit, we're done.
631       if (MaxLineOffset && TokOffset >= MaxLineOffset)
632         break;
633     }
634 
635     // Comments are okay; skip over them.
636     if (TheTok.getKind() == tok::comment) {
637       if (ActiveCommentLoc.isInvalid())
638         ActiveCommentLoc = TheTok.getLocation();
639       continue;
640     }
641 
642     if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
643       // This is the start of a preprocessor directive.
644       Token HashTok = TheTok;
645       InPreprocessorDirective = true;
646       ActiveCommentLoc = SourceLocation();
647 
648       // Figure out which directive this is. Since we're lexing raw tokens,
649       // we don't have an identifier table available. Instead, just look at
650       // the raw identifier to recognize and categorize preprocessor directives.
651       TheLexer.LexFromRawLexer(TheTok);
652       if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
653         StringRef Keyword = TheTok.getRawIdentifier();
654         PreambleDirectiveKind PDK
655           = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
656               .Case("include", PDK_Skipped)
657               .Case("__include_macros", PDK_Skipped)
658               .Case("define", PDK_Skipped)
659               .Case("undef", PDK_Skipped)
660               .Case("line", PDK_Skipped)
661               .Case("error", PDK_Skipped)
662               .Case("pragma", PDK_Skipped)
663               .Case("import", PDK_Skipped)
664               .Case("include_next", PDK_Skipped)
665               .Case("warning", PDK_Skipped)
666               .Case("ident", PDK_Skipped)
667               .Case("sccs", PDK_Skipped)
668               .Case("assert", PDK_Skipped)
669               .Case("unassert", PDK_Skipped)
670               .Case("if", PDK_Skipped)
671               .Case("ifdef", PDK_Skipped)
672               .Case("ifndef", PDK_Skipped)
673               .Case("elif", PDK_Skipped)
674               .Case("else", PDK_Skipped)
675               .Case("endif", PDK_Skipped)
676               .Default(PDK_Unknown);
677 
678         switch (PDK) {
679         case PDK_Skipped:
680           continue;
681 
682         case PDK_Unknown:
683           // We don't know what this directive is; stop at the '#'.
684           break;
685         }
686       }
687 
688       // We only end up here if we didn't recognize the preprocessor
689       // directive or it was one that can't occur in the preamble at this
690       // point. Roll back the current token to the location of the '#'.
691       InPreprocessorDirective = false;
692       TheTok = HashTok;
693     }
694 
695     // We hit a token that we don't recognize as being in the
696     // "preprocessing only" part of the file, so we're no longer in
697     // the preamble.
698     break;
699   } while (true);
700 
701   SourceLocation End;
702   if (ActiveCommentLoc.isValid())
703     End = ActiveCommentLoc; // don't truncate a decl comment.
704   else
705     End = TheTok.getLocation();
706 
707   return PreambleBounds(End.getRawEncoding() - FileLoc.getRawEncoding(),
708                         TheTok.isAtStartOfLine());
709 }
710 
711 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
712 /// token, return a new location that specifies a character within the token.
713 SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
714                                               unsigned CharNo,
715                                               const SourceManager &SM,
716                                               const LangOptions &LangOpts) {
717   // Figure out how many physical characters away the specified expansion
718   // character is.  This needs to take into consideration newlines and
719   // trigraphs.
720   bool Invalid = false;
721   const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
722 
723   // If they request the first char of the token, we're trivially done.
724   if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
725     return TokStart;
726 
727   unsigned PhysOffset = 0;
728 
729   // The usual case is that tokens don't contain anything interesting.  Skip
730   // over the uninteresting characters.  If a token only consists of simple
731   // chars, this method is extremely fast.
732   while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
733     if (CharNo == 0)
734       return TokStart.getLocWithOffset(PhysOffset);
735     ++TokPtr;
736     --CharNo;
737     ++PhysOffset;
738   }
739 
740   // If we have a character that may be a trigraph or escaped newline, use a
741   // lexer to parse it correctly.
742   for (; CharNo; --CharNo) {
743     unsigned Size;
744     Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
745     TokPtr += Size;
746     PhysOffset += Size;
747   }
748 
749   // Final detail: if we end up on an escaped newline, we want to return the
750   // location of the actual byte of the token.  For example foo\<newline>bar
751   // advanced by 3 should return the location of b, not of \\.  One compounding
752   // detail of this is that the escape may be made by a trigraph.
753   if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
754     PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
755 
756   return TokStart.getLocWithOffset(PhysOffset);
757 }
758 
759 /// \brief Computes the source location just past the end of the
760 /// token at this source location.
761 ///
762 /// This routine can be used to produce a source location that
763 /// points just past the end of the token referenced by \p Loc, and
764 /// is generally used when a diagnostic needs to point just after a
765 /// token where it expected something different that it received. If
766 /// the returned source location would not be meaningful (e.g., if
767 /// it points into a macro), this routine returns an invalid
768 /// source location.
769 ///
770 /// \param Offset an offset from the end of the token, where the source
771 /// location should refer to. The default offset (0) produces a source
772 /// location pointing just past the end of the token; an offset of 1 produces
773 /// a source location pointing to the last character in the token, etc.
774 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
775                                           const SourceManager &SM,
776                                           const LangOptions &LangOpts) {
777   if (Loc.isInvalid())
778     return {};
779 
780   if (Loc.isMacroID()) {
781     if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
782       return {}; // Points inside the macro expansion.
783   }
784 
785   unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
786   if (Len > Offset)
787     Len = Len - Offset;
788   else
789     return Loc;
790 
791   return Loc.getLocWithOffset(Len);
792 }
793 
794 /// \brief Returns true if the given MacroID location points at the first
795 /// token of the macro expansion.
796 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
797                                       const SourceManager &SM,
798                                       const LangOptions &LangOpts,
799                                       SourceLocation *MacroBegin) {
800   assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
801 
802   SourceLocation expansionLoc;
803   if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
804     return false;
805 
806   if (expansionLoc.isFileID()) {
807     // No other macro expansions, this is the first.
808     if (MacroBegin)
809       *MacroBegin = expansionLoc;
810     return true;
811   }
812 
813   return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
814 }
815 
816 /// \brief Returns true if the given MacroID location points at the last
817 /// token of the macro expansion.
818 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
819                                     const SourceManager &SM,
820                                     const LangOptions &LangOpts,
821                                     SourceLocation *MacroEnd) {
822   assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
823 
824   SourceLocation spellLoc = SM.getSpellingLoc(loc);
825   unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
826   if (tokLen == 0)
827     return false;
828 
829   SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
830   SourceLocation expansionLoc;
831   if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
832     return false;
833 
834   if (expansionLoc.isFileID()) {
835     // No other macro expansions.
836     if (MacroEnd)
837       *MacroEnd = expansionLoc;
838     return true;
839   }
840 
841   return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
842 }
843 
844 static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
845                                              const SourceManager &SM,
846                                              const LangOptions &LangOpts) {
847   SourceLocation Begin = Range.getBegin();
848   SourceLocation End = Range.getEnd();
849   assert(Begin.isFileID() && End.isFileID());
850   if (Range.isTokenRange()) {
851     End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
852     if (End.isInvalid())
853       return {};
854   }
855 
856   // Break down the source locations.
857   FileID FID;
858   unsigned BeginOffs;
859   std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
860   if (FID.isInvalid())
861     return {};
862 
863   unsigned EndOffs;
864   if (!SM.isInFileID(End, FID, &EndOffs) ||
865       BeginOffs > EndOffs)
866     return {};
867 
868   return CharSourceRange::getCharRange(Begin, End);
869 }
870 
871 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
872                                          const SourceManager &SM,
873                                          const LangOptions &LangOpts) {
874   SourceLocation Begin = Range.getBegin();
875   SourceLocation End = Range.getEnd();
876   if (Begin.isInvalid() || End.isInvalid())
877     return {};
878 
879   if (Begin.isFileID() && End.isFileID())
880     return makeRangeFromFileLocs(Range, SM, LangOpts);
881 
882   if (Begin.isMacroID() && End.isFileID()) {
883     if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
884       return {};
885     Range.setBegin(Begin);
886     return makeRangeFromFileLocs(Range, SM, LangOpts);
887   }
888 
889   if (Begin.isFileID() && End.isMacroID()) {
890     if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
891                                                           &End)) ||
892         (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
893                                                            &End)))
894       return {};
895     Range.setEnd(End);
896     return makeRangeFromFileLocs(Range, SM, LangOpts);
897   }
898 
899   assert(Begin.isMacroID() && End.isMacroID());
900   SourceLocation MacroBegin, MacroEnd;
901   if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
902       ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
903                                                         &MacroEnd)) ||
904        (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
905                                                          &MacroEnd)))) {
906     Range.setBegin(MacroBegin);
907     Range.setEnd(MacroEnd);
908     return makeRangeFromFileLocs(Range, SM, LangOpts);
909   }
910 
911   bool Invalid = false;
912   const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
913                                                         &Invalid);
914   if (Invalid)
915     return {};
916 
917   if (BeginEntry.getExpansion().isMacroArgExpansion()) {
918     const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
919                                                         &Invalid);
920     if (Invalid)
921       return {};
922 
923     if (EndEntry.getExpansion().isMacroArgExpansion() &&
924         BeginEntry.getExpansion().getExpansionLocStart() ==
925             EndEntry.getExpansion().getExpansionLocStart()) {
926       Range.setBegin(SM.getImmediateSpellingLoc(Begin));
927       Range.setEnd(SM.getImmediateSpellingLoc(End));
928       return makeFileCharRange(Range, SM, LangOpts);
929     }
930   }
931 
932   return {};
933 }
934 
935 StringRef Lexer::getSourceText(CharSourceRange Range,
936                                const SourceManager &SM,
937                                const LangOptions &LangOpts,
938                                bool *Invalid) {
939   Range = makeFileCharRange(Range, SM, LangOpts);
940   if (Range.isInvalid()) {
941     if (Invalid) *Invalid = true;
942     return {};
943   }
944 
945   // Break down the source location.
946   std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
947   if (beginInfo.first.isInvalid()) {
948     if (Invalid) *Invalid = true;
949     return {};
950   }
951 
952   unsigned EndOffs;
953   if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
954       beginInfo.second > EndOffs) {
955     if (Invalid) *Invalid = true;
956     return {};
957   }
958 
959   // Try to the load the file buffer.
960   bool invalidTemp = false;
961   StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
962   if (invalidTemp) {
963     if (Invalid) *Invalid = true;
964     return {};
965   }
966 
967   if (Invalid) *Invalid = false;
968   return file.substr(beginInfo.second, EndOffs - beginInfo.second);
969 }
970 
971 StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
972                                        const SourceManager &SM,
973                                        const LangOptions &LangOpts) {
974   assert(Loc.isMacroID() && "Only reasonable to call this on macros");
975 
976   // Find the location of the immediate macro expansion.
977   while (true) {
978     FileID FID = SM.getFileID(Loc);
979     const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
980     const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
981     Loc = Expansion.getExpansionLocStart();
982     if (!Expansion.isMacroArgExpansion())
983       break;
984 
985     // For macro arguments we need to check that the argument did not come
986     // from an inner macro, e.g: "MAC1( MAC2(foo) )"
987 
988     // Loc points to the argument id of the macro definition, move to the
989     // macro expansion.
990     Loc = SM.getImmediateExpansionRange(Loc).first;
991     SourceLocation SpellLoc = Expansion.getSpellingLoc();
992     if (SpellLoc.isFileID())
993       break; // No inner macro.
994 
995     // If spelling location resides in the same FileID as macro expansion
996     // location, it means there is no inner macro.
997     FileID MacroFID = SM.getFileID(Loc);
998     if (SM.isInFileID(SpellLoc, MacroFID))
999       break;
1000 
1001     // Argument came from inner macro.
1002     Loc = SpellLoc;
1003   }
1004 
1005   // Find the spelling location of the start of the non-argument expansion
1006   // range. This is where the macro name was spelled in order to begin
1007   // expanding this macro.
1008   Loc = SM.getSpellingLoc(Loc);
1009 
1010   // Dig out the buffer where the macro name was spelled and the extents of the
1011   // name so that we can render it into the expansion note.
1012   std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1013   unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1014   StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1015   return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1016 }
1017 
1018 StringRef Lexer::getImmediateMacroNameForDiagnostics(
1019     SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1020   assert(Loc.isMacroID() && "Only reasonable to call this on macros");
1021   // Walk past macro argument expanions.
1022   while (SM.isMacroArgExpansion(Loc))
1023     Loc = SM.getImmediateExpansionRange(Loc).first;
1024 
1025   // If the macro's spelling has no FileID, then it's actually a token paste
1026   // or stringization (or similar) and not a macro at all.
1027   if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1028     return {};
1029 
1030   // Find the spelling location of the start of the non-argument expansion
1031   // range. This is where the macro name was spelled in order to begin
1032   // expanding this macro.
1033   Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1034 
1035   // Dig out the buffer where the macro name was spelled and the extents of the
1036   // name so that we can render it into the expansion note.
1037   std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1038   unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1039   StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1040   return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1041 }
1042 
1043 bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1044   return isIdentifierBody(c, LangOpts.DollarIdents);
1045 }
1046 
1047 bool Lexer::isNewLineEscaped(const char *BufferStart, const char *Str) {
1048   assert(isVerticalWhitespace(Str[0]));
1049   if (Str - 1 < BufferStart)
1050     return false;
1051 
1052   if ((Str[0] == '\n' && Str[-1] == '\r') ||
1053       (Str[0] == '\r' && Str[-1] == '\n')) {
1054     if (Str - 2 < BufferStart)
1055       return false;
1056     --Str;
1057   }
1058   --Str;
1059 
1060   // Rewind to first non-space character:
1061   while (Str > BufferStart && isHorizontalWhitespace(*Str))
1062     --Str;
1063 
1064   return *Str == '\\';
1065 }
1066 
1067 StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1068                                        const SourceManager &SM) {
1069   if (Loc.isInvalid() || Loc.isMacroID())
1070     return {};
1071   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1072   if (LocInfo.first.isInvalid())
1073     return {};
1074   bool Invalid = false;
1075   StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1076   if (Invalid)
1077     return {};
1078   const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1079   if (!Line)
1080     return {};
1081   StringRef Rest = Buffer.substr(Line - Buffer.data());
1082   size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1083   return NumWhitespaceChars == StringRef::npos
1084              ? ""
1085              : Rest.take_front(NumWhitespaceChars);
1086 }
1087 
1088 //===----------------------------------------------------------------------===//
1089 // Diagnostics forwarding code.
1090 //===----------------------------------------------------------------------===//
1091 
1092 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1093 /// lexer buffer was all expanded at a single point, perform the mapping.
1094 /// This is currently only used for _Pragma implementation, so it is the slow
1095 /// path of the hot getSourceLocation method.  Do not allow it to be inlined.
1096 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1097     Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1098 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1099                                         SourceLocation FileLoc,
1100                                         unsigned CharNo, unsigned TokLen) {
1101   assert(FileLoc.isMacroID() && "Must be a macro expansion");
1102 
1103   // Otherwise, we're lexing "mapped tokens".  This is used for things like
1104   // _Pragma handling.  Combine the expansion location of FileLoc with the
1105   // spelling location.
1106   SourceManager &SM = PP.getSourceManager();
1107 
1108   // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1109   // characters come from spelling(FileLoc)+Offset.
1110   SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1111   SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1112 
1113   // Figure out the expansion loc range, which is the range covered by the
1114   // original _Pragma(...) sequence.
1115   std::pair<SourceLocation,SourceLocation> II =
1116     SM.getImmediateExpansionRange(FileLoc);
1117 
1118   return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
1119 }
1120 
1121 /// getSourceLocation - Return a source location identifier for the specified
1122 /// offset in the current file.
1123 SourceLocation Lexer::getSourceLocation(const char *Loc,
1124                                         unsigned TokLen) const {
1125   assert(Loc >= BufferStart && Loc <= BufferEnd &&
1126          "Location out of range for this buffer!");
1127 
1128   // In the normal case, we're just lexing from a simple file buffer, return
1129   // the file id from FileLoc with the offset specified.
1130   unsigned CharNo = Loc-BufferStart;
1131   if (FileLoc.isFileID())
1132     return FileLoc.getLocWithOffset(CharNo);
1133 
1134   // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1135   // tokens are lexed from where the _Pragma was defined.
1136   assert(PP && "This doesn't work on raw lexers");
1137   return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1138 }
1139 
1140 /// Diag - Forwarding function for diagnostics.  This translate a source
1141 /// position in the current buffer into a SourceLocation object for rendering.
1142 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1143   return PP->Diag(getSourceLocation(Loc), DiagID);
1144 }
1145 
1146 //===----------------------------------------------------------------------===//
1147 // Trigraph and Escaped Newline Handling Code.
1148 //===----------------------------------------------------------------------===//
1149 
1150 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1151 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1152 static char GetTrigraphCharForLetter(char Letter) {
1153   switch (Letter) {
1154   default:   return 0;
1155   case '=':  return '#';
1156   case ')':  return ']';
1157   case '(':  return '[';
1158   case '!':  return '|';
1159   case '\'': return '^';
1160   case '>':  return '}';
1161   case '/':  return '\\';
1162   case '<':  return '{';
1163   case '-':  return '~';
1164   }
1165 }
1166 
1167 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1168 /// prefixed with ??, emit a trigraph warning.  If trigraphs are enabled,
1169 /// return the result character.  Finally, emit a warning about trigraph use
1170 /// whether trigraphs are enabled or not.
1171 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1172   char Res = GetTrigraphCharForLetter(*CP);
1173   if (!Res || !L) return Res;
1174 
1175   if (!L->getLangOpts().Trigraphs) {
1176     if (!L->isLexingRawMode())
1177       L->Diag(CP-2, diag::trigraph_ignored);
1178     return 0;
1179   }
1180 
1181   if (!L->isLexingRawMode())
1182     L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1183   return Res;
1184 }
1185 
1186 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1187 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1188 /// trigraph equivalent on entry to this function.
1189 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1190   unsigned Size = 0;
1191   while (isWhitespace(Ptr[Size])) {
1192     ++Size;
1193 
1194     if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1195       continue;
1196 
1197     // If this is a \r\n or \n\r, skip the other half.
1198     if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1199         Ptr[Size-1] != Ptr[Size])
1200       ++Size;
1201 
1202     return Size;
1203   }
1204 
1205   // Not an escaped newline, must be a \t or something else.
1206   return 0;
1207 }
1208 
1209 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1210 /// them), skip over them and return the first non-escaped-newline found,
1211 /// otherwise return P.
1212 const char *Lexer::SkipEscapedNewLines(const char *P) {
1213   while (true) {
1214     const char *AfterEscape;
1215     if (*P == '\\') {
1216       AfterEscape = P+1;
1217     } else if (*P == '?') {
1218       // If not a trigraph for escape, bail out.
1219       if (P[1] != '?' || P[2] != '/')
1220         return P;
1221       // FIXME: Take LangOpts into account; the language might not
1222       // support trigraphs.
1223       AfterEscape = P+3;
1224     } else {
1225       return P;
1226     }
1227 
1228     unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1229     if (NewLineSize == 0) return P;
1230     P = AfterEscape+NewLineSize;
1231   }
1232 }
1233 
1234 Optional<Token> Lexer::findNextToken(SourceLocation Loc,
1235                                      const SourceManager &SM,
1236                                      const LangOptions &LangOpts) {
1237   if (Loc.isMacroID()) {
1238     if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1239       return None;
1240   }
1241   Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1242 
1243   // Break down the source location.
1244   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1245 
1246   // Try to load the file buffer.
1247   bool InvalidTemp = false;
1248   StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1249   if (InvalidTemp)
1250     return None;
1251 
1252   const char *TokenBegin = File.data() + LocInfo.second;
1253 
1254   // Lex from the start of the given location.
1255   Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1256                                       TokenBegin, File.end());
1257   // Find the token.
1258   Token Tok;
1259   lexer.LexFromRawLexer(Tok);
1260   return Tok;
1261 }
1262 
1263 /// \brief Checks that the given token is the first token that occurs after the
1264 /// given location (this excludes comments and whitespace). Returns the location
1265 /// immediately after the specified token. If the token is not found or the
1266 /// location is inside a macro, the returned source location will be invalid.
1267 SourceLocation Lexer::findLocationAfterToken(
1268     SourceLocation Loc, tok::TokenKind TKind, const SourceManager &SM,
1269     const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine) {
1270   Optional<Token> Tok = findNextToken(Loc, SM, LangOpts);
1271   if (!Tok || Tok->isNot(TKind))
1272     return {};
1273   SourceLocation TokenLoc = Tok->getLocation();
1274 
1275   // Calculate how much whitespace needs to be skipped if any.
1276   unsigned NumWhitespaceChars = 0;
1277   if (SkipTrailingWhitespaceAndNewLine) {
1278     const char *TokenEnd = SM.getCharacterData(TokenLoc) + Tok->getLength();
1279     unsigned char C = *TokenEnd;
1280     while (isHorizontalWhitespace(C)) {
1281       C = *(++TokenEnd);
1282       NumWhitespaceChars++;
1283     }
1284 
1285     // Skip \r, \n, \r\n, or \n\r
1286     if (C == '\n' || C == '\r') {
1287       char PrevC = C;
1288       C = *(++TokenEnd);
1289       NumWhitespaceChars++;
1290       if ((C == '\n' || C == '\r') && C != PrevC)
1291         NumWhitespaceChars++;
1292     }
1293   }
1294 
1295   return TokenLoc.getLocWithOffset(Tok->getLength() + NumWhitespaceChars);
1296 }
1297 
1298 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1299 /// get its size, and return it.  This is tricky in several cases:
1300 ///   1. If currently at the start of a trigraph, we warn about the trigraph,
1301 ///      then either return the trigraph (skipping 3 chars) or the '?',
1302 ///      depending on whether trigraphs are enabled or not.
1303 ///   2. If this is an escaped newline (potentially with whitespace between
1304 ///      the backslash and newline), implicitly skip the newline and return
1305 ///      the char after it.
1306 ///
1307 /// This handles the slow/uncommon case of the getCharAndSize method.  Here we
1308 /// know that we can accumulate into Size, and that we have already incremented
1309 /// Ptr by Size bytes.
1310 ///
1311 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1312 /// be updated to match.
1313 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1314                                Token *Tok) {
1315   // If we have a slash, look for an escaped newline.
1316   if (Ptr[0] == '\\') {
1317     ++Size;
1318     ++Ptr;
1319 Slash:
1320     // Common case, backslash-char where the char is not whitespace.
1321     if (!isWhitespace(Ptr[0])) return '\\';
1322 
1323     // See if we have optional whitespace characters between the slash and
1324     // newline.
1325     if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1326       // Remember that this token needs to be cleaned.
1327       if (Tok) Tok->setFlag(Token::NeedsCleaning);
1328 
1329       // Warn if there was whitespace between the backslash and newline.
1330       if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1331         Diag(Ptr, diag::backslash_newline_space);
1332 
1333       // Found backslash<whitespace><newline>.  Parse the char after it.
1334       Size += EscapedNewLineSize;
1335       Ptr  += EscapedNewLineSize;
1336 
1337       // Use slow version to accumulate a correct size field.
1338       return getCharAndSizeSlow(Ptr, Size, Tok);
1339     }
1340 
1341     // Otherwise, this is not an escaped newline, just return the slash.
1342     return '\\';
1343   }
1344 
1345   // If this is a trigraph, process it.
1346   if (Ptr[0] == '?' && Ptr[1] == '?') {
1347     // If this is actually a legal trigraph (not something like "??x"), emit
1348     // a trigraph warning.  If so, and if trigraphs are enabled, return it.
1349     if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
1350       // Remember that this token needs to be cleaned.
1351       if (Tok) Tok->setFlag(Token::NeedsCleaning);
1352 
1353       Ptr += 3;
1354       Size += 3;
1355       if (C == '\\') goto Slash;
1356       return C;
1357     }
1358   }
1359 
1360   // If this is neither, return a single character.
1361   ++Size;
1362   return *Ptr;
1363 }
1364 
1365 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1366 /// getCharAndSizeNoWarn method.  Here we know that we can accumulate into Size,
1367 /// and that we have already incremented Ptr by Size bytes.
1368 ///
1369 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1370 /// be updated to match.
1371 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1372                                      const LangOptions &LangOpts) {
1373   // If we have a slash, look for an escaped newline.
1374   if (Ptr[0] == '\\') {
1375     ++Size;
1376     ++Ptr;
1377 Slash:
1378     // Common case, backslash-char where the char is not whitespace.
1379     if (!isWhitespace(Ptr[0])) return '\\';
1380 
1381     // See if we have optional whitespace characters followed by a newline.
1382     if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1383       // Found backslash<whitespace><newline>.  Parse the char after it.
1384       Size += EscapedNewLineSize;
1385       Ptr  += EscapedNewLineSize;
1386 
1387       // Use slow version to accumulate a correct size field.
1388       return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1389     }
1390 
1391     // Otherwise, this is not an escaped newline, just return the slash.
1392     return '\\';
1393   }
1394 
1395   // If this is a trigraph, process it.
1396   if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1397     // If this is actually a legal trigraph (not something like "??x"), return
1398     // it.
1399     if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1400       Ptr += 3;
1401       Size += 3;
1402       if (C == '\\') goto Slash;
1403       return C;
1404     }
1405   }
1406 
1407   // If this is neither, return a single character.
1408   ++Size;
1409   return *Ptr;
1410 }
1411 
1412 //===----------------------------------------------------------------------===//
1413 // Helper methods for lexing.
1414 //===----------------------------------------------------------------------===//
1415 
1416 /// \brief Routine that indiscriminately sets the offset into the source file.
1417 void Lexer::SetByteOffset(unsigned Offset, bool StartOfLine) {
1418   BufferPtr = BufferStart + Offset;
1419   if (BufferPtr > BufferEnd)
1420     BufferPtr = BufferEnd;
1421   // FIXME: What exactly does the StartOfLine bit mean?  There are two
1422   // possible meanings for the "start" of the line: the first token on the
1423   // unexpanded line, or the first token on the expanded line.
1424   IsAtStartOfLine = StartOfLine;
1425   IsAtPhysicalStartOfLine = StartOfLine;
1426 }
1427 
1428 static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1429   if (LangOpts.AsmPreprocessor) {
1430     return false;
1431   } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1432     static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1433         C11AllowedIDCharRanges);
1434     return C11AllowedIDChars.contains(C);
1435   } else if (LangOpts.CPlusPlus) {
1436     static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1437         CXX03AllowedIDCharRanges);
1438     return CXX03AllowedIDChars.contains(C);
1439   } else {
1440     static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1441         C99AllowedIDCharRanges);
1442     return C99AllowedIDChars.contains(C);
1443   }
1444 }
1445 
1446 static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1447   assert(isAllowedIDChar(C, LangOpts));
1448   if (LangOpts.AsmPreprocessor) {
1449     return false;
1450   } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1451     static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1452         C11DisallowedInitialIDCharRanges);
1453     return !C11DisallowedInitialIDChars.contains(C);
1454   } else if (LangOpts.CPlusPlus) {
1455     return true;
1456   } else {
1457     static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1458         C99DisallowedInitialIDCharRanges);
1459     return !C99DisallowedInitialIDChars.contains(C);
1460   }
1461 }
1462 
1463 static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1464                                             const char *End) {
1465   return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1466                                        L.getSourceLocation(End));
1467 }
1468 
1469 static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1470                                       CharSourceRange Range, bool IsFirst) {
1471   // Check C99 compatibility.
1472   if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
1473     enum {
1474       CannotAppearInIdentifier = 0,
1475       CannotStartIdentifier
1476     };
1477 
1478     static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1479         C99AllowedIDCharRanges);
1480     static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1481         C99DisallowedInitialIDCharRanges);
1482     if (!C99AllowedIDChars.contains(C)) {
1483       Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1484         << Range
1485         << CannotAppearInIdentifier;
1486     } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
1487       Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1488         << Range
1489         << CannotStartIdentifier;
1490     }
1491   }
1492 
1493   // Check C++98 compatibility.
1494   if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
1495     static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1496         CXX03AllowedIDCharRanges);
1497     if (!CXX03AllowedIDChars.contains(C)) {
1498       Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1499         << Range;
1500     }
1501   }
1502 }
1503 
1504 /// After encountering UTF-8 character C and interpreting it as an identifier
1505 /// character, check whether it's a homoglyph for a common non-identifier
1506 /// source character that is unlikely to be an intentional identifier
1507 /// character and warn if so.
1508 static void maybeDiagnoseUTF8Homoglyph(DiagnosticsEngine &Diags, uint32_t C,
1509                                        CharSourceRange Range) {
1510   // FIXME: Handle Unicode quotation marks (smart quotes, fullwidth quotes).
1511   struct HomoglyphPair {
1512     uint32_t Character;
1513     char LooksLike;
1514     bool operator<(HomoglyphPair R) const { return Character < R.Character; }
1515   };
1516   static constexpr HomoglyphPair SortedHomoglyphs[] = {
1517     {U'\u01c3', '!'}, // LATIN LETTER RETROFLEX CLICK
1518     {U'\u037e', ';'}, // GREEK QUESTION MARK
1519     {U'\u2212', '-'}, // MINUS SIGN
1520     {U'\u2215', '/'}, // DIVISION SLASH
1521     {U'\u2216', '\\'}, // SET MINUS
1522     {U'\u2217', '*'}, // ASTERISK OPERATOR
1523     {U'\u2223', '|'}, // DIVIDES
1524     {U'\u2227', '^'}, // LOGICAL AND
1525     {U'\u2236', ':'}, // RATIO
1526     {U'\u223c', '~'}, // TILDE OPERATOR
1527     {U'\ua789', ':'}, // MODIFIER LETTER COLON
1528     {U'\uff01', '!'}, // FULLWIDTH EXCLAMATION MARK
1529     {U'\uff03', '#'}, // FULLWIDTH NUMBER SIGN
1530     {U'\uff04', '$'}, // FULLWIDTH DOLLAR SIGN
1531     {U'\uff05', '%'}, // FULLWIDTH PERCENT SIGN
1532     {U'\uff06', '&'}, // FULLWIDTH AMPERSAND
1533     {U'\uff08', '('}, // FULLWIDTH LEFT PARENTHESIS
1534     {U'\uff09', ')'}, // FULLWIDTH RIGHT PARENTHESIS
1535     {U'\uff0a', '*'}, // FULLWIDTH ASTERISK
1536     {U'\uff0b', '+'}, // FULLWIDTH ASTERISK
1537     {U'\uff0c', ','}, // FULLWIDTH COMMA
1538     {U'\uff0d', '-'}, // FULLWIDTH HYPHEN-MINUS
1539     {U'\uff0e', '.'}, // FULLWIDTH FULL STOP
1540     {U'\uff0f', '/'}, // FULLWIDTH SOLIDUS
1541     {U'\uff1a', ':'}, // FULLWIDTH COLON
1542     {U'\uff1b', ';'}, // FULLWIDTH SEMICOLON
1543     {U'\uff1c', '<'}, // FULLWIDTH LESS-THAN SIGN
1544     {U'\uff1d', '='}, // FULLWIDTH EQUALS SIGN
1545     {U'\uff1e', '>'}, // FULLWIDTH GREATER-THAN SIGN
1546     {U'\uff1f', '?'}, // FULLWIDTH QUESTION MARK
1547     {U'\uff20', '@'}, // FULLWIDTH COMMERCIAL AT
1548     {U'\uff3b', '['}, // FULLWIDTH LEFT SQUARE BRACKET
1549     {U'\uff3c', '\\'}, // FULLWIDTH REVERSE SOLIDUS
1550     {U'\uff3d', ']'}, // FULLWIDTH RIGHT SQUARE BRACKET
1551     {U'\uff3e', '^'}, // FULLWIDTH CIRCUMFLEX ACCENT
1552     {U'\uff5b', '{'}, // FULLWIDTH LEFT CURLY BRACKET
1553     {U'\uff5c', '|'}, // FULLWIDTH VERTICAL LINE
1554     {U'\uff5d', '}'}, // FULLWIDTH RIGHT CURLY BRACKET
1555     {U'\uff5e', '~'}, // FULLWIDTH TILDE
1556     {0, 0}
1557   };
1558   auto Homoglyph =
1559       std::lower_bound(std::begin(SortedHomoglyphs),
1560                        std::end(SortedHomoglyphs) - 1, HomoglyphPair{C, '\0'});
1561   if (Homoglyph->Character == C) {
1562     llvm::SmallString<5> CharBuf;
1563     {
1564       llvm::raw_svector_ostream CharOS(CharBuf);
1565       llvm::write_hex(CharOS, C, llvm::HexPrintStyle::Upper, 4);
1566     }
1567     const char LooksLikeStr[] = {Homoglyph->LooksLike, 0};
1568     Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_homoglyph)
1569         << Range << CharBuf << LooksLikeStr;
1570   }
1571 }
1572 
1573 bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1574                                     Token &Result) {
1575   const char *UCNPtr = CurPtr + Size;
1576   uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
1577   if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1578     return false;
1579 
1580   if (!isLexingRawMode())
1581     maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1582                               makeCharRange(*this, CurPtr, UCNPtr),
1583                               /*IsFirst=*/false);
1584 
1585   Result.setFlag(Token::HasUCN);
1586   if ((UCNPtr - CurPtr ==  6 && CurPtr[1] == 'u') ||
1587       (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1588     CurPtr = UCNPtr;
1589   else
1590     while (CurPtr != UCNPtr)
1591       (void)getAndAdvanceChar(CurPtr, Result);
1592   return true;
1593 }
1594 
1595 bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1596   const char *UnicodePtr = CurPtr;
1597   llvm::UTF32 CodePoint;
1598   llvm::ConversionResult Result =
1599       llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1600                                 (const llvm::UTF8 *)BufferEnd,
1601                                 &CodePoint,
1602                                 llvm::strictConversion);
1603   if (Result != llvm::conversionOK ||
1604       !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1605     return false;
1606 
1607   if (!isLexingRawMode()) {
1608     maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1609                               makeCharRange(*this, CurPtr, UnicodePtr),
1610                               /*IsFirst=*/false);
1611     maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), CodePoint,
1612                                makeCharRange(*this, CurPtr, UnicodePtr));
1613   }
1614 
1615   CurPtr = UnicodePtr;
1616   return true;
1617 }
1618 
1619 bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
1620   // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1621   unsigned Size;
1622   unsigned char C = *CurPtr++;
1623   while (isIdentifierBody(C))
1624     C = *CurPtr++;
1625 
1626   --CurPtr;   // Back up over the skipped character.
1627 
1628   // Fast path, no $,\,? in identifier found.  '\' might be an escaped newline
1629   // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1630   //
1631   // TODO: Could merge these checks into an InfoTable flag to make the
1632   // comparison cheaper
1633   if (isASCII(C) && C != '\\' && C != '?' &&
1634       (C != '$' || !LangOpts.DollarIdents)) {
1635 FinishIdentifier:
1636     const char *IdStart = BufferPtr;
1637     FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1638     Result.setRawIdentifierData(IdStart);
1639 
1640     // If we are in raw mode, return this identifier raw.  There is no need to
1641     // look up identifier information or attempt to macro expand it.
1642     if (LexingRawMode)
1643       return true;
1644 
1645     // Fill in Result.IdentifierInfo and update the token kind,
1646     // looking up the identifier in the identifier table.
1647     IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1648     // Note that we have to call PP->LookUpIdentifierInfo() even for code
1649     // completion, it writes IdentifierInfo into Result, and callers rely on it.
1650 
1651     // If the completion point is at the end of an identifier, we want to treat
1652     // the identifier as incomplete even if it resolves to a macro or a keyword.
1653     // This allows e.g. 'class^' to complete to 'classifier'.
1654     if (isCodeCompletionPoint(CurPtr)) {
1655       // Return the code-completion token.
1656       Result.setKind(tok::code_completion);
1657       // Skip the code-completion char and all immediate identifier characters.
1658       // This ensures we get consistent behavior when completing at any point in
1659       // an identifier (i.e. at the start, in the middle, at the end). Note that
1660       // only simple cases (i.e. [a-zA-Z0-9_]) are supported to keep the code
1661       // simpler.
1662       assert(*CurPtr == 0 && "Completion character must be 0");
1663       ++CurPtr;
1664       // Note that code completion token is not added as a separate character
1665       // when the completion point is at the end of the buffer. Therefore, we need
1666       // to check if the buffer has ended.
1667       if (CurPtr < BufferEnd) {
1668         while (isIdentifierBody(*CurPtr))
1669           ++CurPtr;
1670       }
1671       BufferPtr = CurPtr;
1672       return true;
1673     }
1674 
1675     // Finally, now that we know we have an identifier, pass this off to the
1676     // preprocessor, which may macro expand it or something.
1677     if (II->isHandleIdentifierCase())
1678       return PP->HandleIdentifier(Result);
1679 
1680     return true;
1681   }
1682 
1683   // Otherwise, $,\,? in identifier found.  Enter slower path.
1684 
1685   C = getCharAndSize(CurPtr, Size);
1686   while (true) {
1687     if (C == '$') {
1688       // If we hit a $ and they are not supported in identifiers, we are done.
1689       if (!LangOpts.DollarIdents) goto FinishIdentifier;
1690 
1691       // Otherwise, emit a diagnostic and continue.
1692       if (!isLexingRawMode())
1693         Diag(CurPtr, diag::ext_dollar_in_identifier);
1694       CurPtr = ConsumeChar(CurPtr, Size, Result);
1695       C = getCharAndSize(CurPtr, Size);
1696       continue;
1697     } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
1698       C = getCharAndSize(CurPtr, Size);
1699       continue;
1700     } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
1701       C = getCharAndSize(CurPtr, Size);
1702       continue;
1703     } else if (!isIdentifierBody(C)) {
1704       goto FinishIdentifier;
1705     }
1706 
1707     // Otherwise, this character is good, consume it.
1708     CurPtr = ConsumeChar(CurPtr, Size, Result);
1709 
1710     C = getCharAndSize(CurPtr, Size);
1711     while (isIdentifierBody(C)) {
1712       CurPtr = ConsumeChar(CurPtr, Size, Result);
1713       C = getCharAndSize(CurPtr, Size);
1714     }
1715   }
1716 }
1717 
1718 /// isHexaLiteral - Return true if Start points to a hex constant.
1719 /// in microsoft mode (where this is supposed to be several different tokens).
1720 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1721   unsigned Size;
1722   char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1723   if (C1 != '0')
1724     return false;
1725   char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1726   return (C2 == 'x' || C2 == 'X');
1727 }
1728 
1729 /// LexNumericConstant - Lex the remainder of a integer or floating point
1730 /// constant. From[-1] is the first character lexed.  Return the end of the
1731 /// constant.
1732 bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1733   unsigned Size;
1734   char C = getCharAndSize(CurPtr, Size);
1735   char PrevCh = 0;
1736   while (isPreprocessingNumberBody(C)) {
1737     CurPtr = ConsumeChar(CurPtr, Size, Result);
1738     PrevCh = C;
1739     C = getCharAndSize(CurPtr, Size);
1740   }
1741 
1742   // If we fell out, check for a sign, due to 1e+12.  If we have one, continue.
1743   if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1744     // If we are in Microsoft mode, don't continue if the constant is hex.
1745     // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1746     if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1747       return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1748   }
1749 
1750   // If we have a hex FP constant, continue.
1751   if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1752     // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
1753     // not-quite-conforming extension. Only do so if this looks like it's
1754     // actually meant to be a hexfloat, and not if it has a ud-suffix.
1755     bool IsHexFloat = true;
1756     if (!LangOpts.C99) {
1757       if (!isHexaLiteral(BufferPtr, LangOpts))
1758         IsHexFloat = false;
1759       else if (!getLangOpts().CPlusPlus17 &&
1760                std::find(BufferPtr, CurPtr, '_') != CurPtr)
1761         IsHexFloat = false;
1762     }
1763     if (IsHexFloat)
1764       return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1765   }
1766 
1767   // If we have a digit separator, continue.
1768   if (C == '\'' && getLangOpts().CPlusPlus14) {
1769     unsigned NextSize;
1770     char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
1771     if (isIdentifierBody(Next)) {
1772       if (!isLexingRawMode())
1773         Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1774       CurPtr = ConsumeChar(CurPtr, Size, Result);
1775       CurPtr = ConsumeChar(CurPtr, NextSize, Result);
1776       return LexNumericConstant(Result, CurPtr);
1777     }
1778   }
1779 
1780   // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1781   if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1782     return LexNumericConstant(Result, CurPtr);
1783   if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1784     return LexNumericConstant(Result, CurPtr);
1785 
1786   // Update the location of token as well as BufferPtr.
1787   const char *TokStart = BufferPtr;
1788   FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1789   Result.setLiteralData(TokStart);
1790   return true;
1791 }
1792 
1793 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1794 /// in C++11, or warn on a ud-suffix in C++98.
1795 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1796                                bool IsStringLiteral) {
1797   assert(getLangOpts().CPlusPlus);
1798 
1799   // Maximally munch an identifier.
1800   unsigned Size;
1801   char C = getCharAndSize(CurPtr, Size);
1802   bool Consumed = false;
1803 
1804   if (!isIdentifierHead(C)) {
1805     if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1806       Consumed = true;
1807     else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1808       Consumed = true;
1809     else
1810       return CurPtr;
1811   }
1812 
1813   if (!getLangOpts().CPlusPlus11) {
1814     if (!isLexingRawMode())
1815       Diag(CurPtr,
1816            C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1817                     : diag::warn_cxx11_compat_reserved_user_defined_literal)
1818         << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1819     return CurPtr;
1820   }
1821 
1822   // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1823   // that does not start with an underscore is ill-formed. As a conforming
1824   // extension, we treat all such suffixes as if they had whitespace before
1825   // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1826   // likely to be a ud-suffix than a macro, however, and accept that.
1827   if (!Consumed) {
1828     bool IsUDSuffix = false;
1829     if (C == '_')
1830       IsUDSuffix = true;
1831     else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
1832       // In C++1y, we need to look ahead a few characters to see if this is a
1833       // valid suffix for a string literal or a numeric literal (this could be
1834       // the 'operator""if' defining a numeric literal operator).
1835       const unsigned MaxStandardSuffixLength = 3;
1836       char Buffer[MaxStandardSuffixLength] = { C };
1837       unsigned Consumed = Size;
1838       unsigned Chars = 1;
1839       while (true) {
1840         unsigned NextSize;
1841         char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1842                                          getLangOpts());
1843         if (!isIdentifierBody(Next)) {
1844           // End of suffix. Check whether this is on the whitelist.
1845           const StringRef CompleteSuffix(Buffer, Chars);
1846           IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1847                                                             CompleteSuffix);
1848           break;
1849         }
1850 
1851         if (Chars == MaxStandardSuffixLength)
1852           // Too long: can't be a standard suffix.
1853           break;
1854 
1855         Buffer[Chars++] = Next;
1856         Consumed += NextSize;
1857       }
1858     }
1859 
1860     if (!IsUDSuffix) {
1861       if (!isLexingRawMode())
1862         Diag(CurPtr, getLangOpts().MSVCCompat
1863                          ? diag::ext_ms_reserved_user_defined_literal
1864                          : diag::ext_reserved_user_defined_literal)
1865           << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1866       return CurPtr;
1867     }
1868 
1869     CurPtr = ConsumeChar(CurPtr, Size, Result);
1870   }
1871 
1872   Result.setFlag(Token::HasUDSuffix);
1873   while (true) {
1874     C = getCharAndSize(CurPtr, Size);
1875     if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1876     else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1877     else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1878     else break;
1879   }
1880 
1881   return CurPtr;
1882 }
1883 
1884 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1885 /// either " or L" or u8" or u" or U".
1886 bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1887                              tok::TokenKind Kind) {
1888   // Does this string contain the \0 character?
1889   const char *NulCharacter = nullptr;
1890 
1891   if (!isLexingRawMode() &&
1892       (Kind == tok::utf8_string_literal ||
1893        Kind == tok::utf16_string_literal ||
1894        Kind == tok::utf32_string_literal))
1895     Diag(BufferPtr, getLangOpts().CPlusPlus
1896            ? diag::warn_cxx98_compat_unicode_literal
1897            : diag::warn_c99_compat_unicode_literal);
1898 
1899   char C = getAndAdvanceChar(CurPtr, Result);
1900   while (C != '"') {
1901     // Skip escaped characters.  Escaped newlines will already be processed by
1902     // getAndAdvanceChar.
1903     if (C == '\\')
1904       C = getAndAdvanceChar(CurPtr, Result);
1905 
1906     if (C == '\n' || C == '\r' ||             // Newline.
1907         (C == 0 && CurPtr-1 == BufferEnd)) {  // End of file.
1908       if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1909         Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
1910       FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1911       return true;
1912     }
1913 
1914     if (C == 0) {
1915       if (isCodeCompletionPoint(CurPtr-1)) {
1916         PP->CodeCompleteNaturalLanguage();
1917         FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1918         cutOffLexing();
1919         return true;
1920       }
1921 
1922       NulCharacter = CurPtr-1;
1923     }
1924     C = getAndAdvanceChar(CurPtr, Result);
1925   }
1926 
1927   // If we are in C++11, lex the optional ud-suffix.
1928   if (getLangOpts().CPlusPlus)
1929     CurPtr = LexUDSuffix(Result, CurPtr, true);
1930 
1931   // If a nul character existed in the string, warn about it.
1932   if (NulCharacter && !isLexingRawMode())
1933     Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1934 
1935   // Update the location of the token as well as the BufferPtr instance var.
1936   const char *TokStart = BufferPtr;
1937   FormTokenWithChars(Result, CurPtr, Kind);
1938   Result.setLiteralData(TokStart);
1939   return true;
1940 }
1941 
1942 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1943 /// having lexed R", LR", u8R", uR", or UR".
1944 bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1945                                 tok::TokenKind Kind) {
1946   // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1947   //  Between the initial and final double quote characters of the raw string,
1948   //  any transformations performed in phases 1 and 2 (trigraphs,
1949   //  universal-character-names, and line splicing) are reverted.
1950 
1951   if (!isLexingRawMode())
1952     Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1953 
1954   unsigned PrefixLen = 0;
1955 
1956   while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1957     ++PrefixLen;
1958 
1959   // If the last character was not a '(', then we didn't lex a valid delimiter.
1960   if (CurPtr[PrefixLen] != '(') {
1961     if (!isLexingRawMode()) {
1962       const char *PrefixEnd = &CurPtr[PrefixLen];
1963       if (PrefixLen == 16) {
1964         Diag(PrefixEnd, diag::err_raw_delim_too_long);
1965       } else {
1966         Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1967           << StringRef(PrefixEnd, 1);
1968       }
1969     }
1970 
1971     // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1972     // it's possible the '"' was intended to be part of the raw string, but
1973     // there's not much we can do about that.
1974     while (true) {
1975       char C = *CurPtr++;
1976 
1977       if (C == '"')
1978         break;
1979       if (C == 0 && CurPtr-1 == BufferEnd) {
1980         --CurPtr;
1981         break;
1982       }
1983     }
1984 
1985     FormTokenWithChars(Result, CurPtr, tok::unknown);
1986     return true;
1987   }
1988 
1989   // Save prefix and move CurPtr past it
1990   const char *Prefix = CurPtr;
1991   CurPtr += PrefixLen + 1; // skip over prefix and '('
1992 
1993   while (true) {
1994     char C = *CurPtr++;
1995 
1996     if (C == ')') {
1997       // Check for prefix match and closing quote.
1998       if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1999         CurPtr += PrefixLen + 1; // skip over prefix and '"'
2000         break;
2001       }
2002     } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
2003       if (!isLexingRawMode())
2004         Diag(BufferPtr, diag::err_unterminated_raw_string)
2005           << StringRef(Prefix, PrefixLen);
2006       FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2007       return true;
2008     }
2009   }
2010 
2011   // If we are in C++11, lex the optional ud-suffix.
2012   if (getLangOpts().CPlusPlus)
2013     CurPtr = LexUDSuffix(Result, CurPtr, true);
2014 
2015   // Update the location of token as well as BufferPtr.
2016   const char *TokStart = BufferPtr;
2017   FormTokenWithChars(Result, CurPtr, Kind);
2018   Result.setLiteralData(TokStart);
2019   return true;
2020 }
2021 
2022 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
2023 /// after having lexed the '<' character.  This is used for #include filenames.
2024 bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
2025   // Does this string contain the \0 character?
2026   const char *NulCharacter = nullptr;
2027   const char *AfterLessPos = CurPtr;
2028   char C = getAndAdvanceChar(CurPtr, Result);
2029   while (C != '>') {
2030     // Skip escaped characters.  Escaped newlines will already be processed by
2031     // getAndAdvanceChar.
2032     if (C == '\\')
2033       C = getAndAdvanceChar(CurPtr, Result);
2034 
2035     if (C == '\n' || C == '\r' ||             // Newline.
2036         (C == 0 && (CurPtr-1 == BufferEnd ||  // End of file.
2037                     isCodeCompletionPoint(CurPtr-1)))) {
2038       // If the filename is unterminated, then it must just be a lone <
2039       // character.  Return this as such.
2040       FormTokenWithChars(Result, AfterLessPos, tok::less);
2041       return true;
2042     }
2043 
2044     if (C == 0) {
2045       NulCharacter = CurPtr-1;
2046     }
2047     C = getAndAdvanceChar(CurPtr, Result);
2048   }
2049 
2050   // If a nul character existed in the string, warn about it.
2051   if (NulCharacter && !isLexingRawMode())
2052     Diag(NulCharacter, diag::null_in_char_or_string) << 1;
2053 
2054   // Update the location of token as well as BufferPtr.
2055   const char *TokStart = BufferPtr;
2056   FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
2057   Result.setLiteralData(TokStart);
2058   return true;
2059 }
2060 
2061 /// LexCharConstant - Lex the remainder of a character constant, after having
2062 /// lexed either ' or L' or u8' or u' or U'.
2063 bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
2064                             tok::TokenKind Kind) {
2065   // Does this character contain the \0 character?
2066   const char *NulCharacter = nullptr;
2067 
2068   if (!isLexingRawMode()) {
2069     if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
2070       Diag(BufferPtr, getLangOpts().CPlusPlus
2071                           ? diag::warn_cxx98_compat_unicode_literal
2072                           : diag::warn_c99_compat_unicode_literal);
2073     else if (Kind == tok::utf8_char_constant)
2074       Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
2075   }
2076 
2077   char C = getAndAdvanceChar(CurPtr, Result);
2078   if (C == '\'') {
2079     if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
2080       Diag(BufferPtr, diag::ext_empty_character);
2081     FormTokenWithChars(Result, CurPtr, tok::unknown);
2082     return true;
2083   }
2084 
2085   while (C != '\'') {
2086     // Skip escaped characters.
2087     if (C == '\\')
2088       C = getAndAdvanceChar(CurPtr, Result);
2089 
2090     if (C == '\n' || C == '\r' ||             // Newline.
2091         (C == 0 && CurPtr-1 == BufferEnd)) {  // End of file.
2092       if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
2093         Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
2094       FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2095       return true;
2096     }
2097 
2098     if (C == 0) {
2099       if (isCodeCompletionPoint(CurPtr-1)) {
2100         PP->CodeCompleteNaturalLanguage();
2101         FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2102         cutOffLexing();
2103         return true;
2104       }
2105 
2106       NulCharacter = CurPtr-1;
2107     }
2108     C = getAndAdvanceChar(CurPtr, Result);
2109   }
2110 
2111   // If we are in C++11, lex the optional ud-suffix.
2112   if (getLangOpts().CPlusPlus)
2113     CurPtr = LexUDSuffix(Result, CurPtr, false);
2114 
2115   // If a nul character existed in the character, warn about it.
2116   if (NulCharacter && !isLexingRawMode())
2117     Diag(NulCharacter, diag::null_in_char_or_string) << 0;
2118 
2119   // Update the location of token as well as BufferPtr.
2120   const char *TokStart = BufferPtr;
2121   FormTokenWithChars(Result, CurPtr, Kind);
2122   Result.setLiteralData(TokStart);
2123   return true;
2124 }
2125 
2126 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2127 /// Update BufferPtr to point to the next non-whitespace character and return.
2128 ///
2129 /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2130 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2131                            bool &TokAtPhysicalStartOfLine) {
2132   // Whitespace - Skip it, then return the token after the whitespace.
2133   bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2134 
2135   unsigned char Char = *CurPtr;
2136 
2137   // Skip consecutive spaces efficiently.
2138   while (true) {
2139     // Skip horizontal whitespace very aggressively.
2140     while (isHorizontalWhitespace(Char))
2141       Char = *++CurPtr;
2142 
2143     // Otherwise if we have something other than whitespace, we're done.
2144     if (!isVerticalWhitespace(Char))
2145       break;
2146 
2147     if (ParsingPreprocessorDirective) {
2148       // End of preprocessor directive line, let LexTokenInternal handle this.
2149       BufferPtr = CurPtr;
2150       return false;
2151     }
2152 
2153     // OK, but handle newline.
2154     SawNewline = true;
2155     Char = *++CurPtr;
2156   }
2157 
2158   // If the client wants us to return whitespace, return it now.
2159   if (isKeepWhitespaceMode()) {
2160     FormTokenWithChars(Result, CurPtr, tok::unknown);
2161     if (SawNewline) {
2162       IsAtStartOfLine = true;
2163       IsAtPhysicalStartOfLine = true;
2164     }
2165     // FIXME: The next token will not have LeadingSpace set.
2166     return true;
2167   }
2168 
2169   // If this isn't immediately after a newline, there is leading space.
2170   char PrevChar = CurPtr[-1];
2171   bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2172 
2173   Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2174   if (SawNewline) {
2175     Result.setFlag(Token::StartOfLine);
2176     TokAtPhysicalStartOfLine = true;
2177   }
2178 
2179   BufferPtr = CurPtr;
2180   return false;
2181 }
2182 
2183 /// We have just read the // characters from input.  Skip until we find the
2184 /// newline character that terminates the comment.  Then update BufferPtr and
2185 /// return.
2186 ///
2187 /// If we're in KeepCommentMode or any CommentHandler has inserted
2188 /// some tokens, this will store the first token and return true.
2189 bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2190                             bool &TokAtPhysicalStartOfLine) {
2191   // If Line comments aren't explicitly enabled for this language, emit an
2192   // extension warning.
2193   if (!LangOpts.LineComment && !isLexingRawMode()) {
2194     Diag(BufferPtr, diag::ext_line_comment);
2195 
2196     // Mark them enabled so we only emit one warning for this translation
2197     // unit.
2198     LangOpts.LineComment = true;
2199   }
2200 
2201   // Scan over the body of the comment.  The common case, when scanning, is that
2202   // the comment contains normal ascii characters with nothing interesting in
2203   // them.  As such, optimize for this case with the inner loop.
2204   //
2205   // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2206   // character that ends the line comment.
2207   char C;
2208   while (true) {
2209     C = *CurPtr;
2210     // Skip over characters in the fast loop.
2211     while (C != 0 &&                // Potentially EOF.
2212            C != '\n' && C != '\r')  // Newline or DOS-style newline.
2213       C = *++CurPtr;
2214 
2215     const char *NextLine = CurPtr;
2216     if (C != 0) {
2217       // We found a newline, see if it's escaped.
2218       const char *EscapePtr = CurPtr-1;
2219       bool HasSpace = false;
2220       while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
2221         --EscapePtr;
2222         HasSpace = true;
2223       }
2224 
2225       if (*EscapePtr == '\\')
2226         // Escaped newline.
2227         CurPtr = EscapePtr;
2228       else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2229                EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2230         // Trigraph-escaped newline.
2231         CurPtr = EscapePtr-2;
2232       else
2233         break; // This is a newline, we're done.
2234 
2235       // If there was space between the backslash and newline, warn about it.
2236       if (HasSpace && !isLexingRawMode())
2237         Diag(EscapePtr, diag::backslash_newline_space);
2238     }
2239 
2240     // Otherwise, this is a hard case.  Fall back on getAndAdvanceChar to
2241     // properly decode the character.  Read it in raw mode to avoid emitting
2242     // diagnostics about things like trigraphs.  If we see an escaped newline,
2243     // we'll handle it below.
2244     const char *OldPtr = CurPtr;
2245     bool OldRawMode = isLexingRawMode();
2246     LexingRawMode = true;
2247     C = getAndAdvanceChar(CurPtr, Result);
2248     LexingRawMode = OldRawMode;
2249 
2250     // If we only read only one character, then no special handling is needed.
2251     // We're done and can skip forward to the newline.
2252     if (C != 0 && CurPtr == OldPtr+1) {
2253       CurPtr = NextLine;
2254       break;
2255     }
2256 
2257     // If we read multiple characters, and one of those characters was a \r or
2258     // \n, then we had an escaped newline within the comment.  Emit diagnostic
2259     // unless the next line is also a // comment.
2260     if (CurPtr != OldPtr + 1 && C != '/' &&
2261         (CurPtr == BufferEnd + 1 || CurPtr[0] != '/')) {
2262       for (; OldPtr != CurPtr; ++OldPtr)
2263         if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2264           // Okay, we found a // comment that ends in a newline, if the next
2265           // line is also a // comment, but has spaces, don't emit a diagnostic.
2266           if (isWhitespace(C)) {
2267             const char *ForwardPtr = CurPtr;
2268             while (isWhitespace(*ForwardPtr))  // Skip whitespace.
2269               ++ForwardPtr;
2270             if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2271               break;
2272           }
2273 
2274           if (!isLexingRawMode())
2275             Diag(OldPtr-1, diag::ext_multi_line_line_comment);
2276           break;
2277         }
2278     }
2279 
2280     if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2281       --CurPtr;
2282       break;
2283     }
2284 
2285     if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2286       PP->CodeCompleteNaturalLanguage();
2287       cutOffLexing();
2288       return false;
2289     }
2290   }
2291 
2292   // Found but did not consume the newline.  Notify comment handlers about the
2293   // comment unless we're in a #if 0 block.
2294   if (PP && !isLexingRawMode() &&
2295       PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2296                                             getSourceLocation(CurPtr)))) {
2297     BufferPtr = CurPtr;
2298     return true; // A token has to be returned.
2299   }
2300 
2301   // If we are returning comments as tokens, return this comment as a token.
2302   if (inKeepCommentMode())
2303     return SaveLineComment(Result, CurPtr);
2304 
2305   // If we are inside a preprocessor directive and we see the end of line,
2306   // return immediately, so that the lexer can return this as an EOD token.
2307   if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2308     BufferPtr = CurPtr;
2309     return false;
2310   }
2311 
2312   // Otherwise, eat the \n character.  We don't care if this is a \n\r or
2313   // \r\n sequence.  This is an efficiency hack (because we know the \n can't
2314   // contribute to another token), it isn't needed for correctness.  Note that
2315   // this is ok even in KeepWhitespaceMode, because we would have returned the
2316   /// comment above in that mode.
2317   ++CurPtr;
2318 
2319   // The next returned token is at the start of the line.
2320   Result.setFlag(Token::StartOfLine);
2321   TokAtPhysicalStartOfLine = true;
2322   // No leading whitespace seen so far.
2323   Result.clearFlag(Token::LeadingSpace);
2324   BufferPtr = CurPtr;
2325   return false;
2326 }
2327 
2328 /// If in save-comment mode, package up this Line comment in an appropriate
2329 /// way and return it.
2330 bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2331   // If we're not in a preprocessor directive, just return the // comment
2332   // directly.
2333   FormTokenWithChars(Result, CurPtr, tok::comment);
2334 
2335   if (!ParsingPreprocessorDirective || LexingRawMode)
2336     return true;
2337 
2338   // If this Line-style comment is in a macro definition, transmogrify it into
2339   // a C-style block comment.
2340   bool Invalid = false;
2341   std::string Spelling = PP->getSpelling(Result, &Invalid);
2342   if (Invalid)
2343     return true;
2344 
2345   assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2346   Spelling[1] = '*';   // Change prefix to "/*".
2347   Spelling += "*/";    // add suffix.
2348 
2349   Result.setKind(tok::comment);
2350   PP->CreateString(Spelling, Result,
2351                    Result.getLocation(), Result.getLocation());
2352   return true;
2353 }
2354 
2355 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2356 /// character (either \\n or \\r) is part of an escaped newline sequence.  Issue
2357 /// a diagnostic if so.  We know that the newline is inside of a block comment.
2358 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2359                                                   Lexer *L) {
2360   assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2361 
2362   // Back up off the newline.
2363   --CurPtr;
2364 
2365   // If this is a two-character newline sequence, skip the other character.
2366   if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2367     // \n\n or \r\r -> not escaped newline.
2368     if (CurPtr[0] == CurPtr[1])
2369       return false;
2370     // \n\r or \r\n -> skip the newline.
2371     --CurPtr;
2372   }
2373 
2374   // If we have horizontal whitespace, skip over it.  We allow whitespace
2375   // between the slash and newline.
2376   bool HasSpace = false;
2377   while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2378     --CurPtr;
2379     HasSpace = true;
2380   }
2381 
2382   // If we have a slash, we know this is an escaped newline.
2383   if (*CurPtr == '\\') {
2384     if (CurPtr[-1] != '*') return false;
2385   } else {
2386     // It isn't a slash, is it the ?? / trigraph?
2387     if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2388         CurPtr[-3] != '*')
2389       return false;
2390 
2391     // This is the trigraph ending the comment.  Emit a stern warning!
2392     CurPtr -= 2;
2393 
2394     // If no trigraphs are enabled, warn that we ignored this trigraph and
2395     // ignore this * character.
2396     if (!L->getLangOpts().Trigraphs) {
2397       if (!L->isLexingRawMode())
2398         L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
2399       return false;
2400     }
2401     if (!L->isLexingRawMode())
2402       L->Diag(CurPtr, diag::trigraph_ends_block_comment);
2403   }
2404 
2405   // Warn about having an escaped newline between the */ characters.
2406   if (!L->isLexingRawMode())
2407     L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
2408 
2409   // If there was space between the backslash and newline, warn about it.
2410   if (HasSpace && !L->isLexingRawMode())
2411     L->Diag(CurPtr, diag::backslash_newline_space);
2412 
2413   return true;
2414 }
2415 
2416 #ifdef __SSE2__
2417 #include <emmintrin.h>
2418 #elif __ALTIVEC__
2419 #include <altivec.h>
2420 #undef bool
2421 #endif
2422 
2423 /// We have just read from input the / and * characters that started a comment.
2424 /// Read until we find the * and / characters that terminate the comment.
2425 /// Note that we don't bother decoding trigraphs or escaped newlines in block
2426 /// comments, because they cannot cause the comment to end.  The only thing
2427 /// that can happen is the comment could end with an escaped newline between
2428 /// the terminating * and /.
2429 ///
2430 /// If we're in KeepCommentMode or any CommentHandler has inserted
2431 /// some tokens, this will store the first token and return true.
2432 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2433                              bool &TokAtPhysicalStartOfLine) {
2434   // Scan one character past where we should, looking for a '/' character.  Once
2435   // we find it, check to see if it was preceded by a *.  This common
2436   // optimization helps people who like to put a lot of * characters in their
2437   // comments.
2438 
2439   // The first character we get with newlines and trigraphs skipped to handle
2440   // the degenerate /*/ case below correctly if the * has an escaped newline
2441   // after it.
2442   unsigned CharSize;
2443   unsigned char C = getCharAndSize(CurPtr, CharSize);
2444   CurPtr += CharSize;
2445   if (C == 0 && CurPtr == BufferEnd+1) {
2446     if (!isLexingRawMode())
2447       Diag(BufferPtr, diag::err_unterminated_block_comment);
2448     --CurPtr;
2449 
2450     // KeepWhitespaceMode should return this broken comment as a token.  Since
2451     // it isn't a well formed comment, just return it as an 'unknown' token.
2452     if (isKeepWhitespaceMode()) {
2453       FormTokenWithChars(Result, CurPtr, tok::unknown);
2454       return true;
2455     }
2456 
2457     BufferPtr = CurPtr;
2458     return false;
2459   }
2460 
2461   // Check to see if the first character after the '/*' is another /.  If so,
2462   // then this slash does not end the block comment, it is part of it.
2463   if (C == '/')
2464     C = *CurPtr++;
2465 
2466   while (true) {
2467     // Skip over all non-interesting characters until we find end of buffer or a
2468     // (probably ending) '/' character.
2469     if (CurPtr + 24 < BufferEnd &&
2470         // If there is a code-completion point avoid the fast scan because it
2471         // doesn't check for '\0'.
2472         !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2473       // While not aligned to a 16-byte boundary.
2474       while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2475         C = *CurPtr++;
2476 
2477       if (C == '/') goto FoundSlash;
2478 
2479 #ifdef __SSE2__
2480       __m128i Slashes = _mm_set1_epi8('/');
2481       while (CurPtr+16 <= BufferEnd) {
2482         int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2483                                     Slashes));
2484         if (cmp != 0) {
2485           // Adjust the pointer to point directly after the first slash. It's
2486           // not necessary to set C here, it will be overwritten at the end of
2487           // the outer loop.
2488           CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
2489           goto FoundSlash;
2490         }
2491         CurPtr += 16;
2492       }
2493 #elif __ALTIVEC__
2494       __vector unsigned char Slashes = {
2495         '/', '/', '/', '/',  '/', '/', '/', '/',
2496         '/', '/', '/', '/',  '/', '/', '/', '/'
2497       };
2498       while (CurPtr+16 <= BufferEnd &&
2499              !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
2500         CurPtr += 16;
2501 #else
2502       // Scan for '/' quickly.  Many block comments are very large.
2503       while (CurPtr[0] != '/' &&
2504              CurPtr[1] != '/' &&
2505              CurPtr[2] != '/' &&
2506              CurPtr[3] != '/' &&
2507              CurPtr+4 < BufferEnd) {
2508         CurPtr += 4;
2509       }
2510 #endif
2511 
2512       // It has to be one of the bytes scanned, increment to it and read one.
2513       C = *CurPtr++;
2514     }
2515 
2516     // Loop to scan the remainder.
2517     while (C != '/' && C != '\0')
2518       C = *CurPtr++;
2519 
2520     if (C == '/') {
2521   FoundSlash:
2522       if (CurPtr[-2] == '*')  // We found the final */.  We're done!
2523         break;
2524 
2525       if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2526         if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2527           // We found the final */, though it had an escaped newline between the
2528           // * and /.  We're done!
2529           break;
2530         }
2531       }
2532       if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2533         // If this is a /* inside of the comment, emit a warning.  Don't do this
2534         // if this is a /*/, which will end the comment.  This misses cases with
2535         // embedded escaped newlines, but oh well.
2536         if (!isLexingRawMode())
2537           Diag(CurPtr-1, diag::warn_nested_block_comment);
2538       }
2539     } else if (C == 0 && CurPtr == BufferEnd+1) {
2540       if (!isLexingRawMode())
2541         Diag(BufferPtr, diag::err_unterminated_block_comment);
2542       // Note: the user probably forgot a */.  We could continue immediately
2543       // after the /*, but this would involve lexing a lot of what really is the
2544       // comment, which surely would confuse the parser.
2545       --CurPtr;
2546 
2547       // KeepWhitespaceMode should return this broken comment as a token.  Since
2548       // it isn't a well formed comment, just return it as an 'unknown' token.
2549       if (isKeepWhitespaceMode()) {
2550         FormTokenWithChars(Result, CurPtr, tok::unknown);
2551         return true;
2552       }
2553 
2554       BufferPtr = CurPtr;
2555       return false;
2556     } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2557       PP->CodeCompleteNaturalLanguage();
2558       cutOffLexing();
2559       return false;
2560     }
2561 
2562     C = *CurPtr++;
2563   }
2564 
2565   // Notify comment handlers about the comment unless we're in a #if 0 block.
2566   if (PP && !isLexingRawMode() &&
2567       PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2568                                             getSourceLocation(CurPtr)))) {
2569     BufferPtr = CurPtr;
2570     return true; // A token has to be returned.
2571   }
2572 
2573   // If we are returning comments as tokens, return this comment as a token.
2574   if (inKeepCommentMode()) {
2575     FormTokenWithChars(Result, CurPtr, tok::comment);
2576     return true;
2577   }
2578 
2579   // It is common for the tokens immediately after a /**/ comment to be
2580   // whitespace.  Instead of going through the big switch, handle it
2581   // efficiently now.  This is safe even in KeepWhitespaceMode because we would
2582   // have already returned above with the comment as a token.
2583   if (isHorizontalWhitespace(*CurPtr)) {
2584     SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
2585     return false;
2586   }
2587 
2588   // Otherwise, just return so that the next character will be lexed as a token.
2589   BufferPtr = CurPtr;
2590   Result.setFlag(Token::LeadingSpace);
2591   return false;
2592 }
2593 
2594 //===----------------------------------------------------------------------===//
2595 // Primary Lexing Entry Points
2596 //===----------------------------------------------------------------------===//
2597 
2598 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2599 /// uninterpreted string.  This switches the lexer out of directive mode.
2600 void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
2601   assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2602          "Must be in a preprocessing directive!");
2603   Token Tmp;
2604 
2605   // CurPtr - Cache BufferPtr in an automatic variable.
2606   const char *CurPtr = BufferPtr;
2607   while (true) {
2608     char Char = getAndAdvanceChar(CurPtr, Tmp);
2609     switch (Char) {
2610     default:
2611       if (Result)
2612         Result->push_back(Char);
2613       break;
2614     case 0:  // Null.
2615       // Found end of file?
2616       if (CurPtr-1 != BufferEnd) {
2617         if (isCodeCompletionPoint(CurPtr-1)) {
2618           PP->CodeCompleteNaturalLanguage();
2619           cutOffLexing();
2620           return;
2621         }
2622 
2623         // Nope, normal character, continue.
2624         if (Result)
2625           Result->push_back(Char);
2626         break;
2627       }
2628       // FALL THROUGH.
2629       LLVM_FALLTHROUGH;
2630     case '\r':
2631     case '\n':
2632       // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2633       assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2634       BufferPtr = CurPtr-1;
2635 
2636       // Next, lex the character, which should handle the EOD transition.
2637       Lex(Tmp);
2638       if (Tmp.is(tok::code_completion)) {
2639         if (PP)
2640           PP->CodeCompleteNaturalLanguage();
2641         Lex(Tmp);
2642       }
2643       assert(Tmp.is(tok::eod) && "Unexpected token!");
2644 
2645       // Finally, we're done;
2646       return;
2647     }
2648   }
2649 }
2650 
2651 /// LexEndOfFile - CurPtr points to the end of this file.  Handle this
2652 /// condition, reporting diagnostics and handling other edge cases as required.
2653 /// This returns true if Result contains a token, false if PP.Lex should be
2654 /// called again.
2655 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2656   // If we hit the end of the file while parsing a preprocessor directive,
2657   // end the preprocessor directive first.  The next token returned will
2658   // then be the end of file.
2659   if (ParsingPreprocessorDirective) {
2660     // Done parsing the "line".
2661     ParsingPreprocessorDirective = false;
2662     // Update the location of token as well as BufferPtr.
2663     FormTokenWithChars(Result, CurPtr, tok::eod);
2664 
2665     // Restore comment saving mode, in case it was disabled for directive.
2666     if (PP)
2667       resetExtendedTokenMode();
2668     return true;  // Have a token.
2669   }
2670 
2671   // If we are in raw mode, return this event as an EOF token.  Let the caller
2672   // that put us in raw mode handle the event.
2673   if (isLexingRawMode()) {
2674     Result.startToken();
2675     BufferPtr = BufferEnd;
2676     FormTokenWithChars(Result, BufferEnd, tok::eof);
2677     return true;
2678   }
2679 
2680   if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
2681     PP->setRecordedPreambleConditionalStack(ConditionalStack);
2682     ConditionalStack.clear();
2683   }
2684 
2685   // Issue diagnostics for unterminated #if and missing newline.
2686 
2687   // If we are in a #if directive, emit an error.
2688   while (!ConditionalStack.empty()) {
2689     if (PP->getCodeCompletionFileLoc() != FileLoc)
2690       PP->Diag(ConditionalStack.back().IfLoc,
2691                diag::err_pp_unterminated_conditional);
2692     ConditionalStack.pop_back();
2693   }
2694 
2695   // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2696   // a pedwarn.
2697   if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2698     DiagnosticsEngine &Diags = PP->getDiagnostics();
2699     SourceLocation EndLoc = getSourceLocation(BufferEnd);
2700     unsigned DiagID;
2701 
2702     if (LangOpts.CPlusPlus11) {
2703       // C++11 [lex.phases] 2.2 p2
2704       // Prefer the C++98 pedantic compatibility warning over the generic,
2705       // non-extension, user-requested "missing newline at EOF" warning.
2706       if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
2707         DiagID = diag::warn_cxx98_compat_no_newline_eof;
2708       } else {
2709         DiagID = diag::warn_no_newline_eof;
2710       }
2711     } else {
2712       DiagID = diag::ext_no_newline_eof;
2713     }
2714 
2715     Diag(BufferEnd, DiagID)
2716       << FixItHint::CreateInsertion(EndLoc, "\n");
2717   }
2718 
2719   BufferPtr = CurPtr;
2720 
2721   // Finally, let the preprocessor handle this.
2722   return PP->HandleEndOfFile(Result, isPragmaLexer());
2723 }
2724 
2725 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2726 /// the specified lexer will return a tok::l_paren token, 0 if it is something
2727 /// else and 2 if there are no more tokens in the buffer controlled by the
2728 /// lexer.
2729 unsigned Lexer::isNextPPTokenLParen() {
2730   assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2731 
2732   // Switch to 'skipping' mode.  This will ensure that we can lex a token
2733   // without emitting diagnostics, disables macro expansion, and will cause EOF
2734   // to return an EOF token instead of popping the include stack.
2735   LexingRawMode = true;
2736 
2737   // Save state that can be changed while lexing so that we can restore it.
2738   const char *TmpBufferPtr = BufferPtr;
2739   bool inPPDirectiveMode = ParsingPreprocessorDirective;
2740   bool atStartOfLine = IsAtStartOfLine;
2741   bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2742   bool leadingSpace = HasLeadingSpace;
2743 
2744   Token Tok;
2745   Lex(Tok);
2746 
2747   // Restore state that may have changed.
2748   BufferPtr = TmpBufferPtr;
2749   ParsingPreprocessorDirective = inPPDirectiveMode;
2750   HasLeadingSpace = leadingSpace;
2751   IsAtStartOfLine = atStartOfLine;
2752   IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
2753 
2754   // Restore the lexer back to non-skipping mode.
2755   LexingRawMode = false;
2756 
2757   if (Tok.is(tok::eof))
2758     return 2;
2759   return Tok.is(tok::l_paren);
2760 }
2761 
2762 /// \brief Find the end of a version control conflict marker.
2763 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2764                                    ConflictMarkerKind CMK) {
2765   const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2766   size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2767   auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
2768   size_t Pos = RestOfBuffer.find(Terminator);
2769   while (Pos != StringRef::npos) {
2770     // Must occur at start of line.
2771     if (Pos == 0 ||
2772         (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
2773       RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2774       Pos = RestOfBuffer.find(Terminator);
2775       continue;
2776     }
2777     return RestOfBuffer.data()+Pos;
2778   }
2779   return nullptr;
2780 }
2781 
2782 /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2783 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2784 /// and recover nicely.  This returns true if it is a conflict marker and false
2785 /// if not.
2786 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2787   // Only a conflict marker if it starts at the beginning of a line.
2788   if (CurPtr != BufferStart &&
2789       CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2790     return false;
2791 
2792   // Check to see if we have <<<<<<< or >>>>.
2793   if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2794       !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
2795     return false;
2796 
2797   // If we have a situation where we don't care about conflict markers, ignore
2798   // it.
2799   if (CurrentConflictMarkerState || isLexingRawMode())
2800     return false;
2801 
2802   ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2803 
2804   // Check to see if there is an ending marker somewhere in the buffer at the
2805   // start of a line to terminate this conflict marker.
2806   if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
2807     // We found a match.  We are really in a conflict marker.
2808     // Diagnose this, and ignore to the end of line.
2809     Diag(CurPtr, diag::err_conflict_marker);
2810     CurrentConflictMarkerState = Kind;
2811 
2812     // Skip ahead to the end of line.  We know this exists because the
2813     // end-of-conflict marker starts with \r or \n.
2814     while (*CurPtr != '\r' && *CurPtr != '\n') {
2815       assert(CurPtr != BufferEnd && "Didn't find end of line");
2816       ++CurPtr;
2817     }
2818     BufferPtr = CurPtr;
2819     return true;
2820   }
2821 
2822   // No end of conflict marker found.
2823   return false;
2824 }
2825 
2826 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2827 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2828 /// is the end of a conflict marker.  Handle it by ignoring up until the end of
2829 /// the line.  This returns true if it is a conflict marker and false if not.
2830 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2831   // Only a conflict marker if it starts at the beginning of a line.
2832   if (CurPtr != BufferStart &&
2833       CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2834     return false;
2835 
2836   // If we have a situation where we don't care about conflict markers, ignore
2837   // it.
2838   if (!CurrentConflictMarkerState || isLexingRawMode())
2839     return false;
2840 
2841   // Check to see if we have the marker (4 characters in a row).
2842   for (unsigned i = 1; i != 4; ++i)
2843     if (CurPtr[i] != CurPtr[0])
2844       return false;
2845 
2846   // If we do have it, search for the end of the conflict marker.  This could
2847   // fail if it got skipped with a '#if 0' or something.  Note that CurPtr might
2848   // be the end of conflict marker.
2849   if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2850                                         CurrentConflictMarkerState)) {
2851     CurPtr = End;
2852 
2853     // Skip ahead to the end of line.
2854     while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2855       ++CurPtr;
2856 
2857     BufferPtr = CurPtr;
2858 
2859     // No longer in the conflict marker.
2860     CurrentConflictMarkerState = CMK_None;
2861     return true;
2862   }
2863 
2864   return false;
2865 }
2866 
2867 static const char *findPlaceholderEnd(const char *CurPtr,
2868                                       const char *BufferEnd) {
2869   if (CurPtr == BufferEnd)
2870     return nullptr;
2871   BufferEnd -= 1; // Scan until the second last character.
2872   for (; CurPtr != BufferEnd; ++CurPtr) {
2873     if (CurPtr[0] == '#' && CurPtr[1] == '>')
2874       return CurPtr + 2;
2875   }
2876   return nullptr;
2877 }
2878 
2879 bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2880   assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
2881   if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || LexingRawMode)
2882     return false;
2883   const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2884   if (!End)
2885     return false;
2886   const char *Start = CurPtr - 1;
2887   if (!LangOpts.AllowEditorPlaceholders)
2888     Diag(Start, diag::err_placeholder_in_source);
2889   Result.startToken();
2890   FormTokenWithChars(Result, End, tok::raw_identifier);
2891   Result.setRawIdentifierData(Start);
2892   PP->LookUpIdentifierInfo(Result);
2893   Result.setFlag(Token::IsEditorPlaceholder);
2894   BufferPtr = End;
2895   return true;
2896 }
2897 
2898 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2899   if (PP && PP->isCodeCompletionEnabled()) {
2900     SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
2901     return Loc == PP->getCodeCompletionLoc();
2902   }
2903 
2904   return false;
2905 }
2906 
2907 uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2908                            Token *Result) {
2909   unsigned CharSize;
2910   char Kind = getCharAndSize(StartPtr, CharSize);
2911 
2912   unsigned NumHexDigits;
2913   if (Kind == 'u')
2914     NumHexDigits = 4;
2915   else if (Kind == 'U')
2916     NumHexDigits = 8;
2917   else
2918     return 0;
2919 
2920   if (!LangOpts.CPlusPlus && !LangOpts.C99) {
2921     if (Result && !isLexingRawMode())
2922       Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
2923     return 0;
2924   }
2925 
2926   const char *CurPtr = StartPtr + CharSize;
2927   const char *KindLoc = &CurPtr[-1];
2928 
2929   uint32_t CodePoint = 0;
2930   for (unsigned i = 0; i < NumHexDigits; ++i) {
2931     char C = getCharAndSize(CurPtr, CharSize);
2932 
2933     unsigned Value = llvm::hexDigitValue(C);
2934     if (Value == -1U) {
2935       if (Result && !isLexingRawMode()) {
2936         if (i == 0) {
2937           Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2938             << StringRef(KindLoc, 1);
2939         } else {
2940           Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
2941 
2942           // If the user wrote \U1234, suggest a fixit to \u.
2943           if (i == 4 && NumHexDigits == 8) {
2944             CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
2945             Diag(KindLoc, diag::note_ucn_four_not_eight)
2946               << FixItHint::CreateReplacement(URange, "u");
2947           }
2948         }
2949       }
2950 
2951       return 0;
2952     }
2953 
2954     CodePoint <<= 4;
2955     CodePoint += Value;
2956 
2957     CurPtr += CharSize;
2958   }
2959 
2960   if (Result) {
2961     Result->setFlag(Token::HasUCN);
2962     if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
2963       StartPtr = CurPtr;
2964     else
2965       while (StartPtr != CurPtr)
2966         (void)getAndAdvanceChar(StartPtr, *Result);
2967   } else {
2968     StartPtr = CurPtr;
2969   }
2970 
2971   // Don't apply C family restrictions to UCNs in assembly mode
2972   if (LangOpts.AsmPreprocessor)
2973     return CodePoint;
2974 
2975   // C99 6.4.3p2: A universal character name shall not specify a character whose
2976   //   short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2977   //   0060 (`), nor one in the range D800 through DFFF inclusive.)
2978   // C++11 [lex.charset]p2: If the hexadecimal value for a
2979   //   universal-character-name corresponds to a surrogate code point (in the
2980   //   range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2981   //   if the hexadecimal value for a universal-character-name outside the
2982   //   c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2983   //   string literal corresponds to a control character (in either of the
2984   //   ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2985   //   basic source character set, the program is ill-formed.
2986   if (CodePoint < 0xA0) {
2987     if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2988       return CodePoint;
2989 
2990     // We don't use isLexingRawMode() here because we need to warn about bad
2991     // UCNs even when skipping preprocessing tokens in a #if block.
2992     if (Result && PP) {
2993       if (CodePoint < 0x20 || CodePoint >= 0x7F)
2994         Diag(BufferPtr, diag::err_ucn_control_character);
2995       else {
2996         char C = static_cast<char>(CodePoint);
2997         Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2998       }
2999     }
3000 
3001     return 0;
3002   } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
3003     // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
3004     // We don't use isLexingRawMode() here because we need to diagnose bad
3005     // UCNs even when skipping preprocessing tokens in a #if block.
3006     if (Result && PP) {
3007       if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
3008         Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
3009       else
3010         Diag(BufferPtr, diag::err_ucn_escape_invalid);
3011     }
3012     return 0;
3013   }
3014 
3015   return CodePoint;
3016 }
3017 
3018 bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
3019                                    const char *CurPtr) {
3020   static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
3021       UnicodeWhitespaceCharRanges);
3022   if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
3023       UnicodeWhitespaceChars.contains(C)) {
3024     Diag(BufferPtr, diag::ext_unicode_whitespace)
3025       << makeCharRange(*this, BufferPtr, CurPtr);
3026 
3027     Result.setFlag(Token::LeadingSpace);
3028     return true;
3029   }
3030   return false;
3031 }
3032 
3033 bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
3034   if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
3035     if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
3036         !PP->isPreprocessedOutput()) {
3037       maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
3038                                 makeCharRange(*this, BufferPtr, CurPtr),
3039                                 /*IsFirst=*/true);
3040     }
3041 
3042     MIOpt.ReadToken();
3043     return LexIdentifier(Result, CurPtr);
3044   }
3045 
3046   if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
3047       !PP->isPreprocessedOutput() &&
3048       !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
3049     // Non-ASCII characters tend to creep into source code unintentionally.
3050     // Instead of letting the parser complain about the unknown token,
3051     // just drop the character.
3052     // Note that we can /only/ do this when the non-ASCII character is actually
3053     // spelled as Unicode, not written as a UCN. The standard requires that
3054     // we not throw away any possible preprocessor tokens, but there's a
3055     // loophole in the mapping of Unicode characters to basic character set
3056     // characters that allows us to map these particular characters to, say,
3057     // whitespace.
3058     Diag(BufferPtr, diag::err_non_ascii)
3059       << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
3060 
3061     BufferPtr = CurPtr;
3062     return false;
3063   }
3064 
3065   // Otherwise, we have an explicit UCN or a character that's unlikely to show
3066   // up by accident.
3067   MIOpt.ReadToken();
3068   FormTokenWithChars(Result, CurPtr, tok::unknown);
3069   return true;
3070 }
3071 
3072 void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
3073   IsAtStartOfLine = Result.isAtStartOfLine();
3074   HasLeadingSpace = Result.hasLeadingSpace();
3075   HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
3076   // Note that this doesn't affect IsAtPhysicalStartOfLine.
3077 }
3078 
3079 bool Lexer::Lex(Token &Result) {
3080   // Start a new token.
3081   Result.startToken();
3082 
3083   // Set up misc whitespace flags for LexTokenInternal.
3084   if (IsAtStartOfLine) {
3085     Result.setFlag(Token::StartOfLine);
3086     IsAtStartOfLine = false;
3087   }
3088 
3089   if (HasLeadingSpace) {
3090     Result.setFlag(Token::LeadingSpace);
3091     HasLeadingSpace = false;
3092   }
3093 
3094   if (HasLeadingEmptyMacro) {
3095     Result.setFlag(Token::LeadingEmptyMacro);
3096     HasLeadingEmptyMacro = false;
3097   }
3098 
3099   bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
3100   IsAtPhysicalStartOfLine = false;
3101   bool isRawLex = isLexingRawMode();
3102   (void) isRawLex;
3103   bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
3104   // (After the LexTokenInternal call, the lexer might be destroyed.)
3105   assert((returnedToken || !isRawLex) && "Raw lex must succeed");
3106   return returnedToken;
3107 }
3108 
3109 /// LexTokenInternal - This implements a simple C family lexer.  It is an
3110 /// extremely performance critical piece of code.  This assumes that the buffer
3111 /// has a null character at the end of the file.  This returns a preprocessing
3112 /// token, not a normal token, as such, it is an internal interface.  It assumes
3113 /// that the Flags of result have been cleared before calling this.
3114 bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
3115 LexNextToken:
3116   // New token, can't need cleaning yet.
3117   Result.clearFlag(Token::NeedsCleaning);
3118   Result.setIdentifierInfo(nullptr);
3119 
3120   // CurPtr - Cache BufferPtr in an automatic variable.
3121   const char *CurPtr = BufferPtr;
3122 
3123   // Small amounts of horizontal whitespace is very common between tokens.
3124   if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
3125     ++CurPtr;
3126     while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3127       ++CurPtr;
3128 
3129     // If we are keeping whitespace and other tokens, just return what we just
3130     // skipped.  The next lexer invocation will return the token after the
3131     // whitespace.
3132     if (isKeepWhitespaceMode()) {
3133       FormTokenWithChars(Result, CurPtr, tok::unknown);
3134       // FIXME: The next token will not have LeadingSpace set.
3135       return true;
3136     }
3137 
3138     BufferPtr = CurPtr;
3139     Result.setFlag(Token::LeadingSpace);
3140   }
3141 
3142   unsigned SizeTmp, SizeTmp2;   // Temporaries for use in cases below.
3143 
3144   // Read a character, advancing over it.
3145   char Char = getAndAdvanceChar(CurPtr, Result);
3146   tok::TokenKind Kind;
3147 
3148   switch (Char) {
3149   case 0:  // Null.
3150     // Found end of file?
3151     if (CurPtr-1 == BufferEnd)
3152       return LexEndOfFile(Result, CurPtr-1);
3153 
3154     // Check if we are performing code completion.
3155     if (isCodeCompletionPoint(CurPtr-1)) {
3156       // Return the code-completion token.
3157       Result.startToken();
3158       FormTokenWithChars(Result, CurPtr, tok::code_completion);
3159       return true;
3160     }
3161 
3162     if (!isLexingRawMode())
3163       Diag(CurPtr-1, diag::null_in_file);
3164     Result.setFlag(Token::LeadingSpace);
3165     if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3166       return true; // KeepWhitespaceMode
3167 
3168     // We know the lexer hasn't changed, so just try again with this lexer.
3169     // (We manually eliminate the tail call to avoid recursion.)
3170     goto LexNextToken;
3171 
3172   case 26:  // DOS & CP/M EOF: "^Z".
3173     // If we're in Microsoft extensions mode, treat this as end of file.
3174     if (LangOpts.MicrosoftExt) {
3175       if (!isLexingRawMode())
3176         Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
3177       return LexEndOfFile(Result, CurPtr-1);
3178     }
3179 
3180     // If Microsoft extensions are disabled, this is just random garbage.
3181     Kind = tok::unknown;
3182     break;
3183 
3184   case '\r':
3185     if (CurPtr[0] == '\n')
3186       Char = getAndAdvanceChar(CurPtr, Result);
3187     LLVM_FALLTHROUGH;
3188   case '\n':
3189     // If we are inside a preprocessor directive and we see the end of line,
3190     // we know we are done with the directive, so return an EOD token.
3191     if (ParsingPreprocessorDirective) {
3192       // Done parsing the "line".
3193       ParsingPreprocessorDirective = false;
3194 
3195       // Restore comment saving mode, in case it was disabled for directive.
3196       if (PP)
3197         resetExtendedTokenMode();
3198 
3199       // Since we consumed a newline, we are back at the start of a line.
3200       IsAtStartOfLine = true;
3201       IsAtPhysicalStartOfLine = true;
3202 
3203       Kind = tok::eod;
3204       break;
3205     }
3206 
3207     // No leading whitespace seen so far.
3208     Result.clearFlag(Token::LeadingSpace);
3209 
3210     if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3211       return true; // KeepWhitespaceMode
3212 
3213     // We only saw whitespace, so just try again with this lexer.
3214     // (We manually eliminate the tail call to avoid recursion.)
3215     goto LexNextToken;
3216   case ' ':
3217   case '\t':
3218   case '\f':
3219   case '\v':
3220   SkipHorizontalWhitespace:
3221     Result.setFlag(Token::LeadingSpace);
3222     if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3223       return true; // KeepWhitespaceMode
3224 
3225   SkipIgnoredUnits:
3226     CurPtr = BufferPtr;
3227 
3228     // If the next token is obviously a // or /* */ comment, skip it efficiently
3229     // too (without going through the big switch stmt).
3230     if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
3231         LangOpts.LineComment &&
3232         (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
3233       if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3234         return true; // There is a token to return.
3235       goto SkipIgnoredUnits;
3236     } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
3237       if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3238         return true; // There is a token to return.
3239       goto SkipIgnoredUnits;
3240     } else if (isHorizontalWhitespace(*CurPtr)) {
3241       goto SkipHorizontalWhitespace;
3242     }
3243     // We only saw whitespace, so just try again with this lexer.
3244     // (We manually eliminate the tail call to avoid recursion.)
3245     goto LexNextToken;
3246 
3247   // C99 6.4.4.1: Integer Constants.
3248   // C99 6.4.4.2: Floating Constants.
3249   case '0': case '1': case '2': case '3': case '4':
3250   case '5': case '6': case '7': case '8': case '9':
3251     // Notify MIOpt that we read a non-whitespace/non-comment token.
3252     MIOpt.ReadToken();
3253     return LexNumericConstant(Result, CurPtr);
3254 
3255   case 'u':   // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
3256     // Notify MIOpt that we read a non-whitespace/non-comment token.
3257     MIOpt.ReadToken();
3258 
3259     if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3260       Char = getCharAndSize(CurPtr, SizeTmp);
3261 
3262       // UTF-16 string literal
3263       if (Char == '"')
3264         return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3265                                 tok::utf16_string_literal);
3266 
3267       // UTF-16 character constant
3268       if (Char == '\'')
3269         return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3270                                tok::utf16_char_constant);
3271 
3272       // UTF-16 raw string literal
3273       if (Char == 'R' && LangOpts.CPlusPlus11 &&
3274           getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3275         return LexRawStringLiteral(Result,
3276                                ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3277                                            SizeTmp2, Result),
3278                                tok::utf16_string_literal);
3279 
3280       if (Char == '8') {
3281         char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3282 
3283         // UTF-8 string literal
3284         if (Char2 == '"')
3285           return LexStringLiteral(Result,
3286                                ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3287                                            SizeTmp2, Result),
3288                                tok::utf8_string_literal);
3289         if (Char2 == '\'' && LangOpts.CPlusPlus17)
3290           return LexCharConstant(
3291               Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3292                                   SizeTmp2, Result),
3293               tok::utf8_char_constant);
3294 
3295         if (Char2 == 'R' && LangOpts.CPlusPlus11) {
3296           unsigned SizeTmp3;
3297           char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3298           // UTF-8 raw string literal
3299           if (Char3 == '"') {
3300             return LexRawStringLiteral(Result,
3301                    ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3302                                            SizeTmp2, Result),
3303                                SizeTmp3, Result),
3304                    tok::utf8_string_literal);
3305           }
3306         }
3307       }
3308     }
3309 
3310     // treat u like the start of an identifier.
3311     return LexIdentifier(Result, CurPtr);
3312 
3313   case 'U':   // Identifier (Uber) or C11/C++11 UTF-32 string literal
3314     // Notify MIOpt that we read a non-whitespace/non-comment token.
3315     MIOpt.ReadToken();
3316 
3317     if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3318       Char = getCharAndSize(CurPtr, SizeTmp);
3319 
3320       // UTF-32 string literal
3321       if (Char == '"')
3322         return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3323                                 tok::utf32_string_literal);
3324 
3325       // UTF-32 character constant
3326       if (Char == '\'')
3327         return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3328                                tok::utf32_char_constant);
3329 
3330       // UTF-32 raw string literal
3331       if (Char == 'R' && LangOpts.CPlusPlus11 &&
3332           getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3333         return LexRawStringLiteral(Result,
3334                                ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3335                                            SizeTmp2, Result),
3336                                tok::utf32_string_literal);
3337     }
3338 
3339     // treat U like the start of an identifier.
3340     return LexIdentifier(Result, CurPtr);
3341 
3342   case 'R': // Identifier or C++0x raw string literal
3343     // Notify MIOpt that we read a non-whitespace/non-comment token.
3344     MIOpt.ReadToken();
3345 
3346     if (LangOpts.CPlusPlus11) {
3347       Char = getCharAndSize(CurPtr, SizeTmp);
3348 
3349       if (Char == '"')
3350         return LexRawStringLiteral(Result,
3351                                    ConsumeChar(CurPtr, SizeTmp, Result),
3352                                    tok::string_literal);
3353     }
3354 
3355     // treat R like the start of an identifier.
3356     return LexIdentifier(Result, CurPtr);
3357 
3358   case 'L':   // Identifier (Loony) or wide literal (L'x' or L"xyz").
3359     // Notify MIOpt that we read a non-whitespace/non-comment token.
3360     MIOpt.ReadToken();
3361     Char = getCharAndSize(CurPtr, SizeTmp);
3362 
3363     // Wide string literal.
3364     if (Char == '"')
3365       return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3366                               tok::wide_string_literal);
3367 
3368     // Wide raw string literal.
3369     if (LangOpts.CPlusPlus11 && Char == 'R' &&
3370         getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3371       return LexRawStringLiteral(Result,
3372                                ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3373                                            SizeTmp2, Result),
3374                                tok::wide_string_literal);
3375 
3376     // Wide character constant.
3377     if (Char == '\'')
3378       return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3379                              tok::wide_char_constant);
3380     // FALL THROUGH, treating L like the start of an identifier.
3381     LLVM_FALLTHROUGH;
3382 
3383   // C99 6.4.2: Identifiers.
3384   case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3385   case 'H': case 'I': case 'J': case 'K':    /*'L'*/case 'M': case 'N':
3386   case 'O': case 'P': case 'Q':    /*'R'*/case 'S': case 'T':    /*'U'*/
3387   case 'V': case 'W': case 'X': case 'Y': case 'Z':
3388   case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3389   case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
3390   case 'o': case 'p': case 'q': case 'r': case 's': case 't':    /*'u'*/
3391   case 'v': case 'w': case 'x': case 'y': case 'z':
3392   case '_':
3393     // Notify MIOpt that we read a non-whitespace/non-comment token.
3394     MIOpt.ReadToken();
3395     return LexIdentifier(Result, CurPtr);
3396 
3397   case '$':   // $ in identifiers.
3398     if (LangOpts.DollarIdents) {
3399       if (!isLexingRawMode())
3400         Diag(CurPtr-1, diag::ext_dollar_in_identifier);
3401       // Notify MIOpt that we read a non-whitespace/non-comment token.
3402       MIOpt.ReadToken();
3403       return LexIdentifier(Result, CurPtr);
3404     }
3405 
3406     Kind = tok::unknown;
3407     break;
3408 
3409   // C99 6.4.4: Character Constants.
3410   case '\'':
3411     // Notify MIOpt that we read a non-whitespace/non-comment token.
3412     MIOpt.ReadToken();
3413     return LexCharConstant(Result, CurPtr, tok::char_constant);
3414 
3415   // C99 6.4.5: String Literals.
3416   case '"':
3417     // Notify MIOpt that we read a non-whitespace/non-comment token.
3418     MIOpt.ReadToken();
3419     return LexStringLiteral(Result, CurPtr, tok::string_literal);
3420 
3421   // C99 6.4.6: Punctuators.
3422   case '?':
3423     Kind = tok::question;
3424     break;
3425   case '[':
3426     Kind = tok::l_square;
3427     break;
3428   case ']':
3429     Kind = tok::r_square;
3430     break;
3431   case '(':
3432     Kind = tok::l_paren;
3433     break;
3434   case ')':
3435     Kind = tok::r_paren;
3436     break;
3437   case '{':
3438     Kind = tok::l_brace;
3439     break;
3440   case '}':
3441     Kind = tok::r_brace;
3442     break;
3443   case '.':
3444     Char = getCharAndSize(CurPtr, SizeTmp);
3445     if (Char >= '0' && Char <= '9') {
3446       // Notify MIOpt that we read a non-whitespace/non-comment token.
3447       MIOpt.ReadToken();
3448 
3449       return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
3450     } else if (LangOpts.CPlusPlus && Char == '*') {
3451       Kind = tok::periodstar;
3452       CurPtr += SizeTmp;
3453     } else if (Char == '.' &&
3454                getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
3455       Kind = tok::ellipsis;
3456       CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3457                            SizeTmp2, Result);
3458     } else {
3459       Kind = tok::period;
3460     }
3461     break;
3462   case '&':
3463     Char = getCharAndSize(CurPtr, SizeTmp);
3464     if (Char == '&') {
3465       Kind = tok::ampamp;
3466       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3467     } else if (Char == '=') {
3468       Kind = tok::ampequal;
3469       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3470     } else {
3471       Kind = tok::amp;
3472     }
3473     break;
3474   case '*':
3475     if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3476       Kind = tok::starequal;
3477       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3478     } else {
3479       Kind = tok::star;
3480     }
3481     break;
3482   case '+':
3483     Char = getCharAndSize(CurPtr, SizeTmp);
3484     if (Char == '+') {
3485       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3486       Kind = tok::plusplus;
3487     } else if (Char == '=') {
3488       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3489       Kind = tok::plusequal;
3490     } else {
3491       Kind = tok::plus;
3492     }
3493     break;
3494   case '-':
3495     Char = getCharAndSize(CurPtr, SizeTmp);
3496     if (Char == '-') {      // --
3497       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3498       Kind = tok::minusminus;
3499     } else if (Char == '>' && LangOpts.CPlusPlus &&
3500                getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') {  // C++ ->*
3501       CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3502                            SizeTmp2, Result);
3503       Kind = tok::arrowstar;
3504     } else if (Char == '>') {   // ->
3505       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3506       Kind = tok::arrow;
3507     } else if (Char == '=') {   // -=
3508       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3509       Kind = tok::minusequal;
3510     } else {
3511       Kind = tok::minus;
3512     }
3513     break;
3514   case '~':
3515     Kind = tok::tilde;
3516     break;
3517   case '!':
3518     if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3519       Kind = tok::exclaimequal;
3520       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3521     } else {
3522       Kind = tok::exclaim;
3523     }
3524     break;
3525   case '/':
3526     // 6.4.9: Comments
3527     Char = getCharAndSize(CurPtr, SizeTmp);
3528     if (Char == '/') {         // Line comment.
3529       // Even if Line comments are disabled (e.g. in C89 mode), we generally
3530       // want to lex this as a comment.  There is one problem with this though,
3531       // that in one particular corner case, this can change the behavior of the
3532       // resultant program.  For example, In  "foo //**/ bar", C89 would lex
3533       // this as "foo / bar" and languages with Line comments would lex it as
3534       // "foo".  Check to see if the character after the second slash is a '*'.
3535       // If so, we will lex that as a "/" instead of the start of a comment.
3536       // However, we never do this if we are just preprocessing.
3537       bool TreatAsComment = LangOpts.LineComment &&
3538                             (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
3539       if (!TreatAsComment)
3540         if (!(PP && PP->isPreprocessedOutput()))
3541           TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3542 
3543       if (TreatAsComment) {
3544         if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3545                             TokAtPhysicalStartOfLine))
3546           return true; // There is a token to return.
3547 
3548         // It is common for the tokens immediately after a // comment to be
3549         // whitespace (indentation for the next line).  Instead of going through
3550         // the big switch, handle it efficiently now.
3551         goto SkipIgnoredUnits;
3552       }
3553     }
3554 
3555     if (Char == '*') {  // /**/ comment.
3556       if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3557                            TokAtPhysicalStartOfLine))
3558         return true; // There is a token to return.
3559 
3560       // We only saw whitespace, so just try again with this lexer.
3561       // (We manually eliminate the tail call to avoid recursion.)
3562       goto LexNextToken;
3563     }
3564 
3565     if (Char == '=') {
3566       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3567       Kind = tok::slashequal;
3568     } else {
3569       Kind = tok::slash;
3570     }
3571     break;
3572   case '%':
3573     Char = getCharAndSize(CurPtr, SizeTmp);
3574     if (Char == '=') {
3575       Kind = tok::percentequal;
3576       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3577     } else if (LangOpts.Digraphs && Char == '>') {
3578       Kind = tok::r_brace;                             // '%>' -> '}'
3579       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3580     } else if (LangOpts.Digraphs && Char == ':') {
3581       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3582       Char = getCharAndSize(CurPtr, SizeTmp);
3583       if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
3584         Kind = tok::hashhash;                          // '%:%:' -> '##'
3585         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3586                              SizeTmp2, Result);
3587       } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
3588         CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3589         if (!isLexingRawMode())
3590           Diag(BufferPtr, diag::ext_charize_microsoft);
3591         Kind = tok::hashat;
3592       } else {                                         // '%:' -> '#'
3593         // We parsed a # character.  If this occurs at the start of the line,
3594         // it's actually the start of a preprocessing directive.  Callback to
3595         // the preprocessor to handle it.
3596         // TODO: -fpreprocessed mode??
3597         if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3598           goto HandleDirective;
3599 
3600         Kind = tok::hash;
3601       }
3602     } else {
3603       Kind = tok::percent;
3604     }
3605     break;
3606   case '<':
3607     Char = getCharAndSize(CurPtr, SizeTmp);
3608     if (ParsingFilename) {
3609       return LexAngledStringLiteral(Result, CurPtr);
3610     } else if (Char == '<') {
3611       char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3612       if (After == '=') {
3613         Kind = tok::lesslessequal;
3614         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3615                              SizeTmp2, Result);
3616       } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3617         // If this is actually a '<<<<<<<' version control conflict marker,
3618         // recognize it as such and recover nicely.
3619         goto LexNextToken;
3620       } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3621         // If this is '<<<<' and we're in a Perforce-style conflict marker,
3622         // ignore it.
3623         goto LexNextToken;
3624       } else if (LangOpts.CUDA && After == '<') {
3625         Kind = tok::lesslessless;
3626         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3627                              SizeTmp2, Result);
3628       } else {
3629         CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3630         Kind = tok::lessless;
3631       }
3632     } else if (Char == '=') {
3633       char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3634       if (After == '>') {
3635         if (getLangOpts().CPlusPlus2a) {
3636           if (!isLexingRawMode())
3637             Diag(BufferPtr, diag::warn_cxx17_compat_spaceship);
3638           CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3639                                SizeTmp2, Result);
3640           Kind = tok::spaceship;
3641           break;
3642         }
3643         // Suggest adding a space between the '<=' and the '>' to avoid a
3644         // change in semantics if this turns up in C++ <=17 mode.
3645         if (getLangOpts().CPlusPlus && !isLexingRawMode()) {
3646           Diag(BufferPtr, diag::warn_cxx2a_compat_spaceship)
3647             << FixItHint::CreateInsertion(
3648                    getSourceLocation(CurPtr + SizeTmp, SizeTmp2), " ");
3649         }
3650       }
3651       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3652       Kind = tok::lessequal;
3653     } else if (LangOpts.Digraphs && Char == ':') {     // '<:' -> '['
3654       if (LangOpts.CPlusPlus11 &&
3655           getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3656         // C++0x [lex.pptoken]p3:
3657         //  Otherwise, if the next three characters are <:: and the subsequent
3658         //  character is neither : nor >, the < is treated as a preprocessor
3659         //  token by itself and not as the first character of the alternative
3660         //  token <:.
3661         unsigned SizeTmp3;
3662         char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3663         if (After != ':' && After != '>') {
3664           Kind = tok::less;
3665           if (!isLexingRawMode())
3666             Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3667           break;
3668         }
3669       }
3670 
3671       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3672       Kind = tok::l_square;
3673     } else if (LangOpts.Digraphs && Char == '%') {     // '<%' -> '{'
3674       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3675       Kind = tok::l_brace;
3676     } else if (Char == '#' && /*Not a trigraph*/ SizeTmp == 1 &&
3677                lexEditorPlaceholder(Result, CurPtr)) {
3678       return true;
3679     } else {
3680       Kind = tok::less;
3681     }
3682     break;
3683   case '>':
3684     Char = getCharAndSize(CurPtr, SizeTmp);
3685     if (Char == '=') {
3686       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3687       Kind = tok::greaterequal;
3688     } else if (Char == '>') {
3689       char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3690       if (After == '=') {
3691         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3692                              SizeTmp2, Result);
3693         Kind = tok::greatergreaterequal;
3694       } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3695         // If this is actually a '>>>>' conflict marker, recognize it as such
3696         // and recover nicely.
3697         goto LexNextToken;
3698       } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3699         // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3700         goto LexNextToken;
3701       } else if (LangOpts.CUDA && After == '>') {
3702         Kind = tok::greatergreatergreater;
3703         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3704                              SizeTmp2, Result);
3705       } else {
3706         CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3707         Kind = tok::greatergreater;
3708       }
3709     } else {
3710       Kind = tok::greater;
3711     }
3712     break;
3713   case '^':
3714     Char = getCharAndSize(CurPtr, SizeTmp);
3715     if (Char == '=') {
3716       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3717       Kind = tok::caretequal;
3718     } else if (LangOpts.OpenCL && Char == '^') {
3719       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3720       Kind = tok::caretcaret;
3721     } else {
3722       Kind = tok::caret;
3723     }
3724     break;
3725   case '|':
3726     Char = getCharAndSize(CurPtr, SizeTmp);
3727     if (Char == '=') {
3728       Kind = tok::pipeequal;
3729       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3730     } else if (Char == '|') {
3731       // If this is '|||||||' and we're in a conflict marker, ignore it.
3732       if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3733         goto LexNextToken;
3734       Kind = tok::pipepipe;
3735       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3736     } else {
3737       Kind = tok::pipe;
3738     }
3739     break;
3740   case ':':
3741     Char = getCharAndSize(CurPtr, SizeTmp);
3742     if (LangOpts.Digraphs && Char == '>') {
3743       Kind = tok::r_square; // ':>' -> ']'
3744       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3745     } else if ((LangOpts.CPlusPlus ||
3746                 LangOpts.DoubleSquareBracketAttributes) &&
3747                Char == ':') {
3748       Kind = tok::coloncolon;
3749       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3750     } else {
3751       Kind = tok::colon;
3752     }
3753     break;
3754   case ';':
3755     Kind = tok::semi;
3756     break;
3757   case '=':
3758     Char = getCharAndSize(CurPtr, SizeTmp);
3759     if (Char == '=') {
3760       // If this is '====' and we're in a conflict marker, ignore it.
3761       if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3762         goto LexNextToken;
3763 
3764       Kind = tok::equalequal;
3765       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3766     } else {
3767       Kind = tok::equal;
3768     }
3769     break;
3770   case ',':
3771     Kind = tok::comma;
3772     break;
3773   case '#':
3774     Char = getCharAndSize(CurPtr, SizeTmp);
3775     if (Char == '#') {
3776       Kind = tok::hashhash;
3777       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3778     } else if (Char == '@' && LangOpts.MicrosoftExt) {  // #@ -> Charize
3779       Kind = tok::hashat;
3780       if (!isLexingRawMode())
3781         Diag(BufferPtr, diag::ext_charize_microsoft);
3782       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3783     } else {
3784       // We parsed a # character.  If this occurs at the start of the line,
3785       // it's actually the start of a preprocessing directive.  Callback to
3786       // the preprocessor to handle it.
3787       // TODO: -fpreprocessed mode??
3788       if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3789         goto HandleDirective;
3790 
3791       Kind = tok::hash;
3792     }
3793     break;
3794 
3795   case '@':
3796     // Objective C support.
3797     if (CurPtr[-1] == '@' && LangOpts.ObjC1)
3798       Kind = tok::at;
3799     else
3800       Kind = tok::unknown;
3801     break;
3802 
3803   // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
3804   case '\\':
3805     if (!LangOpts.AsmPreprocessor) {
3806       if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3807         if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3808           if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3809             return true; // KeepWhitespaceMode
3810 
3811           // We only saw whitespace, so just try again with this lexer.
3812           // (We manually eliminate the tail call to avoid recursion.)
3813           goto LexNextToken;
3814         }
3815 
3816         return LexUnicode(Result, CodePoint, CurPtr);
3817       }
3818     }
3819 
3820     Kind = tok::unknown;
3821     break;
3822 
3823   default: {
3824     if (isASCII(Char)) {
3825       Kind = tok::unknown;
3826       break;
3827     }
3828 
3829     llvm::UTF32 CodePoint;
3830 
3831     // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3832     // an escaped newline.
3833     --CurPtr;
3834     const char *UTF8StartPtr = CurPtr;
3835     llvm::ConversionResult Status =
3836         llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3837                                   (const llvm::UTF8 *)BufferEnd,
3838                                   &CodePoint,
3839                                   llvm::strictConversion);
3840     if (Status == llvm::conversionOK) {
3841       if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3842         if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3843           return true; // KeepWhitespaceMode
3844 
3845         // We only saw whitespace, so just try again with this lexer.
3846         // (We manually eliminate the tail call to avoid recursion.)
3847         goto LexNextToken;
3848       }
3849       if (!isLexingRawMode())
3850         maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), CodePoint,
3851                                    makeCharRange(*this, UTF8StartPtr, CurPtr));
3852       return LexUnicode(Result, CodePoint, CurPtr);
3853     }
3854 
3855     if (isLexingRawMode() || ParsingPreprocessorDirective ||
3856         PP->isPreprocessedOutput()) {
3857       ++CurPtr;
3858       Kind = tok::unknown;
3859       break;
3860     }
3861 
3862     // Non-ASCII characters tend to creep into source code unintentionally.
3863     // Instead of letting the parser complain about the unknown token,
3864     // just diagnose the invalid UTF-8, then drop the character.
3865     Diag(CurPtr, diag::err_invalid_utf8);
3866 
3867     BufferPtr = CurPtr+1;
3868     // We're pretending the character didn't exist, so just try again with
3869     // this lexer.
3870     // (We manually eliminate the tail call to avoid recursion.)
3871     goto LexNextToken;
3872   }
3873   }
3874 
3875   // Notify MIOpt that we read a non-whitespace/non-comment token.
3876   MIOpt.ReadToken();
3877 
3878   // Update the location of token as well as BufferPtr.
3879   FormTokenWithChars(Result, CurPtr, Kind);
3880   return true;
3881 
3882 HandleDirective:
3883   // We parsed a # character and it's the start of a preprocessing directive.
3884 
3885   FormTokenWithChars(Result, CurPtr, tok::hash);
3886   PP->HandleDirective(Result);
3887 
3888   if (PP->hadModuleLoaderFatalFailure()) {
3889     // With a fatal failure in the module loader, we abort parsing.
3890     assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
3891     return true;
3892   }
3893 
3894   // We parsed the directive; lex a token with the new state.
3895   return false;
3896 }
3897