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