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