Coverage Report

Created: 2023-09-30 09:22

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Lex/Lexer.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Lexer.cpp - C Language Family Lexer --------------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements the Lexer and Token interfaces.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Lex/Lexer.h"
14
#include "UnicodeCharSets.h"
15
#include "clang/Basic/CharInfo.h"
16
#include "clang/Basic/Diagnostic.h"
17
#include "clang/Basic/IdentifierTable.h"
18
#include "clang/Basic/LLVM.h"
19
#include "clang/Basic/LangOptions.h"
20
#include "clang/Basic/SourceLocation.h"
21
#include "clang/Basic/SourceManager.h"
22
#include "clang/Basic/TokenKinds.h"
23
#include "clang/Lex/LexDiagnostic.h"
24
#include "clang/Lex/LiteralSupport.h"
25
#include "clang/Lex/MultipleIncludeOpt.h"
26
#include "clang/Lex/Preprocessor.h"
27
#include "clang/Lex/PreprocessorOptions.h"
28
#include "clang/Lex/Token.h"
29
#include "llvm/ADT/STLExtras.h"
30
#include "llvm/ADT/StringExtras.h"
31
#include "llvm/ADT/StringRef.h"
32
#include "llvm/ADT/StringSwitch.h"
33
#include "llvm/Support/Compiler.h"
34
#include "llvm/Support/ConvertUTF.h"
35
#include "llvm/Support/MathExtras.h"
36
#include "llvm/Support/MemoryBufferRef.h"
37
#include "llvm/Support/NativeFormatting.h"
38
#include "llvm/Support/Unicode.h"
39
#include "llvm/Support/UnicodeCharRanges.h"
40
#include <algorithm>
41
#include <cassert>
42
#include <cstddef>
43
#include <cstdint>
44
#include <cstring>
45
#include <optional>
46
#include <string>
47
#include <tuple>
48
#include <utility>
49
50
using namespace clang;
51
52
//===----------------------------------------------------------------------===//
53
// Token Class Implementation
54
//===----------------------------------------------------------------------===//
55
56
/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
57
417k
bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
58
417k
  if (isAnnotation())
59
2
    return false;
60
417k
  if (IdentifierInfo *II = getIdentifierInfo())
61
395k
    return II->getObjCKeywordID() == objcKey;
62
21.7k
  return false;
63
417k
}
64
65
/// getObjCKeywordID - Return the ObjC keyword kind.
66
1.39M
tok::ObjCKeywordKind Token::getObjCKeywordID() const {
67
1.39M
  if (isAnnotation())
68
1
    return tok::objc_not_keyword;
69
1.39M
  IdentifierInfo *specId = getIdentifierInfo();
70
1.39M
  return specId ? 
specId->getObjCKeywordID()1.17M
:
tok::objc_not_keyword220k
;
71
1.39M
}
72
73
//===----------------------------------------------------------------------===//
74
// Lexer Class Implementation
75
//===----------------------------------------------------------------------===//
76
77
0
void Lexer::anchor() {}
78
79
void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
80
67.6M
                      const char *BufEnd) {
81
67.6M
  BufferStart = BufStart;
82
67.6M
  BufferPtr = BufPtr;
83
67.6M
  BufferEnd = BufEnd;
84
85
67.6M
  assert(BufEnd[0] == 0 &&
86
67.6M
         "We assume that the input buffer has a null character at the end"
87
67.6M
         " to simplify lexing!");
88
89
  // Check whether we have a BOM in the beginning of the buffer. If yes - act
90
  // accordingly. Right now we support only UTF-8 with and without BOM, so, just
91
  // skip the UTF-8 BOM if it's present.
92
67.6M
  if (BufferStart == BufferPtr) {
93
    // Determine the size of the BOM.
94
3.23M
    StringRef Buf(BufferStart, BufferEnd - BufferStart);
95
3.23M
    size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
96
3.23M
      .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
97
3.23M
      .Default(0);
98
99
    // Skip the BOM.
100
3.23M
    BufferPtr += BOMLength;
101
3.23M
  }
102
103
67.6M
  Is_PragmaLexer = false;
104
67.6M
  CurrentConflictMarkerState = CMK_None;
105
106
  // Start of the file is a start of line.
107
67.6M
  IsAtStartOfLine = true;
108
67.6M
  IsAtPhysicalStartOfLine = true;
109
110
67.6M
  HasLeadingSpace = false;
111
67.6M
  HasLeadingEmptyMacro = false;
112
113
  // We are not after parsing a #.
114
67.6M
  ParsingPreprocessorDirective = false;
115
116
  // We are not after parsing #include.
117
67.6M
  ParsingFilename = false;
118
119
  // We are not in raw mode.  Raw mode disables diagnostics and interpretation
120
  // of tokens (e.g. identifiers, thus disabling macro expansion).  It is used
121
  // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
122
  // or otherwise skipping over tokens.
123
67.6M
  LexingRawMode = false;
124
125
  // Default to not keeping comments.
126
67.6M
  ExtendedTokenMode = 0;
127
128
67.6M
  NewLinePtr = nullptr;
129
67.6M
}
130
131
/// Lexer constructor - Create a new lexer object for the specified buffer
132
/// with the specified preprocessor managing the lexing process.  This lexer
133
/// assumes that the associated file buffer and Preprocessor objects will
134
/// outlive it, so it doesn't take ownership of either of them.
135
Lexer::Lexer(FileID FID, const llvm::MemoryBufferRef &InputFile,
136
             Preprocessor &PP, bool IsFirstIncludeOfFile)
137
1.76M
    : PreprocessorLexer(&PP, FID),
138
1.76M
      FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
139
1.76M
      LangOpts(PP.getLangOpts()), LineComment(LangOpts.LineComment),
140
1.76M
      IsFirstTimeLexingFile(IsFirstIncludeOfFile) {
141
1.76M
  InitLexer(InputFile.getBufferStart(), InputFile.getBufferStart(),
142
1.76M
            InputFile.getBufferEnd());
143
144
1.76M
  resetExtendedTokenMode();
145
1.76M
}
146
147
/// Lexer constructor - Create a new raw lexer object.  This object is only
148
/// suitable for calls to 'LexFromRawLexer'.  This lexer assumes that the text
149
/// range will outlive it, so it doesn't take ownership of it.
150
Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
151
             const char *BufStart, const char *BufPtr, const char *BufEnd,
152
             bool IsFirstIncludeOfFile)
153
65.9M
    : FileLoc(fileloc), LangOpts(langOpts), LineComment(LangOpts.LineComment),
154
65.9M
      IsFirstTimeLexingFile(IsFirstIncludeOfFile) {
155
65.9M
  InitLexer(BufStart, BufPtr, BufEnd);
156
157
  // We *are* in raw mode.
158
65.9M
  LexingRawMode = true;
159
65.9M
}
160
161
/// Lexer constructor - Create a new raw lexer object.  This object is only
162
/// suitable for calls to 'LexFromRawLexer'.  This lexer assumes that the text
163
/// range will outlive it, so it doesn't take ownership of it.
164
Lexer::Lexer(FileID FID, const llvm::MemoryBufferRef &FromFile,
165
             const SourceManager &SM, const LangOptions &langOpts,
166
             bool IsFirstIncludeOfFile)
167
108k
    : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile.getBufferStart(),
168
108k
            FromFile.getBufferStart(), FromFile.getBufferEnd(),
169
108k
            IsFirstIncludeOfFile) {}
Unexecuted instantiation: clang::Lexer::Lexer(clang::FileID, llvm::MemoryBufferRef const&, clang::SourceManager const&, clang::LangOptions const&, bool)
clang::Lexer::Lexer(clang::FileID, llvm::MemoryBufferRef const&, clang::SourceManager const&, clang::LangOptions const&, bool)
Line
Count
Source
167
108k
    : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile.getBufferStart(),
168
108k
            FromFile.getBufferStart(), FromFile.getBufferEnd(),
169
108k
            IsFirstIncludeOfFile) {}
170
171
83.1M
void Lexer::resetExtendedTokenMode() {
172
83.1M
  assert(PP && "Cannot reset token mode without a preprocessor");
173
83.1M
  if (LangOpts.TraditionalCPP)
174
1.19k
    SetKeepWhitespaceMode(true);
175
83.1M
  else
176
83.1M
    SetCommentRetentionState(PP->getCommentRetentionState());
177
83.1M
}
178
179
/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
180
/// _Pragma expansion.  This has a variety of magic semantics that this method
181
/// sets up.  It returns a new'd Lexer that must be delete'd when done.
182
///
183
/// On entrance to this routine, TokStartLoc is a macro location which has a
184
/// spelling loc that indicates the bytes to be lexed for the token and an
185
/// expansion location that indicates where all lexed tokens should be
186
/// "expanded from".
187
///
188
/// TODO: It would really be nice to make _Pragma just be a wrapper around a
189
/// normal lexer that remaps tokens as they fly by.  This would require making
190
/// Preprocessor::Lex virtual.  Given that, we could just dump in a magic lexer
191
/// interface that could handle this stuff.  This would pull GetMappedTokenLoc
192
/// out of the critical path of the lexer!
193
///
194
Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
195
                                 SourceLocation ExpansionLocStart,
196
                                 SourceLocation ExpansionLocEnd,
197
699k
                                 unsigned TokLen, Preprocessor &PP) {
198
699k
  SourceManager &SM = PP.getSourceManager();
199
200
  // Create the lexer as if we were going to lex the file normally.
201
699k
  FileID SpellingFID = SM.getFileID(SpellingLoc);
202
699k
  llvm::MemoryBufferRef InputFile = SM.getBufferOrFake(SpellingFID);
203
699k
  Lexer *L = new Lexer(SpellingFID, InputFile, PP);
204
205
  // Now that the lexer is created, change the start/end locations so that we
206
  // just lex the subsection of the file that we want.  This is lexing from a
207
  // scratch buffer.
208
699k
  const char *StrData = SM.getCharacterData(SpellingLoc);
209
210
699k
  L->BufferPtr = StrData;
211
699k
  L->BufferEnd = StrData+TokLen;
212
699k
  assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
213
214
  // Set the SourceLocation with the remapping information.  This ensures that
215
  // GetMappedTokenLoc will remap the tokens as they are lexed.
216
699k
  L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
217
699k
                                     ExpansionLocStart,
218
699k
                                     ExpansionLocEnd, TokLen);
219
220
  // Ensure that the lexer thinks it is inside a directive, so that end \n will
221
  // return an EOD token.
222
699k
  L->ParsingPreprocessorDirective = true;
223
224
  // This lexer really is for _Pragma.
225
699k
  L->Is_PragmaLexer = true;
226
699k
  return L;
227
699k
}
228
229
329k
void Lexer::seek(unsigned Offset, bool IsAtStartOfLine) {
230
329k
  this->IsAtPhysicalStartOfLine = IsAtStartOfLine;
231
329k
  this->IsAtStartOfLine = IsAtStartOfLine;
232
329k
  assert((BufferStart + Offset) <= BufferEnd);
233
329k
  BufferPtr = BufferStart + Offset;
234
329k
}
235
236
2.66k
template <typename T> static void StringifyImpl(T &Str, char Quote) {
237
2.66k
  typename T::size_type i = 0, e = Str.size();
238
95.3k
  while (i < e) {
239
92.6k
    if (Str[i] == '\\' || 
Str[i] == Quote92.6k
) {
240
4.20k
      Str.insert(Str.begin() + i, '\\');
241
4.20k
      i += 2;
242
4.20k
      ++e;
243
88.4k
    } else if (Str[i] == '\n' || 
Str[i] == '\r'88.4k
) {
244
      // Replace '\r\n' and '\n\r' to '\\' followed by 'n'.
245
17
      if ((i < e - 1) && (Str[i + 1] == '\n' || 
Str[i + 1] == '\r'13
) &&
246
17
          
Str[i] != Str[i + 1]4
) {
247
0
        Str[i] = '\\';
248
0
        Str[i + 1] = 'n';
249
17
      } else {
250
        // Replace '\n' and '\r' to '\\' followed by 'n'.
251
17
        Str[i] = '\\';
252
17
        Str.insert(Str.begin() + i + 1, 'n');
253
17
        ++e;
254
17
      }
255
17
      i += 2;
256
17
    } else
257
88.4k
      ++i;
258
92.6k
  }
259
2.66k
}
Lexer.cpp:void StringifyImpl<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, char)
Line
Count
Source
236
2.13k
template <typename T> static void StringifyImpl(T &Str, char Quote) {
237
2.13k
  typename T::size_type i = 0, e = Str.size();
238
50.9k
  while (i < e) {
239
48.8k
    if (Str[i] == '\\' || 
Str[i] == Quote48.7k
) {
240
4.15k
      Str.insert(Str.begin() + i, '\\');
241
4.15k
      i += 2;
242
4.15k
      ++e;
243
44.6k
    } else if (Str[i] == '\n' || 
Str[i] == '\r'44.6k
) {
244
      // Replace '\r\n' and '\n\r' to '\\' followed by 'n'.
245
9
      if ((i < e - 1) && (Str[i + 1] == '\n' || 
Str[i + 1] == '\r'7
) &&
246
9
          
Str[i] != Str[i + 1]2
) {
247
0
        Str[i] = '\\';
248
0
        Str[i + 1] = 'n';
249
9
      } else {
250
        // Replace '\n' and '\r' to '\\' followed by 'n'.
251
9
        Str[i] = '\\';
252
9
        Str.insert(Str.begin() + i + 1, 'n');
253
9
        ++e;
254
9
      }
255
9
      i += 2;
256
9
    } else
257
44.6k
      ++i;
258
48.8k
  }
259
2.13k
}
Lexer.cpp:void StringifyImpl<llvm::SmallVectorImpl<char> >(llvm::SmallVectorImpl<char>&, char)
Line
Count
Source
236
527
template <typename T> static void StringifyImpl(T &Str, char Quote) {
237
527
  typename T::size_type i = 0, e = Str.size();
238
44.4k
  while (i < e) {
239
43.8k
    if (Str[i] == '\\' || 
Str[i] == Quote43.8k
) {
240
47
      Str.insert(Str.begin() + i, '\\');
241
47
      i += 2;
242
47
      ++e;
243
43.8k
    } else if (Str[i] == '\n' || 
Str[i] == '\r'43.8k
) {
244
      // Replace '\r\n' and '\n\r' to '\\' followed by 'n'.
245
8
      if ((i < e - 1) && (Str[i + 1] == '\n' || 
Str[i + 1] == '\r'6
) &&
246
8
          
Str[i] != Str[i + 1]2
) {
247
0
        Str[i] = '\\';
248
0
        Str[i + 1] = 'n';
249
8
      } else {
250
        // Replace '\n' and '\r' to '\\' followed by 'n'.
251
8
        Str[i] = '\\';
252
8
        Str.insert(Str.begin() + i + 1, 'n');
253
8
        ++e;
254
8
      }
255
8
      i += 2;
256
8
    } else
257
43.8k
      ++i;
258
43.8k
  }
259
527
}
260
261
2.13k
std::string Lexer::Stringify(StringRef Str, bool Charify) {
262
2.13k
  std::string Result = std::string(Str);
263
2.13k
  char Quote = Charify ? 
'\''0
: '"';
264
2.13k
  StringifyImpl(Result, Quote);
265
2.13k
  return Result;
266
2.13k
}
267
268
527
void Lexer::Stringify(SmallVectorImpl<char> &Str) { StringifyImpl(Str, '"'); }
269
270
//===----------------------------------------------------------------------===//
271
// Token Spelling
272
//===----------------------------------------------------------------------===//
273
274
/// Slow case of getSpelling. Extract the characters comprising the
275
/// spelling of this token from the provided input buffer.
276
static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
277
31.0k
                              const LangOptions &LangOpts, char *Spelling) {
278
31.0k
  assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
279
280
31.0k
  size_t Length = 0;
281
31.0k
  const char *BufEnd = BufPtr + Tok.getLength();
282
283
31.0k
  if (tok::isStringLiteral(Tok.getKind())) {
284
    // Munch the encoding-prefix and opening double-quote.
285
123
    while (BufPtr < BufEnd) {
286
123
      unsigned Size;
287
123
      Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
288
123
      BufPtr += Size;
289
290
123
      if (Spelling[Length - 1] == '"')
291
97
        break;
292
123
    }
293
294
    // Raw string literals need special handling; trigraph expansion and line
295
    // splicing do not occur within their d-char-sequence nor within their
296
    // r-char-sequence.
297
97
    if (Length >= 2 &&
298
97
        
Spelling[Length - 2] == 'R'12
&&
Spelling[Length - 1] == '"'12
) {
299
      // Search backwards from the end of the token to find the matching closing
300
      // quote.
301
12
      const char *RawEnd = BufEnd;
302
30
      do --RawEnd; while (*RawEnd != '"');
303
12
      size_t RawLength = RawEnd - BufPtr + 1;
304
305
      // Everything between the quotes is included verbatim in the spelling.
306
12
      memcpy(Spelling + Length, BufPtr, RawLength);
307
12
      Length += RawLength;
308
12
      BufPtr += RawLength;
309
310
      // The rest of the token is lexed normally.
311
12
    }
312
97
  }
313
314
341k
  while (BufPtr < BufEnd) {
315
310k
    unsigned Size;
316
310k
    Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
317
310k
    BufPtr += Size;
318
310k
  }
319
320
31.0k
  assert(Length < Tok.getLength() &&
321
31.0k
         "NeedsCleaning flag set on token that didn't need cleaning!");
322
31.0k
  return Length;
323
31.0k
}
324
325
/// getSpelling() - Return the 'spelling' of this token.  The spelling of a
326
/// token are the characters used to represent the token in the source file
327
/// after trigraph expansion and escaped-newline folding.  In particular, this
328
/// wants to get the true, uncanonicalized, spelling of things like digraphs
329
/// UCNs, etc.
330
StringRef Lexer::getSpelling(SourceLocation loc,
331
                             SmallVectorImpl<char> &buffer,
332
                             const SourceManager &SM,
333
                             const LangOptions &options,
334
1.48k
                             bool *invalid) {
335
  // Break down the source location.
336
1.48k
  std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
337
338
  // Try to the load the file buffer.
339
1.48k
  bool invalidTemp = false;
340
1.48k
  StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
341
1.48k
  if (invalidTemp) {
342
0
    if (invalid) *invalid = true;
343
0
    return {};
344
0
  }
345
346
1.48k
  const char *tokenBegin = file.data() + locInfo.second;
347
348
  // Lex from the start of the given location.
349
1.48k
  Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
350
1.48k
              file.begin(), tokenBegin, file.end());
351
1.48k
  Token token;
352
1.48k
  lexer.LexFromRawLexer(token);
353
354
1.48k
  unsigned length = token.getLength();
355
356
  // Common case:  no need for cleaning.
357
1.48k
  if (!token.needsCleaning())
358
1.48k
    return StringRef(tokenBegin, length);
359
360
  // Hard case, we need to relex the characters into the string.
361
1
  buffer.resize(length);
362
1
  buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
363
1
  return StringRef(buffer.data(), buffer.size());
364
1.48k
}
365
366
/// getSpelling() - Return the 'spelling' of this token.  The spelling of a
367
/// token are the characters used to represent the token in the source file
368
/// after trigraph expansion and escaped-newline folding.  In particular, this
369
/// wants to get the true, uncanonicalized, spelling of things like digraphs
370
/// UCNs, etc.
371
std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
372
7.83M
                               const LangOptions &LangOpts, bool *Invalid) {
373
7.83M
  assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
374
375
7.83M
  bool CharDataInvalid = false;
376
7.83M
  const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
377
7.83M
                                                    &CharDataInvalid);
378
7.83M
  if (Invalid)
379
2.07k
    *Invalid = CharDataInvalid;
380
7.83M
  if (CharDataInvalid)
381
1
    return {};
382
383
  // If this token contains nothing interesting, return it directly.
384
7.83M
  if (!Tok.needsCleaning())
385
7.83M
    return std::string(TokStart, TokStart + Tok.getLength());
386
387
7
  std::string Result;
388
7
  Result.resize(Tok.getLength());
389
7
  Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
390
7
  return Result;
391
7.83M
}
392
393
/// getSpelling - This method is used to get the spelling of a token into a
394
/// preallocated buffer, instead of as an std::string.  The caller is required
395
/// to allocate enough space for the token, which is guaranteed to be at least
396
/// Tok.getLength() bytes long.  The actual length of the token is returned.
397
///
398
/// Note that this method may do two possible things: it may either fill in
399
/// the buffer specified with characters, or it may *change the input pointer*
400
/// to point to a constant buffer with the data already in it (avoiding a
401
/// copy).  The caller is not allowed to modify the returned buffer pointer
402
/// if an internal buffer is returned.
403
unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
404
                            const SourceManager &SourceMgr,
405
50.1M
                            const LangOptions &LangOpts, bool *Invalid) {
406
50.1M
  assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
407
408
50.1M
  const char *TokStart = nullptr;
409
  // NOTE: this has to be checked *before* testing for an IdentifierInfo.
410
50.1M
  if (Tok.is(tok::raw_identifier))
411
1.00M
    TokStart = Tok.getRawIdentifier().data();
412
49.1M
  else if (!Tok.hasUCN()) {
413
49.1M
    if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
414
      // Just return the string from the identifier table, which is very quick.
415
16.3M
      Buffer = II->getNameStart();
416
16.3M
      return II->getLength();
417
16.3M
    }
418
49.1M
  }
419
420
  // NOTE: this can be checked even after testing for an IdentifierInfo.
421
33.7M
  if (Tok.isLiteral())
422
32.3M
    TokStart = Tok.getLiteralData();
423
424
33.7M
  if (!TokStart) {
425
    // Compute the start of the token in the input lexer buffer.
426
393k
    bool CharDataInvalid = false;
427
393k
    TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
428
393k
    if (Invalid)
429
105k
      *Invalid = CharDataInvalid;
430
393k
    if (CharDataInvalid) {
431
2
      Buffer = "";
432
2
      return 0;
433
2
    }
434
393k
  }
435
436
  // If this token contains nothing interesting, return it directly.
437
33.7M
  if (!Tok.needsCleaning()) {
438
33.6M
    Buffer = TokStart;
439
33.6M
    return Tok.getLength();
440
33.6M
  }
441
442
  // Otherwise, hard case, relex the characters into the string.
443
31.0k
  return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
444
33.7M
}
445
446
/// MeasureTokenLength - Relex the token at the specified location and return
447
/// its length in bytes in the input file.  If the token needs cleaning (e.g.
448
/// includes a trigraph or an escaped newline) then this count includes bytes
449
/// that are part of that.
450
unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
451
                                   const SourceManager &SM,
452
62.5M
                                   const LangOptions &LangOpts) {
453
62.5M
  Token TheTok;
454
62.5M
  if (getRawToken(Loc, TheTok, SM, LangOpts))
455
1.86k
    return 0;
456
62.5M
  return TheTok.getLength();
457
62.5M
}
458
459
/// Relex the token at the specified location.
460
/// \returns true if there was a failure, false on success.
461
bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
462
                        const SourceManager &SM,
463
                        const LangOptions &LangOpts,
464
62.5M
                        bool IgnoreWhiteSpace) {
465
  // TODO: this could be special cased for common tokens like identifiers, ')',
466
  // etc to make this faster, if it mattered.  Just look at StrData[0] to handle
467
  // all obviously single-char tokens.  This could use
468
  // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
469
  // something.
470
471
  // If this comes from a macro expansion, we really do want the macro name, not
472
  // the token this macro expanded to.
473
62.5M
  Loc = SM.getExpansionLoc(Loc);
474
62.5M
  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
475
62.5M
  bool Invalid = false;
476
62.5M
  StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
477
62.5M
  if (Invalid)
478
16
    return true;
479
480
62.5M
  const char *StrData = Buffer.data()+LocInfo.second;
481
482
62.5M
  if (!IgnoreWhiteSpace && 
isWhitespace(StrData[0])62.5M
)
483
1.85k
    return true;
484
485
  // Create a lexer starting at the beginning of this token.
486
62.5M
  Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
487
62.5M
                 Buffer.begin(), StrData, Buffer.end());
488
62.5M
  TheLexer.SetCommentRetentionState(true);
489
62.5M
  TheLexer.LexFromRawLexer(Result);
490
62.5M
  return false;
491
62.5M
}
492
493
/// Returns the pointer that points to the beginning of line that contains
494
/// the given offset, or null if the offset if invalid.
495
12.4k
static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
496
12.4k
  const char *BufStart = Buffer.data();
497
12.4k
  if (Offset >= Buffer.size())
498
6
    return nullptr;
499
500
12.4k
  const char *LexStart = BufStart + Offset;
501
291k
  for (; LexStart != BufStart; 
--LexStart278k
) {
502
290k
    if (isVerticalWhitespace(LexStart[0]) &&
503
290k
        
!Lexer::isNewLineEscaped(BufStart, LexStart)12.1k
) {
504
      // LexStart should point at first character of logical line.
505
12.0k
      ++LexStart;
506
12.0k
      break;
507
12.0k
    }
508
290k
  }
509
12.4k
  return LexStart;
510
12.4k
}
511
512
static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
513
                                              const SourceManager &SM,
514
10.6k
                                              const LangOptions &LangOpts) {
515
10.6k
  assert(Loc.isFileID());
516
10.6k
  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
517
10.6k
  if (LocInfo.first.isInvalid())
518
0
    return Loc;
519
520
10.6k
  bool Invalid = false;
521
10.6k
  StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
522
10.6k
  if (Invalid)
523
0
    return Loc;
524
525
  // Back up from the current location until we hit the beginning of a line
526
  // (or the buffer). We'll relex from that point.
527
10.6k
  const char *StrData = Buffer.data() + LocInfo.second;
528
10.6k
  const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
529
10.6k
  if (!LexStart || 
LexStart == StrData10.5k
)
530
255
    return Loc;
531
532
  // Create a lexer starting at the beginning of this token.
533
10.3k
  SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
534
10.3k
  Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
535
10.3k
                 Buffer.end());
536
10.3k
  TheLexer.SetCommentRetentionState(true);
537
538
  // Lex tokens until we find the token that contains the source location.
539
10.3k
  Token TheTok;
540
16.8k
  do {
541
16.8k
    TheLexer.LexFromRawLexer(TheTok);
542
543
16.8k
    if (TheLexer.getBufferLocation() > StrData) {
544
      // Lexing this token has taken the lexer past the source location we're
545
      // looking for. If the current token encompasses our source location,
546
      // return the beginning of that token.
547
10.3k
      if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
548
9.85k
        return TheTok.getLocation();
549
550
      // We ended up skipping over the source location entirely, which means
551
      // that it points into whitespace. We're done here.
552
493
      break;
553
10.3k
    }
554
16.8k
  } while (
TheTok.getKind() != tok::eof6.53k
);
555
556
  // We've passed our source location; just return the original source location.
557
493
  return Loc;
558
10.3k
}
559
560
SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
561
                                          const SourceManager &SM,
562
10.6k
                                          const LangOptions &LangOpts) {
563
10.6k
  if (Loc.isFileID())
564
10.5k
    return getBeginningOfFileToken(Loc, SM, LangOpts);
565
566
20
  if (!SM.isMacroArgExpansion(Loc))
567
0
    return Loc;
568
569
20
  SourceLocation FileLoc = SM.getSpellingLoc(Loc);
570
20
  SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
571
20
  std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
572
20
  std::pair<FileID, unsigned> BeginFileLocInfo =
573
20
      SM.getDecomposedLoc(BeginFileLoc);
574
20
  assert(FileLocInfo.first == BeginFileLocInfo.first &&
575
20
         FileLocInfo.second >= BeginFileLocInfo.second);
576
20
  return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
577
20
}
578
579
namespace {
580
581
enum PreambleDirectiveKind {
582
  PDK_Skipped,
583
  PDK_Unknown
584
};
585
586
} // namespace
587
588
PreambleBounds Lexer::ComputePreamble(StringRef Buffer,
589
                                      const LangOptions &LangOpts,
590
543
                                      unsigned MaxLines) {
591
  // Create a lexer starting at the beginning of the file. Note that we use a
592
  // "fake" file source location at offset 1 so that the lexer will track our
593
  // position within the file.
594
543
  const SourceLocation::UIntTy StartOffset = 1;
595
543
  SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
596
543
  Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
597
543
                 Buffer.end());
598
543
  TheLexer.SetCommentRetentionState(true);
599
600
543
  bool InPreprocessorDirective = false;
601
543
  Token TheTok;
602
543
  SourceLocation ActiveCommentLoc;
603
604
543
  unsigned MaxLineOffset = 0;
605
543
  if (MaxLines) {
606
84
    const char *CurPtr = Buffer.begin();
607
84
    unsigned CurLine = 0;
608
12.3k
    while (CurPtr != Buffer.end()) {
609
12.3k
      char ch = *CurPtr++;
610
12.3k
      if (ch == '\n') {
611
642
        ++CurLine;
612
642
        if (CurLine == MaxLines)
613
83
          break;
614
642
      }
615
12.3k
    }
616
84
    if (CurPtr != Buffer.end())
617
78
      MaxLineOffset = CurPtr - Buffer.begin();
618
84
  }
619
620
4.03k
  do {
621
4.03k
    TheLexer.LexFromRawLexer(TheTok);
622
623
4.03k
    if (InPreprocessorDirective) {
624
      // If we've hit the end of the file, we're done.
625
2.87k
      if (TheTok.getKind() == tok::eof) {
626
15
        break;
627
15
      }
628
629
      // If we haven't hit the end of the preprocessor directive, skip this
630
      // token.
631
2.86k
      if (!TheTok.isAtStartOfLine())
632
1.93k
        continue;
633
634
      // We've passed the end of the preprocessor directive, and will look
635
      // at this token again below.
636
931
      InPreprocessorDirective = false;
637
931
    }
638
639
    // Keep track of the # of lines in the preamble.
640
2.08k
    if (TheTok.isAtStartOfLine()) {
641
2.06k
      unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
642
643
      // If we were asked to limit the number of lines in the preamble,
644
      // and we're about to exceed that limit, we're done.
645
2.06k
      if (MaxLineOffset && 
TokOffset >= MaxLineOffset360
)
646
18
        break;
647
2.06k
    }
648
649
    // Comments are okay; skip over them.
650
2.06k
    if (TheTok.getKind() == tok::comment) {
651
612
      if (ActiveCommentLoc.isInvalid())
652
235
        ActiveCommentLoc = TheTok.getLocation();
653
612
      continue;
654
612
    }
655
656
1.45k
    if (TheTok.isAtStartOfLine() && 
TheTok.getKind() == tok::hash1.43k
) {
657
      // This is the start of a preprocessor directive.
658
946
      Token HashTok = TheTok;
659
946
      InPreprocessorDirective = true;
660
946
      ActiveCommentLoc = SourceLocation();
661
662
      // Figure out which directive this is. Since we're lexing raw tokens,
663
      // we don't have an identifier table available. Instead, just look at
664
      // the raw identifier to recognize and categorize preprocessor directives.
665
946
      TheLexer.LexFromRawLexer(TheTok);
666
946
      if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
667
946
        StringRef Keyword = TheTok.getRawIdentifier();
668
946
        PreambleDirectiveKind PDK
669
946
          = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
670
946
              .Case("include", PDK_Skipped)
671
946
              .Case("__include_macros", PDK_Skipped)
672
946
              .Case("define", PDK_Skipped)
673
946
              .Case("undef", PDK_Skipped)
674
946
              .Case("line", PDK_Skipped)
675
946
              .Case("error", PDK_Skipped)
676
946
              .Case("pragma", PDK_Skipped)
677
946
              .Case("import", PDK_Skipped)
678
946
              .Case("include_next", PDK_Skipped)
679
946
              .Case("warning", PDK_Skipped)
680
946
              .Case("ident", PDK_Skipped)
681
946
              .Case("sccs", PDK_Skipped)
682
946
              .Case("assert", PDK_Skipped)
683
946
              .Case("unassert", PDK_Skipped)
684
946
              .Case("if", PDK_Skipped)
685
946
              .Case("ifdef", PDK_Skipped)
686
946
              .Case("ifndef", PDK_Skipped)
687
946
              .Case("elif", PDK_Skipped)
688
946
              .Case("elifdef", PDK_Skipped)
689
946
              .Case("elifndef", PDK_Skipped)
690
946
              .Case("else", PDK_Skipped)
691
946
              .Case("endif", PDK_Skipped)
692
946
              .Default(PDK_Unknown);
693
694
946
        switch (PDK) {
695
946
        case PDK_Skipped:
696
946
          continue;
697
698
0
        case PDK_Unknown:
699
          // We don't know what this directive is; stop at the '#'.
700
0
          break;
701
946
        }
702
946
      }
703
704
      // We only end up here if we didn't recognize the preprocessor
705
      // directive or it was one that can't occur in the preamble at this
706
      // point. Roll back the current token to the location of the '#'.
707
0
      TheTok = HashTok;
708
511
    } else if (TheTok.isAtStartOfLine() &&
709
511
               
TheTok.getKind() == tok::raw_identifier491
&&
710
511
               
TheTok.getRawIdentifier() == "module"478
&&
711
511
               
LangOpts.CPlusPlusModules2
) {
712
      // The initial global module fragment introducer "module;" is part of
713
      // the preamble, which runs up to the module declaration "module foo;".
714
2
      Token ModuleTok = TheTok;
715
2
      do {
716
2
        TheLexer.LexFromRawLexer(TheTok);
717
2
      } while (TheTok.getKind() == tok::comment);
718
2
      if (TheTok.getKind() != tok::semi) {
719
        // Not global module fragment, roll back.
720
1
        TheTok = ModuleTok;
721
1
        break;
722
1
      }
723
1
      continue;
724
2
    }
725
726
    // We hit a token that we don't recognize as being in the
727
    // "preprocessing only" part of the file, so we're no longer in
728
    // the preamble.
729
509
    break;
730
3.49k
  } while (true);
731
732
543
  SourceLocation End;
733
543
  if (ActiveCommentLoc.isValid())
734
81
    End = ActiveCommentLoc; // don't truncate a decl comment.
735
462
  else
736
462
    End = TheTok.getLocation();
737
738
543
  return PreambleBounds(End.getRawEncoding() - FileLoc.getRawEncoding(),
739
543
                        TheTok.isAtStartOfLine());
740
543
}
741
742
unsigned Lexer::getTokenPrefixLength(SourceLocation TokStart, unsigned CharNo,
743
                                     const SourceManager &SM,
744
96.8k
                                     const LangOptions &LangOpts) {
745
  // Figure out how many physical characters away the specified expansion
746
  // character is.  This needs to take into consideration newlines and
747
  // trigraphs.
748
96.8k
  bool Invalid = false;
749
96.8k
  const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
750
751
  // If they request the first char of the token, we're trivially done.
752
96.8k
  if (Invalid || (CharNo == 0 && 
Lexer::isObviouslySimpleCharacter(*TokPtr)3.58k
))
753
3.56k
    return 0;
754
755
93.2k
  unsigned PhysOffset = 0;
756
757
  // The usual case is that tokens don't contain anything interesting.  Skip
758
  // over the uninteresting characters.  If a token only consists of simple
759
  // chars, this method is extremely fast.
760
653k
  while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
761
649k
    if (CharNo == 0)
762
89.4k
      return PhysOffset;
763
560k
    ++TokPtr;
764
560k
    --CharNo;
765
560k
    ++PhysOffset;
766
560k
  }
767
768
  // If we have a character that may be a trigraph or escaped newline, use a
769
  // lexer to parse it correctly.
770
20.1k
  
for (; 3.86k
CharNo;
--CharNo16.2k
) {
771
16.2k
    unsigned Size;
772
16.2k
    Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
773
16.2k
    TokPtr += Size;
774
16.2k
    PhysOffset += Size;
775
16.2k
  }
776
777
  // Final detail: if we end up on an escaped newline, we want to return the
778
  // location of the actual byte of the token.  For example foo\<newline>bar
779
  // advanced by 3 should return the location of b, not of \\.  One compounding
780
  // detail of this is that the escape may be made by a trigraph.
781
3.86k
  if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
782
2.53k
    PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
783
784
3.86k
  return PhysOffset;
785
93.2k
}
786
787
/// Computes the source location just past the end of the
788
/// token at this source location.
789
///
790
/// This routine can be used to produce a source location that
791
/// points just past the end of the token referenced by \p Loc, and
792
/// is generally used when a diagnostic needs to point just after a
793
/// token where it expected something different that it received. If
794
/// the returned source location would not be meaningful (e.g., if
795
/// it points into a macro), this routine returns an invalid
796
/// source location.
797
///
798
/// \param Offset an offset from the end of the token, where the source
799
/// location should refer to. The default offset (0) produces a source
800
/// location pointing just past the end of the token; an offset of 1 produces
801
/// a source location pointing to the last character in the token, etc.
802
SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
803
                                          const SourceManager &SM,
804
4.56M
                                          const LangOptions &LangOpts) {
805
4.56M
  if (Loc.isInvalid())
806
109
    return {};
807
808
4.56M
  if (Loc.isMacroID()) {
809
595
    if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
810
205
      return {}; // Points inside the macro expansion.
811
595
  }
812
813
4.56M
  unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
814
4.56M
  if (Len > Offset)
815
4.56M
    Len = Len - Offset;
816
672
  else
817
672
    return Loc;
818
819
4.56M
  return Loc.getLocWithOffset(Len);
820
4.56M
}
821
822
/// Returns true if the given MacroID location points at the first
823
/// token of the macro expansion.
824
bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
825
                                      const SourceManager &SM,
826
                                      const LangOptions &LangOpts,
827
62.1M
                                      SourceLocation *MacroBegin) {
828
62.1M
  assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
829
830
62.1M
  SourceLocation expansionLoc;
831
62.1M
  if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
832
32.2M
    return false;
833
834
29.9M
  if (expansionLoc.isFileID()) {
835
    // No other macro expansions, this is the first.
836
7.71M
    if (MacroBegin)
837
368
      *MacroBegin = expansionLoc;
838
7.71M
    return true;
839
7.71M
  }
840
841
22.2M
  return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
842
29.9M
}
843
844
/// Returns true if the given MacroID location points at the last
845
/// token of the macro expansion.
846
bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
847
                                    const SourceManager &SM,
848
                                    const LangOptions &LangOpts,
849
57.5M
                                    SourceLocation *MacroEnd) {
850
57.5M
  assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
851
852
57.5M
  SourceLocation spellLoc = SM.getSpellingLoc(loc);
853
57.5M
  unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
854
57.5M
  if (tokLen == 0)
855
0
    return false;
856
857
57.5M
  SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
858
57.5M
  SourceLocation expansionLoc;
859
57.5M
  if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
860
7.25M
    return false;
861
862
50.3M
  if (expansionLoc.isFileID()) {
863
    // No other macro expansions.
864
32.6M
    if (MacroEnd)
865
482
      *MacroEnd = expansionLoc;
866
32.6M
    return true;
867
32.6M
  }
868
869
17.6M
  return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
870
50.3M
}
871
872
static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
873
                                             const SourceManager &SM,
874
4.42M
                                             const LangOptions &LangOpts) {
875
4.42M
  SourceLocation Begin = Range.getBegin();
876
4.42M
  SourceLocation End = Range.getEnd();
877
4.42M
  assert(Begin.isFileID() && End.isFileID());
878
4.42M
  if (Range.isTokenRange()) {
879
4.42M
    End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
880
4.42M
    if (End.isInvalid())
881
0
      return {};
882
4.42M
  }
883
884
  // Break down the source locations.
885
4.42M
  FileID FID;
886
4.42M
  unsigned BeginOffs;
887
4.42M
  std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
888
4.42M
  if (FID.isInvalid())
889
0
    return {};
890
891
4.42M
  unsigned EndOffs;
892
4.42M
  if (!SM.isInFileID(End, FID, &EndOffs) ||
893
4.42M
      BeginOffs > EndOffs)
894
0
    return {};
895
896
4.42M
  return CharSourceRange::getCharRange(Begin, End);
897
4.42M
}
898
899
// Assumes that `Loc` is in an expansion.
900
static bool isInExpansionTokenRange(const SourceLocation Loc,
901
88
                                    const SourceManager &SM) {
902
88
  return SM.getSLocEntry(SM.getFileID(Loc))
903
88
      .getExpansion()
904
88
      .isExpansionTokenRange();
905
88
}
906
907
CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
908
                                         const SourceManager &SM,
909
4.42M
                                         const LangOptions &LangOpts) {
910
4.42M
  SourceLocation Begin = Range.getBegin();
911
4.42M
  SourceLocation End = Range.getEnd();
912
4.42M
  if (Begin.isInvalid() || 
End.isInvalid()4.42M
)
913
8
    return {};
914
915
4.42M
  if (Begin.isFileID() && 
End.isFileID()4.42M
)
916
4.42M
    return makeRangeFromFileLocs(Range, SM, LangOpts);
917
918
470
  if (Begin.isMacroID() && 
End.isFileID()462
) {
919
245
    if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
920
1
      return {};
921
244
    Range.setBegin(Begin);
922
244
    return makeRangeFromFileLocs(Range, SM, LangOpts);
923
245
  }
924
925
225
  if (Begin.isFileID() && 
End.isMacroID()8
) {
926
8
    if (Range.isTokenRange()) {
927
8
      if (!isAtEndOfMacroExpansion(End, SM, LangOpts, &End))
928
0
        return {};
929
      // Use the *original* end, not the expanded one in `End`.
930
8
      Range.setTokenRange(isInExpansionTokenRange(Range.getEnd(), SM));
931
8
    } else 
if (0
!isAtStartOfMacroExpansion(End, SM, LangOpts, &End)0
)
932
0
      return {};
933
8
    Range.setEnd(End);
934
8
    return makeRangeFromFileLocs(Range, SM, LangOpts);
935
8
  }
936
937
217
  assert(Begin.isMacroID() && End.isMacroID());
938
217
  SourceLocation MacroBegin, MacroEnd;
939
217
  if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
940
217
      
(100
(100
Range.isTokenRange()100
&& isAtEndOfMacroExpansion(End, SM, LangOpts,
941
98
                                                        &MacroEnd)) ||
942
100
       
(20
Range.isCharRange()20
&& isAtStartOfMacroExpansion(End, SM, LangOpts,
943
80
                                                         &MacroEnd)))) {
944
80
    Range.setBegin(MacroBegin);
945
80
    Range.setEnd(MacroEnd);
946
    // Use the *original* `End`, not the expanded one in `MacroEnd`.
947
80
    if (Range.isTokenRange())
948
80
      Range.setTokenRange(isInExpansionTokenRange(End, SM));
949
80
    return makeRangeFromFileLocs(Range, SM, LangOpts);
950
80
  }
951
952
137
  bool Invalid = false;
953
137
  const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
954
137
                                                        &Invalid);
955
137
  if (Invalid)
956
0
    return {};
957
958
137
  if (BeginEntry.getExpansion().isMacroArgExpansion()) {
959
116
    const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
960
116
                                                        &Invalid);
961
116
    if (Invalid)
962
0
      return {};
963
964
116
    if (EndEntry.getExpansion().isMacroArgExpansion() &&
965
116
        BeginEntry.getExpansion().getExpansionLocStart() ==
966
115
            EndEntry.getExpansion().getExpansionLocStart()) {
967
114
      Range.setBegin(SM.getImmediateSpellingLoc(Begin));
968
114
      Range.setEnd(SM.getImmediateSpellingLoc(End));
969
114
      return makeFileCharRange(Range, SM, LangOpts);
970
114
    }
971
116
  }
972
973
23
  return {};
974
137
}
975
976
StringRef Lexer::getSourceText(CharSourceRange Range,
977
                               const SourceManager &SM,
978
                               const LangOptions &LangOpts,
979
4.41M
                               bool *Invalid) {
980
4.41M
  Range = makeFileCharRange(Range, SM, LangOpts);
981
4.41M
  if (Range.isInvalid()) {
982
9
    if (Invalid) 
*Invalid = true2
;
983
9
    return {};
984
9
  }
985
986
  // Break down the source location.
987
4.41M
  std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
988
4.41M
  if (beginInfo.first.isInvalid()) {
989
0
    if (Invalid) *Invalid = true;
990
0
    return {};
991
0
  }
992
993
4.41M
  unsigned EndOffs;
994
4.41M
  if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
995
4.41M
      beginInfo.second > EndOffs) {
996
0
    if (Invalid) *Invalid = true;
997
0
    return {};
998
0
  }
999
1000
  // Try to the load the file buffer.
1001
4.41M
  bool invalidTemp = false;
1002
4.41M
  StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
1003
4.41M
  if (invalidTemp) {
1004
0
    if (Invalid) *Invalid = true;
1005
0
    return {};
1006
0
  }
1007
1008
4.41M
  if (Invalid) 
*Invalid = false1.43k
;
1009
4.41M
  return file.substr(beginInfo.second, EndOffs - beginInfo.second);
1010
4.41M
}
1011
1012
StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
1013
                                       const SourceManager &SM,
1014
7.23k
                                       const LangOptions &LangOpts) {
1015
7.23k
  assert(Loc.isMacroID() && "Only reasonable to call this on macros");
1016
1017
  // Find the location of the immediate macro expansion.
1018
21.5k
  
while (7.23k
true) {
1019
21.5k
    FileID FID = SM.getFileID(Loc);
1020
21.5k
    const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
1021
21.5k
    const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
1022
21.5k
    Loc = Expansion.getExpansionLocStart();
1023
21.5k
    if (!Expansion.isMacroArgExpansion())
1024
4.62k
      break;
1025
1026
    // For macro arguments we need to check that the argument did not come
1027
    // from an inner macro, e.g: "MAC1( MAC2(foo) )"
1028
1029
    // Loc points to the argument id of the macro definition, move to the
1030
    // macro expansion.
1031
16.9k
    Loc = SM.getImmediateExpansionRange(Loc).getBegin();
1032
16.9k
    SourceLocation SpellLoc = Expansion.getSpellingLoc();
1033
16.9k
    if (SpellLoc.isFileID())
1034
2.61k
      break; // No inner macro.
1035
1036
    // If spelling location resides in the same FileID as macro expansion
1037
    // location, it means there is no inner macro.
1038
14.3k
    FileID MacroFID = SM.getFileID(Loc);
1039
14.3k
    if (SM.isInFileID(SpellLoc, MacroFID))
1040
1
      break;
1041
1042
    // Argument came from inner macro.
1043
14.3k
    Loc = SpellLoc;
1044
14.3k
  }
1045
1046
  // Find the spelling location of the start of the non-argument expansion
1047
  // range. This is where the macro name was spelled in order to begin
1048
  // expanding this macro.
1049
7.23k
  Loc = SM.getSpellingLoc(Loc);
1050
1051
  // Dig out the buffer where the macro name was spelled and the extents of the
1052
  // name so that we can render it into the expansion note.
1053
7.23k
  std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1054
7.23k
  unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1055
7.23k
  StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1056
7.23k
  return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1057
7.23k
}
1058
1059
StringRef Lexer::getImmediateMacroNameForDiagnostics(
1060
1.29k
    SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1061
1.29k
  assert(Loc.isMacroID() && "Only reasonable to call this on macros");
1062
  // Walk past macro argument expansions.
1063
1.95k
  
while (1.29k
SM.isMacroArgExpansion(Loc))
1064
660
    Loc = SM.getImmediateExpansionRange(Loc).getBegin();
1065
1066
  // If the macro's spelling isn't FileID or from scratch space, then it's
1067
  // actually a token paste or stringization (or similar) and not a macro at
1068
  // all.
1069
1.29k
  SourceLocation SpellLoc = SM.getSpellingLoc(Loc);
1070
1.29k
  if (!SpellLoc.isFileID() || SM.isWrittenInScratchSpace(SpellLoc))
1071
24
    return {};
1072
1073
  // Find the spelling location of the start of the non-argument expansion
1074
  // range. This is where the macro name was spelled in order to begin
1075
  // expanding this macro.
1076
1.27k
  Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).getBegin());
1077
1078
  // Dig out the buffer where the macro name was spelled and the extents of the
1079
  // name so that we can render it into the expansion note.
1080
1.27k
  std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1081
1.27k
  unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1082
1.27k
  StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1083
1.27k
  return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1084
1.29k
}
1085
1086
1.44k
bool Lexer::isAsciiIdentifierContinueChar(char c, const LangOptions &LangOpts) {
1087
1.44k
  return isAsciiIdentifierContinue(c, LangOpts.DollarIdents);
1088
1.44k
}
1089
1090
12.1k
bool Lexer::isNewLineEscaped(const char *BufferStart, const char *Str) {
1091
12.1k
  assert(isVerticalWhitespace(Str[0]));
1092
12.1k
  if (Str - 1 < BufferStart)
1093
2
    return false;
1094
1095
12.1k
  if ((Str[0] == '\n' && 
Str[-1] == '\r'12.1k
) ||
1096
12.1k
      
(12.1k
Str[0] == '\r'12.1k
&&
Str[-1] == '\n'18
)) {
1097
18
    if (Str - 2 < BufferStart)
1098
2
      return false;
1099
16
    --Str;
1100
16
  }
1101
12.1k
  --Str;
1102
1103
  // Rewind to first non-space character:
1104
12.2k
  while (Str > BufferStart && 
isHorizontalWhitespace(*Str)12.2k
)
1105
106
    --Str;
1106
1107
12.1k
  return *Str == '\\';
1108
12.1k
}
1109
1110
StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1111
1.83k
                                       const SourceManager &SM) {
1112
1.83k
  if (Loc.isInvalid() || Loc.isMacroID())
1113
0
    return {};
1114
1.83k
  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1115
1.83k
  if (LocInfo.first.isInvalid())
1116
0
    return {};
1117
1.83k
  bool Invalid = false;
1118
1.83k
  StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1119
1.83k
  if (Invalid)
1120
0
    return {};
1121
1.83k
  const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1122
1.83k
  if (!Line)
1123
0
    return {};
1124
1.83k
  StringRef Rest = Buffer.substr(Line - Buffer.data());
1125
1.83k
  size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1126
1.83k
  return NumWhitespaceChars == StringRef::npos
1127
1.83k
             ? 
""0
1128
1.83k
             : Rest.take_front(NumWhitespaceChars);
1129
1.83k
}
1130
1131
//===----------------------------------------------------------------------===//
1132
// Diagnostics forwarding code.
1133
//===----------------------------------------------------------------------===//
1134
1135
/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1136
/// lexer buffer was all expanded at a single point, perform the mapping.
1137
/// This is currently only used for _Pragma implementation, so it is the slow
1138
/// path of the hot getSourceLocation method.  Do not allow it to be inlined.
1139
static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1140
    Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1141
static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1142
                                        SourceLocation FileLoc,
1143
3.28M
                                        unsigned CharNo, unsigned TokLen) {
1144
3.28M
  assert(FileLoc.isMacroID() && "Must be a macro expansion");
1145
1146
  // Otherwise, we're lexing "mapped tokens".  This is used for things like
1147
  // _Pragma handling.  Combine the expansion location of FileLoc with the
1148
  // spelling location.
1149
3.28M
  SourceManager &SM = PP.getSourceManager();
1150
1151
  // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1152
  // characters come from spelling(FileLoc)+Offset.
1153
3.28M
  SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1154
3.28M
  SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1155
1156
  // Figure out the expansion loc range, which is the range covered by the
1157
  // original _Pragma(...) sequence.
1158
3.28M
  CharSourceRange II = SM.getImmediateExpansionRange(FileLoc);
1159
1160
3.28M
  return SM.createExpansionLoc(SpellingLoc, II.getBegin(), II.getEnd(), TokLen);
1161
3.28M
}
1162
1163
/// getSourceLocation - Return a source location identifier for the specified
1164
/// offset in the current file.
1165
SourceLocation Lexer::getSourceLocation(const char *Loc,
1166
1.77G
                                        unsigned TokLen) const {
1167
1.77G
  assert(Loc >= BufferStart && Loc <= BufferEnd &&
1168
1.77G
         "Location out of range for this buffer!");
1169
1170
  // In the normal case, we're just lexing from a simple file buffer, return
1171
  // the file id from FileLoc with the offset specified.
1172
1.77G
  unsigned CharNo = Loc-BufferStart;
1173
1.77G
  if (FileLoc.isFileID())
1174
1.76G
    return FileLoc.getLocWithOffset(CharNo);
1175
1176
  // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1177
  // tokens are lexed from where the _Pragma was defined.
1178
3.28M
  assert(PP && "This doesn't work on raw lexers");
1179
3.28M
  return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1180
3.28M
}
1181
1182
/// Diag - Forwarding function for diagnostics.  This translate a source
1183
/// position in the current buffer into a SourceLocation object for rendering.
1184
130k
DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1185
130k
  return PP->Diag(getSourceLocation(Loc), DiagID);
1186
130k
}
1187
1188
//===----------------------------------------------------------------------===//
1189
// Trigraph and Escaped Newline Handling Code.
1190
//===----------------------------------------------------------------------===//
1191
1192
/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1193
/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1194
430
static char GetTrigraphCharForLetter(char Letter) {
1195
430
  switch (Letter) {
1196
180
  default:   return 0;
1197
34
  case '=':  return '#';
1198
44
  case ')':  return ']';
1199
40
  case '(':  return '[';
1200
7
  case '!':  return '|';
1201
1
  case '\'': return '^';
1202
59
  case '>':  return '}';
1203
34
  case '/':  return '\\';
1204
28
  case '<':  return '{';
1205
3
  case '-':  return '~';
1206
430
  }
1207
430
}
1208
1209
/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1210
/// prefixed with ??, emit a trigraph warning.  If trigraphs are enabled,
1211
/// return the result character.  Finally, emit a warning about trigraph use
1212
/// whether trigraphs are enabled or not.
1213
385
static char DecodeTrigraphChar(const char *CP, Lexer *L, bool Trigraphs) {
1214
385
  char Res = GetTrigraphCharForLetter(*CP);
1215
385
  if (!Res)
1216
180
    return Res;
1217
1218
205
  if (!Trigraphs) {
1219
73
    if (L && 
!L->isLexingRawMode()63
)
1220
28
      L->Diag(CP-2, diag::trigraph_ignored);
1221
73
    return 0;
1222
73
  }
1223
1224
132
  if (L && 
!L->isLexingRawMode()89
)
1225
71
    L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1226
132
  return Res;
1227
205
}
1228
1229
/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1230
/// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1231
/// trigraph equivalent on entry to this function.
1232
7.41M
unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1233
7.41M
  unsigned Size = 0;
1234
7.41M
  while (isWhitespace(Ptr[Size])) {
1235
7.41M
    ++Size;
1236
1237
7.41M
    if (Ptr[Size-1] != '\n' && 
Ptr[Size-1] != '\r'447
)
1238
239
      continue;
1239
1240
    // If this is a \r\n or \n\r, skip the other half.
1241
7.41M
    if ((Ptr[Size] == '\r' || 
Ptr[Size] == '\n'7.41M
) &&
1242
7.41M
        
Ptr[Size-1] != Ptr[Size]279
)
1243
200
      ++Size;
1244
1245
7.41M
    return Size;
1246
7.41M
  }
1247
1248
  // Not an escaped newline, must be a \t or something else.
1249
2.54k
  return 0;
1250
7.41M
}
1251
1252
/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1253
/// them), skip over them and return the first non-escaped-newline found,
1254
/// otherwise return P.
1255
2.53k
const char *Lexer::SkipEscapedNewLines(const char *P) {
1256
2.55k
  while (true) {
1257
2.55k
    const char *AfterEscape;
1258
2.55k
    if (*P == '\\') {
1259
2.53k
      AfterEscape = P+1;
1260
2.53k
    } else 
if (23
*P == '?'23
) {
1261
      // If not a trigraph for escape, bail out.
1262
1
      if (P[1] != '?' || 
P[2] != '/'0
)
1263
1
        return P;
1264
      // FIXME: Take LangOpts into account; the language might not
1265
      // support trigraphs.
1266
0
      AfterEscape = P+3;
1267
22
    } else {
1268
22
      return P;
1269
22
    }
1270
1271
2.53k
    unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1272
2.53k
    if (NewLineSize == 0) 
return P2.51k
;
1273
22
    P = AfterEscape+NewLineSize;
1274
22
  }
1275
2.53k
}
1276
1277
std::optional<Token> Lexer::findNextToken(SourceLocation Loc,
1278
                                          const SourceManager &SM,
1279
2.76k
                                          const LangOptions &LangOpts) {
1280
2.76k
  if (Loc.isMacroID()) {
1281
2
    if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1282
2
      return std::nullopt;
1283
2
  }
1284
2.76k
  Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1285
1286
  // Break down the source location.
1287
2.76k
  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1288
1289
  // Try to load the file buffer.
1290
2.76k
  bool InvalidTemp = false;
1291
2.76k
  StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1292
2.76k
  if (InvalidTemp)
1293
0
    return std::nullopt;
1294
1295
2.76k
  const char *TokenBegin = File.data() + LocInfo.second;
1296
1297
  // Lex from the start of the given location.
1298
2.76k
  Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1299
2.76k
                                      TokenBegin, File.end());
1300
  // Find the token.
1301
2.76k
  Token Tok;
1302
2.76k
  lexer.LexFromRawLexer(Tok);
1303
2.76k
  return Tok;
1304
2.76k
}
1305
1306
/// Checks that the given token is the first token that occurs after the
1307
/// given location (this excludes comments and whitespace). Returns the location
1308
/// immediately after the specified token. If the token is not found or the
1309
/// location is inside a macro, the returned source location will be invalid.
1310
SourceLocation Lexer::findLocationAfterToken(
1311
    SourceLocation Loc, tok::TokenKind TKind, const SourceManager &SM,
1312
2.19k
    const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine) {
1313
2.19k
  std::optional<Token> Tok = findNextToken(Loc, SM, LangOpts);
1314
2.19k
  if (!Tok || 
Tok->isNot(TKind)2.19k
)
1315
892
    return {};
1316
1.30k
  SourceLocation TokenLoc = Tok->getLocation();
1317
1318
  // Calculate how much whitespace needs to be skipped if any.
1319
1.30k
  unsigned NumWhitespaceChars = 0;
1320
1.30k
  if (SkipTrailingWhitespaceAndNewLine) {
1321
7
    const char *TokenEnd = SM.getCharacterData(TokenLoc) + Tok->getLength();
1322
7
    unsigned char C = *TokenEnd;
1323
15
    while (isHorizontalWhitespace(C)) {
1324
8
      C = *(++TokenEnd);
1325
8
      NumWhitespaceChars++;
1326
8
    }
1327
1328
    // Skip \r, \n, \r\n, or \n\r
1329
7
    if (C == '\n' || C == '\r') {
1330
0
      char PrevC = C;
1331
0
      C = *(++TokenEnd);
1332
0
      NumWhitespaceChars++;
1333
0
      if ((C == '\n' || C == '\r') && C != PrevC)
1334
0
        NumWhitespaceChars++;
1335
0
    }
1336
7
  }
1337
1338
1.30k
  return TokenLoc.getLocWithOffset(Tok->getLength() + NumWhitespaceChars);
1339
2.19k
}
1340
1341
/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1342
/// get its size, and return it.  This is tricky in several cases:
1343
///   1. If currently at the start of a trigraph, we warn about the trigraph,
1344
///      then either return the trigraph (skipping 3 chars) or the '?',
1345
///      depending on whether trigraphs are enabled or not.
1346
///   2. If this is an escaped newline (potentially with whitespace between
1347
///      the backslash and newline), implicitly skip the newline and return
1348
///      the char after it.
1349
///
1350
/// This handles the slow/uncommon case of the getCharAndSize method.  Here we
1351
/// know that we can accumulate into Size, and that we have already incremented
1352
/// Ptr by Size bytes.
1353
///
1354
/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1355
/// be updated to match.
1356
char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1357
15.1M
                               Token *Tok) {
1358
  // If we have a slash, look for an escaped newline.
1359
15.1M
  if (Ptr[0] == '\\') {
1360
7.59M
    ++Size;
1361
7.59M
    ++Ptr;
1362
7.59M
Slash:
1363
    // Common case, backslash-char where the char is not whitespace.
1364
7.59M
    if (!isWhitespace(Ptr[0])) 
return '\\'215k
;
1365
1366
    // See if we have optional whitespace characters between the slash and
1367
    // newline.
1368
7.38M
    if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1369
      // Remember that this token needs to be cleaned.
1370
7.38M
      if (Tok) 
Tok->setFlag(Token::NeedsCleaning)7.38M
;
1371
1372
      // Warn if there was whitespace between the backslash and newline.
1373
7.38M
      if (Ptr[0] != '\n' && 
Ptr[0] != '\r'244
&&
Tok40
&&
!isLexingRawMode()25
)
1374
12
        Diag(Ptr, diag::backslash_newline_space);
1375
1376
      // Found backslash<whitespace><newline>.  Parse the char after it.
1377
7.38M
      Size += EscapedNewLineSize;
1378
7.38M
      Ptr  += EscapedNewLineSize;
1379
1380
      // Use slow version to accumulate a correct size field.
1381
7.38M
      return getCharAndSizeSlow(Ptr, Size, Tok);
1382
7.38M
    }
1383
1384
    // Otherwise, this is not an escaped newline, just return the slash.
1385
34
    return '\\';
1386
7.38M
  }
1387
1388
  // If this is a trigraph, process it.
1389
7.59M
  if (Ptr[0] == '?' && 
Ptr[1] == '?'213k
) {
1390
    // If this is actually a legal trigraph (not something like "??x"), emit
1391
    // a trigraph warning.  If so, and if trigraphs are enabled, return it.
1392
385
    if (char C = DecodeTrigraphChar(Ptr + 2, Tok ? this : nullptr,
1393
385
                                    LangOpts.Trigraphs)) {
1394
      // Remember that this token needs to be cleaned.
1395
132
      if (Tok) 
Tok->setFlag(Token::NeedsCleaning)89
;
1396
1397
132
      Ptr += 3;
1398
132
      Size += 3;
1399
132
      if (C == '\\') 
goto Slash18
;
1400
114
      return C;
1401
132
    }
1402
385
  }
1403
1404
  // If this is neither, return a single character.
1405
7.59M
  ++Size;
1406
7.59M
  return *Ptr;
1407
7.59M
}
1408
1409
/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1410
/// getCharAndSizeNoWarn method.  Here we know that we can accumulate into Size,
1411
/// and that we have already incremented Ptr by Size bytes.
1412
///
1413
/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1414
/// be updated to match.
1415
char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1416
65.1k
                                     const LangOptions &LangOpts) {
1417
  // If we have a slash, look for an escaped newline.
1418
65.1k
  if (Ptr[0] == '\\') {
1419
33.9k
    ++Size;
1420
33.9k
    ++Ptr;
1421
33.9k
Slash:
1422
    // Common case, backslash-char where the char is not whitespace.
1423
33.9k
    if (!isWhitespace(Ptr[0])) 
return '\\'2.80k
;
1424
1425
    // See if we have optional whitespace characters followed by a newline.
1426
31.1k
    if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1427
      // Found backslash<whitespace><newline>.  Parse the char after it.
1428
31.1k
      Size += EscapedNewLineSize;
1429
31.1k
      Ptr  += EscapedNewLineSize;
1430
1431
      // Use slow version to accumulate a correct size field.
1432
31.1k
      return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1433
31.1k
    }
1434
1435
    // Otherwise, this is not an escaped newline, just return the slash.
1436
0
    return '\\';
1437
31.1k
  }
1438
1439
  // If this is a trigraph, process it.
1440
31.2k
  if (LangOpts.Trigraphs && 
Ptr[0] == '?'6.86k
&&
Ptr[1] == '?'45
) {
1441
    // If this is actually a legal trigraph (not something like "??x"), return
1442
    // it.
1443
45
    if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1444
45
      Ptr += 3;
1445
45
      Size += 3;
1446
45
      if (C == '\\') 
goto Slash8
;
1447
37
      return C;
1448
45
    }
1449
45
  }
1450
1451
  // If this is neither, return a single character.
1452
31.1k
  ++Size;
1453
31.1k
  return *Ptr;
1454
31.2k
}
1455
1456
//===----------------------------------------------------------------------===//
1457
// Helper methods for lexing.
1458
//===----------------------------------------------------------------------===//
1459
1460
/// Routine that indiscriminately sets the offset into the source file.
1461
439
void Lexer::SetByteOffset(unsigned Offset, bool StartOfLine) {
1462
439
  BufferPtr = BufferStart + Offset;
1463
439
  if (BufferPtr > BufferEnd)
1464
0
    BufferPtr = BufferEnd;
1465
  // FIXME: What exactly does the StartOfLine bit mean?  There are two
1466
  // possible meanings for the "start" of the line: the first token on the
1467
  // unexpanded line, or the first token on the expanded line.
1468
439
  IsAtStartOfLine = StartOfLine;
1469
439
  IsAtPhysicalStartOfLine = StartOfLine;
1470
439
}
1471
1472
369
static bool isUnicodeWhitespace(uint32_t Codepoint) {
1473
369
  static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
1474
369
      UnicodeWhitespaceCharRanges);
1475
369
  return UnicodeWhitespaceChars.contains(Codepoint);
1476
369
}
1477
1478
119
static llvm::SmallString<5> codepointAsHexString(uint32_t C) {
1479
119
  llvm::SmallString<5> CharBuf;
1480
119
  llvm::raw_svector_ostream CharOS(CharBuf);
1481
119
  llvm::write_hex(CharOS, C, llvm::HexPrintStyle::Upper, 4);
1482
119
  return CharBuf;
1483
119
}
1484
1485
// To mitigate https://github.com/llvm/llvm-project/issues/54732,
1486
// we allow "Mathematical Notation Characters" in identifiers.
1487
// This is a proposed profile that extends the XID_Start/XID_continue
1488
// with mathematical symbols, superscipts and subscripts digits
1489
// found in some production software.
1490
// https://www.unicode.org/L2/L2022/22230-math-profile.pdf
1491
static bool isMathematicalExtensionID(uint32_t C, const LangOptions &LangOpts,
1492
238
                                      bool IsStart, bool &IsExtension) {
1493
238
  static const llvm::sys::UnicodeCharSet MathStartChars(
1494
238
      MathematicalNotationProfileIDStartRanges);
1495
238
  static const llvm::sys::UnicodeCharSet MathContinueChars(
1496
238
      MathematicalNotationProfileIDContinueRanges);
1497
238
  if (MathStartChars.contains(C) ||
1498
238
      
(230
!IsStart230
&&
MathContinueChars.contains(C)112
)) {
1499
22
    IsExtension = true;
1500
22
    return true;
1501
22
  }
1502
216
  return false;
1503
238
}
1504
1505
static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts,
1506
759
                            bool &IsExtension) {
1507
759
  if (LangOpts.AsmPreprocessor) {
1508
2
    return false;
1509
757
  } else if (LangOpts.DollarIdents && '$' == C) {
1510
0
    return true;
1511
757
  } else if (LangOpts.CPlusPlus || 
LangOpts.C23511
) {
1512
    // A non-leading codepoint must have the XID_Continue property.
1513
    // XIDContinueRanges doesn't contains characters also in XIDStartRanges,
1514
    // so we need to check both tables.
1515
    // '_' doesn't have the XID_Continue property but is allowed in C and C++.
1516
311
    static const llvm::sys::UnicodeCharSet XIDStartChars(XIDStartRanges);
1517
311
    static const llvm::sys::UnicodeCharSet XIDContinueChars(XIDContinueRanges);
1518
311
    if (C == '_' || XIDStartChars.contains(C) || 
XIDContinueChars.contains(C)125
)
1519
197
      return true;
1520
114
    return isMathematicalExtensionID(C, LangOpts, /*IsStart=*/false,
1521
114
                                     IsExtension);
1522
446
  } else if (LangOpts.C11) {
1523
269
    static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1524
269
        C11AllowedIDCharRanges);
1525
269
    return C11AllowedIDChars.contains(C);
1526
269
  } else {
1527
177
    static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1528
177
        C99AllowedIDCharRanges);
1529
177
    return C99AllowedIDChars.contains(C);
1530
177
  }
1531
759
}
1532
1533
static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts,
1534
409
                                     bool &IsExtension) {
1535
409
  assert(C > 0x7F && "isAllowedInitiallyIDChar called with an ASCII codepoint");
1536
409
  IsExtension = false;
1537
409
  if (LangOpts.AsmPreprocessor) {
1538
0
    return false;
1539
0
  }
1540
409
  if (LangOpts.CPlusPlus || 
LangOpts.C23252
) {
1541
219
    static const llvm::sys::UnicodeCharSet XIDStartChars(XIDStartRanges);
1542
219
    if (XIDStartChars.contains(C))
1543
95
      return true;
1544
124
    return isMathematicalExtensionID(C, LangOpts, /*IsStart=*/true,
1545
124
                                     IsExtension);
1546
219
  }
1547
190
  if (!isAllowedIDChar(C, LangOpts, IsExtension))
1548
77
    return false;
1549
113
  if (LangOpts.C11) {
1550
85
    static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1551
85
        C11DisallowedInitialIDCharRanges);
1552
85
    return !C11DisallowedInitialIDChars.contains(C);
1553
85
  }
1554
28
  static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1555
28
      C99DisallowedInitialIDCharRanges);
1556
28
  return !C99DisallowedInitialIDChars.contains(C);
1557
113
}
1558
1559
static void diagnoseExtensionInIdentifier(DiagnosticsEngine &Diags, uint32_t C,
1560
20
                                          CharSourceRange Range) {
1561
1562
20
  static const llvm::sys::UnicodeCharSet MathStartChars(
1563
20
      MathematicalNotationProfileIDStartRanges);
1564
20
  static const llvm::sys::UnicodeCharSet MathContinueChars(
1565
20
      MathematicalNotationProfileIDContinueRanges);
1566
1567
20
  (void)MathStartChars;
1568
20
  (void)MathContinueChars;
1569
20
  assert((MathStartChars.contains(C) || MathContinueChars.contains(C)) &&
1570
20
         "Unexpected mathematical notation codepoint");
1571
20
  Diags.Report(Range.getBegin(), diag::ext_mathematical_notation)
1572
20
      << codepointAsHexString(C) << Range;
1573
20
}
1574
1575
static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1576
851
                                            const char *End) {
1577
851
  return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1578
851
                                       L.getSourceLocation(End));
1579
851
}
1580
1581
static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1582
452
                                      CharSourceRange Range, bool IsFirst) {
1583
  // Check C99 compatibility.
1584
452
  if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
1585
16
    enum {
1586
16
      CannotAppearInIdentifier = 0,
1587
16
      CannotStartIdentifier
1588
16
    };
1589
1590
16
    static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1591
16
        C99AllowedIDCharRanges);
1592
16
    static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1593
16
        C99DisallowedInitialIDCharRanges);
1594
16
    if (!C99AllowedIDChars.contains(C)) {
1595
6
      Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1596
6
        << Range
1597
6
        << CannotAppearInIdentifier;
1598
10
    } else if (IsFirst && 
C99DisallowedInitialIDChars.contains(C)4
) {
1599
2
      Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1600
2
        << Range
1601
2
        << CannotStartIdentifier;
1602
2
    }
1603
16
  }
1604
452
}
1605
1606
/// After encountering UTF-8 character C and interpreting it as an identifier
1607
/// character, check whether it's a homoglyph for a common non-identifier
1608
/// source character that is unlikely to be an intentional identifier
1609
/// character and warn if so.
1610
static void maybeDiagnoseUTF8Homoglyph(DiagnosticsEngine &Diags, uint32_t C,
1611
273
                                       CharSourceRange Range) {
1612
  // FIXME: Handle Unicode quotation marks (smart quotes, fullwidth quotes).
1613
273
  struct HomoglyphPair {
1614
273
    uint32_t Character;
1615
273
    char LooksLike;
1616
1.60k
    bool operator<(HomoglyphPair R) const { return Character < R.Character; }
1617
273
  };
1618
273
  static constexpr HomoglyphPair SortedHomoglyphs[] = {
1619
273
    {U'\u00ad', 0},   // SOFT HYPHEN
1620
273
    {U'\u01c3', '!'}, // LATIN LETTER RETROFLEX CLICK
1621
273
    {U'\u037e', ';'}, // GREEK QUESTION MARK
1622
273
    {U'\u200b', 0},   // ZERO WIDTH SPACE
1623
273
    {U'\u200c', 0},   // ZERO WIDTH NON-JOINER
1624
273
    {U'\u200d', 0},   // ZERO WIDTH JOINER
1625
273
    {U'\u2060', 0},   // WORD JOINER
1626
273
    {U'\u2061', 0},   // FUNCTION APPLICATION
1627
273
    {U'\u2062', 0},   // INVISIBLE TIMES
1628
273
    {U'\u2063', 0},   // INVISIBLE SEPARATOR
1629
273
    {U'\u2064', 0},   // INVISIBLE PLUS
1630
273
    {U'\u2212', '-'}, // MINUS SIGN
1631
273
    {U'\u2215', '/'}, // DIVISION SLASH
1632
273
    {U'\u2216', '\\'}, // SET MINUS
1633
273
    {U'\u2217', '*'}, // ASTERISK OPERATOR
1634
273
    {U'\u2223', '|'}, // DIVIDES
1635
273
    {U'\u2227', '^'}, // LOGICAL AND
1636
273
    {U'\u2236', ':'}, // RATIO
1637
273
    {U'\u223c', '~'}, // TILDE OPERATOR
1638
273
    {U'\ua789', ':'}, // MODIFIER LETTER COLON
1639
273
    {U'\ufeff', 0},   // ZERO WIDTH NO-BREAK SPACE
1640
273
    {U'\uff01', '!'}, // FULLWIDTH EXCLAMATION MARK
1641
273
    {U'\uff03', '#'}, // FULLWIDTH NUMBER SIGN
1642
273
    {U'\uff04', '$'}, // FULLWIDTH DOLLAR SIGN
1643
273
    {U'\uff05', '%'}, // FULLWIDTH PERCENT SIGN
1644
273
    {U'\uff06', '&'}, // FULLWIDTH AMPERSAND
1645
273
    {U'\uff08', '('}, // FULLWIDTH LEFT PARENTHESIS
1646
273
    {U'\uff09', ')'}, // FULLWIDTH RIGHT PARENTHESIS
1647
273
    {U'\uff0a', '*'}, // FULLWIDTH ASTERISK
1648
273
    {U'\uff0b', '+'}, // FULLWIDTH ASTERISK
1649
273
    {U'\uff0c', ','}, // FULLWIDTH COMMA
1650
273
    {U'\uff0d', '-'}, // FULLWIDTH HYPHEN-MINUS
1651
273
    {U'\uff0e', '.'}, // FULLWIDTH FULL STOP
1652
273
    {U'\uff0f', '/'}, // FULLWIDTH SOLIDUS
1653
273
    {U'\uff1a', ':'}, // FULLWIDTH COLON
1654
273
    {U'\uff1b', ';'}, // FULLWIDTH SEMICOLON
1655
273
    {U'\uff1c', '<'}, // FULLWIDTH LESS-THAN SIGN
1656
273
    {U'\uff1d', '='}, // FULLWIDTH EQUALS SIGN
1657
273
    {U'\uff1e', '>'}, // FULLWIDTH GREATER-THAN SIGN
1658
273
    {U'\uff1f', '?'}, // FULLWIDTH QUESTION MARK
1659
273
    {U'\uff20', '@'}, // FULLWIDTH COMMERCIAL AT
1660
273
    {U'\uff3b', '['}, // FULLWIDTH LEFT SQUARE BRACKET
1661
273
    {U'\uff3c', '\\'}, // FULLWIDTH REVERSE SOLIDUS
1662
273
    {U'\uff3d', ']'}, // FULLWIDTH RIGHT SQUARE BRACKET
1663
273
    {U'\uff3e', '^'}, // FULLWIDTH CIRCUMFLEX ACCENT
1664
273
    {U'\uff5b', '{'}, // FULLWIDTH LEFT CURLY BRACKET
1665
273
    {U'\uff5c', '|'}, // FULLWIDTH VERTICAL LINE
1666
273
    {U'\uff5d', '}'}, // FULLWIDTH RIGHT CURLY BRACKET
1667
273
    {U'\uff5e', '~'}, // FULLWIDTH TILDE
1668
273
    {0, 0}
1669
273
  };
1670
273
  auto Homoglyph =
1671
273
      std::lower_bound(std::begin(SortedHomoglyphs),
1672
273
                       std::end(SortedHomoglyphs) - 1, HomoglyphPair{C, '\0'});
1673
273
  if (Homoglyph->Character == C) {
1674
39
    if (Homoglyph->LooksLike) {
1675
32
      const char LooksLikeStr[] = {Homoglyph->LooksLike, 0};
1676
32
      Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_homoglyph)
1677
32
          << Range << codepointAsHexString(C) << LooksLikeStr;
1678
32
    } else {
1679
7
      Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_zero_width)
1680
7
          << Range << codepointAsHexString(C);
1681
7
    }
1682
39
  }
1683
273
}
1684
1685
static void diagnoseInvalidUnicodeCodepointInIdentifier(
1686
    DiagnosticsEngine &Diags, const LangOptions &LangOpts, uint32_t CodePoint,
1687
60
    CharSourceRange Range, bool IsFirst) {
1688
60
  if (isASCII(CodePoint))
1689
0
    return;
1690
1691
60
  bool IsExtension;
1692
60
  bool IsIDStart = isAllowedInitiallyIDChar(CodePoint, LangOpts, IsExtension);
1693
60
  bool IsIDContinue =
1694
60
      IsIDStart || isAllowedIDChar(CodePoint, LangOpts, IsExtension);
1695
1696
60
  if ((IsFirst && 
IsIDStart22
) || (!IsFirst &&
IsIDContinue38
))
1697
0
    return;
1698
1699
60
  bool InvalidOnlyAtStart = IsFirst && 
!IsIDStart22
&&
IsIDContinue22
;
1700
1701
60
  if (!IsFirst || 
InvalidOnlyAtStart22
) {
1702
46
    Diags.Report(Range.getBegin(), diag::err_character_not_allowed_identifier)
1703
46
        << Range << codepointAsHexString(CodePoint) << int(InvalidOnlyAtStart)
1704
46
        << FixItHint::CreateRemoval(Range);
1705
46
  } else {
1706
14
    Diags.Report(Range.getBegin(), diag::err_character_not_allowed)
1707
14
        << Range << codepointAsHexString(CodePoint)
1708
14
        << FixItHint::CreateRemoval(Range);
1709
14
  }
1710
60
}
1711
1712
bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1713
313
                                    Token &Result) {
1714
313
  const char *UCNPtr = CurPtr + Size;
1715
313
  uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
1716
313
  if (CodePoint == 0) {
1717
96
    return false;
1718
96
  }
1719
217
  bool IsExtension = false;
1720
217
  if (!isAllowedIDChar(CodePoint, LangOpts, IsExtension)) {
1721
27
    if (isASCII(CodePoint) || 
isUnicodeWhitespace(CodePoint)25
)
1722
2
      return false;
1723
25
    if (!isLexingRawMode() && 
!ParsingPreprocessorDirective22
&&
1724
25
        
!PP->isPreprocessedOutput()22
)
1725
20
      diagnoseInvalidUnicodeCodepointInIdentifier(
1726
20
          PP->getDiagnostics(), LangOpts, CodePoint,
1727
20
          makeCharRange(*this, CurPtr, UCNPtr),
1728
20
          /*IsFirst=*/false);
1729
1730
    // We got a unicode codepoint that is neither a space nor a
1731
    // a valid identifier part.
1732
    // Carry on as if the codepoint was valid for recovery purposes.
1733
190
  } else if (!isLexingRawMode()) {
1734
179
    if (IsExtension)
1735
2
      diagnoseExtensionInIdentifier(PP->getDiagnostics(), CodePoint,
1736
2
                                    makeCharRange(*this, CurPtr, UCNPtr));
1737
1738
179
    maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1739
179
                              makeCharRange(*this, CurPtr, UCNPtr),
1740
179
                              /*IsFirst=*/false);
1741
179
  }
1742
1743
215
  Result.setFlag(Token::HasUCN);
1744
215
  if ((UCNPtr - CurPtr ==  6 && 
CurPtr[1] == 'u'136
) ||
1745
215
      
(79
UCNPtr - CurPtr == 1079
&&
CurPtr[1] == 'U'31
))
1746
155
    CurPtr = UCNPtr;
1747
60
  else
1748
1.05k
    
while (60
CurPtr != UCNPtr)
1749
992
      (void)getAndAdvanceChar(CurPtr, Result);
1750
215
  return true;
1751
217
}
1752
1753
307
bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr, Token &Result) {
1754
307
  llvm::UTF32 CodePoint;
1755
1756
  // If a UTF-8 codepoint appears immediately after an escaped new line,
1757
  // CurPtr may point to the splicing \ on the preceding line,
1758
  // so we need to skip it.
1759
307
  unsigned FirstCodeUnitSize;
1760
307
  getCharAndSize(CurPtr, FirstCodeUnitSize);
1761
307
  const char *CharStart = CurPtr + FirstCodeUnitSize - 1;
1762
307
  const char *UnicodePtr = CharStart;
1763
1764
307
  llvm::ConversionResult ConvResult = llvm::convertUTF8Sequence(
1765
307
      (const llvm::UTF8 **)&UnicodePtr, (const llvm::UTF8 *)BufferEnd,
1766
307
      &CodePoint, llvm::strictConversion);
1767
307
  if (ConvResult != llvm::conversionOK)
1768
15
    return false;
1769
1770
292
  bool IsExtension = false;
1771
292
  if (!isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts,
1772
292
                       IsExtension)) {
1773
98
    if (isASCII(CodePoint) || isUnicodeWhitespace(CodePoint))
1774
10
      return false;
1775
1776
88
    if (!isLexingRawMode() && 
!ParsingPreprocessorDirective37
&&
1777
88
        
!PP->isPreprocessedOutput()37
)
1778
18
      diagnoseInvalidUnicodeCodepointInIdentifier(
1779
18
          PP->getDiagnostics(), LangOpts, CodePoint,
1780
18
          makeCharRange(*this, CharStart, UnicodePtr), /*IsFirst=*/false);
1781
    // We got a unicode codepoint that is neither a space nor a
1782
    // a valid identifier part. Carry on as if the codepoint was
1783
    // valid for recovery purposes.
1784
194
  } else if (!isLexingRawMode()) {
1785
157
    if (IsExtension)
1786
12
      diagnoseExtensionInIdentifier(
1787
12
          PP->getDiagnostics(), CodePoint,
1788
12
          makeCharRange(*this, CharStart, UnicodePtr));
1789
157
    maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1790
157
                              makeCharRange(*this, CharStart, UnicodePtr),
1791
157
                              /*IsFirst=*/false);
1792
157
    maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), CodePoint,
1793
157
                               makeCharRange(*this, CharStart, UnicodePtr));
1794
157
  }
1795
1796
  // Once we sucessfully parsed some UTF-8,
1797
  // calling ConsumeChar ensures the NeedsCleaning flag is set on the token
1798
  // being lexed, and that warnings about trailing spaces are emitted.
1799
282
  ConsumeChar(CurPtr, FirstCodeUnitSize, Result);
1800
282
  CurPtr = UnicodePtr;
1801
282
  return true;
1802
292
}
1803
1804
bool Lexer::LexUnicodeIdentifierStart(Token &Result, uint32_t C,
1805
349
                                      const char *CurPtr) {
1806
349
  bool IsExtension = false;
1807
349
  if (isAllowedInitiallyIDChar(C, LangOpts, IsExtension)) {
1808
208
    if (!isLexingRawMode() && 
!ParsingPreprocessorDirective161
&&
1809
208
        
!PP->isPreprocessedOutput()125
) {
1810
116
      if (IsExtension)
1811
6
        diagnoseExtensionInIdentifier(PP->getDiagnostics(), C,
1812
6
                                      makeCharRange(*this, BufferPtr, CurPtr));
1813
116
      maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
1814
116
                                makeCharRange(*this, BufferPtr, CurPtr),
1815
116
                                /*IsFirst=*/true);
1816
116
      maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), C,
1817
116
                                 makeCharRange(*this, BufferPtr, CurPtr));
1818
116
    }
1819
1820
208
    MIOpt.ReadToken();
1821
208
    return LexIdentifierContinue(Result, CurPtr);
1822
208
  }
1823
1824
141
  if (!isLexingRawMode() && 
!ParsingPreprocessorDirective83
&&
1825
141
      
!PP->isPreprocessedOutput()52
&&
!isASCII(*BufferPtr)35
&&
1826
141
      
!isUnicodeWhitespace(C)22
) {
1827
    // Non-ASCII characters tend to creep into source code unintentionally.
1828
    // Instead of letting the parser complain about the unknown token,
1829
    // just drop the character.
1830
    // Note that we can /only/ do this when the non-ASCII character is actually
1831
    // spelled as Unicode, not written as a UCN. The standard requires that
1832
    // we not throw away any possible preprocessor tokens, but there's a
1833
    // loophole in the mapping of Unicode characters to basic character set
1834
    // characters that allows us to map these particular characters to, say,
1835
    // whitespace.
1836
22
    diagnoseInvalidUnicodeCodepointInIdentifier(
1837
22
        PP->getDiagnostics(), LangOpts, C,
1838
22
        makeCharRange(*this, BufferPtr, CurPtr), /*IsStart*/ true);
1839
22
    BufferPtr = CurPtr;
1840
22
    return false;
1841
22
  }
1842
1843
  // Otherwise, we have an explicit UCN or a character that's unlikely to show
1844
  // up by accident.
1845
119
  MIOpt.ReadToken();
1846
119
  FormTokenWithChars(Result, CurPtr, tok::unknown);
1847
119
  return true;
1848
141
}
1849
1850
703M
bool Lexer::LexIdentifierContinue(Token &Result, const char *CurPtr) {
1851
  // Match [_A-Za-z0-9]*, we have already matched an identifier start.
1852
7.83G
  while (true) {
1853
7.83G
    unsigned char C = *CurPtr;
1854
    // Fast path.
1855
7.83G
    if (isAsciiIdentifierContinue(C)) {
1856
7.13G
      ++CurPtr;
1857
7.13G
      continue;
1858
7.13G
    }
1859
1860
703M
    unsigned Size;
1861
    // Slow path: handle trigraph, unicode codepoints, UCNs.
1862
703M
    C = getCharAndSize(CurPtr, Size);
1863
703M
    if (isAsciiIdentifierContinue(C)) {
1864
108
      CurPtr = ConsumeChar(CurPtr, Size, Result);
1865
108
      continue;
1866
108
    }
1867
703M
    if (C == '$') {
1868
      // If we hit a $ and they are not supported in identifiers, we are done.
1869
24.1k
      if (!LangOpts.DollarIdents)
1870
2
        break;
1871
      // Otherwise, emit a diagnostic and continue.
1872
24.1k
      if (!isLexingRawMode())
1873
2.82k
        Diag(CurPtr, diag::ext_dollar_in_identifier);
1874
24.1k
      CurPtr = ConsumeChar(CurPtr, Size, Result);
1875
24.1k
      continue;
1876
24.1k
    }
1877
702M
    if (C == '\\' && 
tryConsumeIdentifierUCN(CurPtr, Size, Result)281
)
1878
190
      continue;
1879
702M
    if (!isASCII(C) && 
tryConsumeIdentifierUTF8Char(CurPtr, Result)278
)
1880
253
      continue;
1881
    // Neither an expected Unicode codepoint nor a UCN.
1882
702M
    break;
1883
702M
  }
1884
1885
703M
  const char *IdStart = BufferPtr;
1886
703M
  FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1887
703M
  Result.setRawIdentifierData(IdStart);
1888
1889
  // If we are in raw mode, return this identifier raw.  There is no need to
1890
  // look up identifier information or attempt to macro expand it.
1891
703M
  if (LexingRawMode)
1892
146M
    return true;
1893
1894
  // Fill in Result.IdentifierInfo and update the token kind,
1895
  // looking up the identifier in the identifier table.
1896
556M
  IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1897
  // Note that we have to call PP->LookUpIdentifierInfo() even for code
1898
  // completion, it writes IdentifierInfo into Result, and callers rely on it.
1899
1900
  // If the completion point is at the end of an identifier, we want to treat
1901
  // the identifier as incomplete even if it resolves to a macro or a keyword.
1902
  // This allows e.g. 'class^' to complete to 'classifier'.
1903
556M
  if (isCodeCompletionPoint(CurPtr)) {
1904
    // Return the code-completion token.
1905
91
    Result.setKind(tok::code_completion);
1906
    // Skip the code-completion char and all immediate identifier characters.
1907
    // This ensures we get consistent behavior when completing at any point in
1908
    // an identifier (i.e. at the start, in the middle, at the end). Note that
1909
    // only simple cases (i.e. [a-zA-Z0-9_]) are supported to keep the code
1910
    // simpler.
1911
91
    assert(*CurPtr == 0 && "Completion character must be 0");
1912
91
    ++CurPtr;
1913
    // Note that code completion token is not added as a separate character
1914
    // when the completion point is at the end of the buffer. Therefore, we need
1915
    // to check if the buffer has ended.
1916
91
    if (CurPtr < BufferEnd) {
1917
139
      while (isAsciiIdentifierContinue(*CurPtr))
1918
49
        ++CurPtr;
1919
90
    }
1920
91
    BufferPtr = CurPtr;
1921
91
    return true;
1922
91
  }
1923
1924
  // Finally, now that we know we have an identifier, pass this off to the
1925
  // preprocessor, which may macro expand it or something.
1926
556M
  if (II->isHandleIdentifierCase())
1927
48.1M
    return PP->HandleIdentifier(Result);
1928
1929
508M
  return true;
1930
556M
}
1931
1932
/// isHexaLiteral - Return true if Start points to a hex constant.
1933
/// in microsoft mode (where this is supposed to be several different tokens).
1934
196k
bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1935
196k
  unsigned Size;
1936
196k
  char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1937
196k
  if (C1 != '0')
1938
188k
    return false;
1939
7.65k
  char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1940
7.65k
  return (C2 == 'x' || 
C2 == 'X'15
);
1941
196k
}
1942
1943
/// LexNumericConstant - Lex the remainder of a integer or floating point
1944
/// constant. From[-1] is the first character lexed.  Return the end of the
1945
/// constant.
1946
65.8M
bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1947
65.8M
  unsigned Size;
1948
65.8M
  char C = getCharAndSize(CurPtr, Size);
1949
65.8M
  char PrevCh = 0;
1950
226M
  while (isPreprocessingNumberBody(C)) {
1951
160M
    CurPtr = ConsumeChar(CurPtr, Size, Result);
1952
160M
    PrevCh = C;
1953
160M
    C = getCharAndSize(CurPtr, Size);
1954
160M
  }
1955
1956
  // If we fell out, check for a sign, due to 1e+12.  If we have one, continue.
1957
65.8M
  if ((C == '-' || 
C == '+'64.7M
) &&
(1.51M
PrevCh == 'E'1.51M
||
PrevCh == 'e'1.51M
)) {
1958
    // If we are in Microsoft mode, don't continue if the constant is hex.
1959
    // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1960
1.41M
    if (!LangOpts.MicrosoftExt || 
!isHexaLiteral(BufferPtr, LangOpts)188k
)
1961
1.41M
      return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1962
1.41M
  }
1963
1964
  // If we have a hex FP constant, continue.
1965
64.4M
  if ((C == '-' || 
C == '+'64.3M
) &&
(107k
PrevCh == 'P'107k
||
PrevCh == 'p'107k
)) {
1966
    // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
1967
    // not-quite-conforming extension. Only do so if this looks like it's
1968
    // actually meant to be a hexfloat, and not if it has a ud-suffix.
1969
13.6k
    bool IsHexFloat = true;
1970
13.6k
    if (!LangOpts.C99) {
1971
7.63k
      if (!isHexaLiteral(BufferPtr, LangOpts))
1972
9
        IsHexFloat = false;
1973
7.62k
      else if (!LangOpts.CPlusPlus17 &&
1974
7.62k
               
std::find(BufferPtr, CurPtr, '_') != CurPtr6.89k
)
1975
3
        IsHexFloat = false;
1976
7.63k
    }
1977
13.6k
    if (IsHexFloat)
1978
13.6k
      return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1979
13.6k
  }
1980
1981
  // If we have a digit separator, continue.
1982
64.3M
  if (C == '\'' && 
(1.94k
LangOpts.CPlusPlus141.94k
||
LangOpts.C23487
)) {
1983
1.58k
    unsigned NextSize;
1984
1.58k
    char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, LangOpts);
1985
1.58k
    if (isAsciiIdentifierContinue(Next)) {
1986
1.56k
      if (!isLexingRawMode())
1987
542
        Diag(CurPtr, LangOpts.CPlusPlus
1988
542
                         ? 
diag::warn_cxx11_compat_digit_separator422
1989
542
                         : 
diag::warn_c23_compat_digit_separator120
);
1990
1.56k
      CurPtr = ConsumeChar(CurPtr, Size, Result);
1991
1.56k
      CurPtr = ConsumeChar(CurPtr, NextSize, Result);
1992
1.56k
      return LexNumericConstant(Result, CurPtr);
1993
1.56k
    }
1994
1.58k
  }
1995
1996
  // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1997
64.3M
  if (C == '\\' && 
tryConsumeIdentifierUCN(CurPtr, Size, Result)6
)
1998
5
    return LexNumericConstant(Result, CurPtr);
1999
64.3M
  if (!isASCII(C) && 
tryConsumeIdentifierUTF8Char(CurPtr, Result)13
)
2000
13
    return LexNumericConstant(Result, CurPtr);
2001
2002
  // Update the location of token as well as BufferPtr.
2003
64.3M
  const char *TokStart = BufferPtr;
2004
64.3M
  FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
2005
64.3M
  Result.setLiteralData(TokStart);
2006
64.3M
  return true;
2007
64.3M
}
2008
2009
/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
2010
/// in C++11, or warn on a ud-suffix in C++98.
2011
const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
2012
8.61M
                               bool IsStringLiteral) {
2013
8.61M
  assert(LangOpts.CPlusPlus);
2014
2015
  // Maximally munch an identifier.
2016
8.61M
  unsigned Size;
2017
8.61M
  char C = getCharAndSize(CurPtr, Size);
2018
8.61M
  bool Consumed = false;
2019
2020
8.61M
  if (!isAsciiIdentifierStart(C)) {
2021
8.59M
    if (C == '\\' && 
tryConsumeIdentifierUCN(CurPtr, Size, Result)6
)
2022
0
      Consumed = true;
2023
8.59M
    else if (!isASCII(C) && 
tryConsumeIdentifierUTF8Char(CurPtr, Result)0
)
2024
0
      Consumed = true;
2025
8.59M
    else
2026
8.59M
      return CurPtr;
2027
8.59M
  }
2028
2029
17.1k
  if (!LangOpts.CPlusPlus11) {
2030
23
    if (!isLexingRawMode())
2031
8
      Diag(CurPtr,
2032
8
           C == '_' ? 
diag::warn_cxx11_compat_user_defined_literal3
2033
8
                    : 
diag::warn_cxx11_compat_reserved_user_defined_literal5
)
2034
8
        << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
2035
23
    return CurPtr;
2036
23
  }
2037
2038
  // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
2039
  // that does not start with an underscore is ill-formed. As a conforming
2040
  // extension, we treat all such suffixes as if they had whitespace before
2041
  // them. We assume a suffix beginning with a UCN or UTF-8 character is more
2042
  // likely to be a ud-suffix than a macro, however, and accept that.
2043
17.1k
  if (!Consumed) {
2044
17.1k
    bool IsUDSuffix = false;
2045
17.1k
    if (C == '_')
2046
415
      IsUDSuffix = true;
2047
16.7k
    else if (IsStringLiteral && 
LangOpts.CPlusPlus1410.6k
) {
2048
      // In C++1y, we need to look ahead a few characters to see if this is a
2049
      // valid suffix for a string literal or a numeric literal (this could be
2050
      // the 'operator""if' defining a numeric literal operator).
2051
695
      const unsigned MaxStandardSuffixLength = 3;
2052
695
      char Buffer[MaxStandardSuffixLength] = { C };
2053
695
      unsigned Consumed = Size;
2054
695
      unsigned Chars = 1;
2055
1.18k
      while (true) {
2056
1.18k
        unsigned NextSize;
2057
1.18k
        char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize, LangOpts);
2058
1.18k
        if (!isAsciiIdentifierContinue(Next)) {
2059
          // End of suffix. Check whether this is on the allowed list.
2060
692
          const StringRef CompleteSuffix(Buffer, Chars);
2061
692
          IsUDSuffix =
2062
692
              StringLiteralParser::isValidUDSuffix(LangOpts, CompleteSuffix);
2063
692
          break;
2064
692
        }
2065
2066
489
        if (Chars == MaxStandardSuffixLength)
2067
          // Too long: can't be a standard suffix.
2068
3
          break;
2069
2070
486
        Buffer[Chars++] = Next;
2071
486
        Consumed += NextSize;
2072
486
      }
2073
695
    }
2074
2075
17.1k
    if (!IsUDSuffix) {
2076
16.0k
      if (!isLexingRawMode())
2077
15
        Diag(CurPtr, LangOpts.MSVCCompat
2078
15
                         ? 
diag::ext_ms_reserved_user_defined_literal0
2079
15
                         : diag::ext_reserved_user_defined_literal)
2080
15
            << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
2081
16.0k
      return CurPtr;
2082
16.0k
    }
2083
2084
1.09k
    CurPtr = ConsumeChar(CurPtr, Size, Result);
2085
1.09k
  }
2086
2087
1.09k
  Result.setFlag(Token::HasUDSuffix);
2088
2.49k
  while (true) {
2089
2.49k
    C = getCharAndSize(CurPtr, Size);
2090
2.49k
    if (isAsciiIdentifierContinue(C)) {
2091
1.36k
      CurPtr = ConsumeChar(CurPtr, Size, Result);
2092
1.36k
    } else 
if (1.12k
C == '\\'1.12k
&&
tryConsumeIdentifierUCN(CurPtr, Size, Result)20
) {
2093
1.10k
    } else if (!isASCII(C) && 
tryConsumeIdentifierUTF8Char(CurPtr, Result)16
) {
2094
16
    } else
2095
1.09k
      break;
2096
2.49k
  }
2097
2098
1.09k
  return CurPtr;
2099
17.1k
}
2100
2101
/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
2102
/// either " or L" or u8" or u" or U".
2103
bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
2104
13.5M
                             tok::TokenKind Kind) {
2105
13.5M
  const char *AfterQuote = CurPtr;
2106
  // Does this string contain the \0 character?
2107
13.5M
  const char *NulCharacter = nullptr;
2108
2109
13.5M
  if (!isLexingRawMode() &&
2110
13.5M
      
(10.8M
Kind == tok::utf8_string_literal10.8M
||
2111
10.8M
       
Kind == tok::utf16_string_literal10.8M
||
2112
10.8M
       
Kind == tok::utf32_string_literal10.8M
))
2113
826
    Diag(BufferPtr, LangOpts.CPlusPlus ? 
diag::warn_cxx98_compat_unicode_literal666
2114
826
                                       : 
diag::warn_c99_compat_unicode_literal160
);
2115
2116
13.5M
  char C = getAndAdvanceChar(CurPtr, Result);
2117
146M
  while (C != '"') {
2118
    // Skip escaped characters.  Escaped newlines will already be processed by
2119
    // getAndAdvanceChar.
2120
132M
    if (C == '\\')
2121
198k
      C = getAndAdvanceChar(CurPtr, Result);
2122
2123
132M
    if (C == '\n' || 
C == '\r'132M
|| // Newline.
2124
132M
        
(132M
C == 0132M
&&
CurPtr-1 == BufferEnd44
)) { // End of file.
2125
86
      if (!isLexingRawMode() && 
!LangOpts.AsmPreprocessor7
)
2126
5
        Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
2127
86
      FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2128
86
      return true;
2129
86
    }
2130
2131
132M
    if (C == 0) {
2132
21
      if (isCodeCompletionPoint(CurPtr-1)) {
2133
12
        if (ParsingFilename)
2134
5
          codeCompleteIncludedFile(AfterQuote, CurPtr - 1, /*IsAngled=*/false);
2135
7
        else
2136
7
          PP->CodeCompleteNaturalLanguage();
2137
12
        FormTokenWithChars(Result, CurPtr - 1, tok::unknown);
2138
12
        cutOffLexing();
2139
12
        return true;
2140
12
      }
2141
2142
9
      NulCharacter = CurPtr-1;
2143
9
    }
2144
132M
    C = getAndAdvanceChar(CurPtr, Result);
2145
132M
  }
2146
2147
  // If we are in C++11, lex the optional ud-suffix.
2148
13.5M
  if (LangOpts.CPlusPlus)
2149
8.12M
    CurPtr = LexUDSuffix(Result, CurPtr, true);
2150
2151
  // If a nul character existed in the string, warn about it.
2152
13.5M
  if (NulCharacter && 
!isLexingRawMode()8
)
2153
2
    Diag(NulCharacter, diag::null_in_char_or_string) << 1;
2154
2155
  // Update the location of the token as well as the BufferPtr instance var.
2156
13.5M
  const char *TokStart = BufferPtr;
2157
13.5M
  FormTokenWithChars(Result, CurPtr, Kind);
2158
13.5M
  Result.setLiteralData(TokStart);
2159
13.5M
  return true;
2160
13.5M
}
2161
2162
/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
2163
/// having lexed R", LR", u8R", uR", or UR".
2164
bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
2165
633
                                tok::TokenKind Kind) {
2166
  // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
2167
  //  Between the initial and final double quote characters of the raw string,
2168
  //  any transformations performed in phases 1 and 2 (trigraphs,
2169
  //  universal-character-names, and line splicing) are reverted.
2170
2171
633
  if (!isLexingRawMode())
2172
137
    Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
2173
2174
633
  unsigned PrefixLen = 0;
2175
2176
1.90k
  while (PrefixLen != 16 && 
isRawStringDelimBody(CurPtr[PrefixLen])1.90k
)
2177
1.27k
    ++PrefixLen;
2178
2179
  // If the last character was not a '(', then we didn't lex a valid delimiter.
2180
633
  if (CurPtr[PrefixLen] != '(') {
2181
4
    if (!isLexingRawMode()) {
2182
1
      const char *PrefixEnd = &CurPtr[PrefixLen];
2183
1
      if (PrefixLen == 16) {
2184
1
        Diag(PrefixEnd, diag::err_raw_delim_too_long);
2185
1
      } else {
2186
0
        Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
2187
0
          << StringRef(PrefixEnd, 1);
2188
0
      }
2189
1
    }
2190
2191
    // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
2192
    // it's possible the '"' was intended to be part of the raw string, but
2193
    // there's not much we can do about that.
2194
347
    while (true) {
2195
347
      char C = *CurPtr++;
2196
2197
347
      if (C == '"')
2198
4
        break;
2199
343
      if (C == 0 && 
CurPtr-1 == BufferEnd0
) {
2200
0
        --CurPtr;
2201
0
        break;
2202
0
      }
2203
343
    }
2204
2205
4
    FormTokenWithChars(Result, CurPtr, tok::unknown);
2206
4
    return true;
2207
4
  }
2208
2209
  // Save prefix and move CurPtr past it
2210
629
  const char *Prefix = CurPtr;
2211
629
  CurPtr += PrefixLen + 1; // skip over prefix and '('
2212
2213
12.0k
  while (true) {
2214
12.0k
    char C = *CurPtr++;
2215
2216
12.0k
    if (C == ')') {
2217
      // Check for prefix match and closing quote.
2218
639
      if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && 
CurPtr[PrefixLen] == '"'631
) {
2219
625
        CurPtr += PrefixLen + 1; // skip over prefix and '"'
2220
625
        break;
2221
625
      }
2222
11.3k
    } else if (C == 0 && 
CurPtr-1 == BufferEnd4
) { // End of file.
2223
4
      if (!isLexingRawMode())
2224
1
        Diag(BufferPtr, diag::err_unterminated_raw_string)
2225
1
          << StringRef(Prefix, PrefixLen);
2226
4
      FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2227
4
      return true;
2228
4
    }
2229
12.0k
  }
2230
2231
  // If we are in C++11, lex the optional ud-suffix.
2232
625
  if (LangOpts.CPlusPlus)
2233
625
    CurPtr = LexUDSuffix(Result, CurPtr, true);
2234
2235
  // Update the location of token as well as BufferPtr.
2236
625
  const char *TokStart = BufferPtr;
2237
625
  FormTokenWithChars(Result, CurPtr, Kind);
2238
625
  Result.setLiteralData(TokStart);
2239
625
  return true;
2240
629
}
2241
2242
/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
2243
/// after having lexed the '<' character.  This is used for #include filenames.
2244
3.74M
bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
2245
  // Does this string contain the \0 character?
2246
3.74M
  const char *NulCharacter = nullptr;
2247
3.74M
  const char *AfterLessPos = CurPtr;
2248
3.74M
  char C = getAndAdvanceChar(CurPtr, Result);
2249
79.6M
  while (C != '>') {
2250
    // Skip escaped characters.  Escaped newlines will already be processed by
2251
    // getAndAdvanceChar.
2252
75.9M
    if (C == '\\')
2253
6
      C = getAndAdvanceChar(CurPtr, Result);
2254
2255
75.9M
    if (isVerticalWhitespace(C) ||               // Newline.
2256
75.9M
        
(75.9M
C == 075.9M
&&
(CurPtr - 1 == BufferEnd)13
)) { // End of file.
2257
      // If the filename is unterminated, then it must just be a lone <
2258
      // character.  Return this as such.
2259
10
      FormTokenWithChars(Result, AfterLessPos, tok::less);
2260
10
      return true;
2261
10
    }
2262
2263
75.9M
    if (C == 0) {
2264
10
      if (isCodeCompletionPoint(CurPtr - 1)) {
2265
9
        codeCompleteIncludedFile(AfterLessPos, CurPtr - 1, /*IsAngled=*/true);
2266
9
        cutOffLexing();
2267
9
        FormTokenWithChars(Result, CurPtr - 1, tok::unknown);
2268
9
        return true;
2269
9
      }
2270
1
      NulCharacter = CurPtr-1;
2271
1
    }
2272
75.9M
    C = getAndAdvanceChar(CurPtr, Result);
2273
75.9M
  }
2274
2275
  // If a nul character existed in the string, warn about it.
2276
3.74M
  if (NulCharacter && 
!isLexingRawMode()1
)
2277
1
    Diag(NulCharacter, diag::null_in_char_or_string) << 1;
2278
2279
  // Update the location of token as well as BufferPtr.
2280
3.74M
  const char *TokStart = BufferPtr;
2281
3.74M
  FormTokenWithChars(Result, CurPtr, tok::header_name);
2282
3.74M
  Result.setLiteralData(TokStart);
2283
3.74M
  return true;
2284
3.74M
}
2285
2286
void Lexer::codeCompleteIncludedFile(const char *PathStart,
2287
                                     const char *CompletionPoint,
2288
14
                                     bool IsAngled) {
2289
  // Completion only applies to the filename, after the last slash.
2290
14
  StringRef PartialPath(PathStart, CompletionPoint - PathStart);
2291
14
  llvm::StringRef SlashChars = LangOpts.MSVCCompat ? 
"/\\"4
:
"/"10
;
2292
14
  auto Slash = PartialPath.find_last_of(SlashChars);
2293
14
  StringRef Dir =
2294
14
      (Slash == StringRef::npos) ? 
""10
:
PartialPath.take_front(Slash)4
;
2295
14
  const char *StartOfFilename =
2296
14
      (Slash == StringRef::npos) ? 
PathStart10
:
PathStart + Slash + 14
;
2297
  // Code completion filter range is the filename only, up to completion point.
2298
14
  PP->setCodeCompletionIdentifierInfo(&PP->getIdentifierTable().get(
2299
14
      StringRef(StartOfFilename, CompletionPoint - StartOfFilename)));
2300
  // We should replace the characters up to the closing quote or closest slash,
2301
  // if any.
2302
85
  while (CompletionPoint < BufferEnd) {
2303
85
    char Next = *(CompletionPoint + 1);
2304
85
    if (Next == 0 || Next == '\r' || Next == '\n')
2305
0
      break;
2306
85
    ++CompletionPoint;
2307
85
    if (Next == (IsAngled ? 
'>'60
:
'"'25
))
2308
13
      break;
2309
72
    if (SlashChars.contains(Next))
2310
1
      break;
2311
72
  }
2312
2313
14
  PP->setCodeCompletionTokenRange(
2314
14
      FileLoc.getLocWithOffset(StartOfFilename - BufferStart),
2315
14
      FileLoc.getLocWithOffset(CompletionPoint - BufferStart));
2316
14
  PP->CodeCompleteIncludedFile(Dir, IsAngled);
2317
14
}
2318
2319
/// LexCharConstant - Lex the remainder of a character constant, after having
2320
/// lexed either ' or L' or u8' or u' or U'.
2321
bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
2322
970k
                            tok::TokenKind Kind) {
2323
  // Does this character contain the \0 character?
2324
970k
  const char *NulCharacter = nullptr;
2325
2326
970k
  if (!isLexingRawMode()) {
2327
620k
    if (Kind == tok::utf16_char_constant || 
Kind == tok::utf32_char_constant620k
)
2328
328
      Diag(BufferPtr, LangOpts.CPlusPlus
2329
328
                          ? 
diag::warn_cxx98_compat_unicode_literal270
2330
328
                          : 
diag::warn_c99_compat_unicode_literal58
);
2331
620k
    else if (Kind == tok::utf8_char_constant)
2332
197
      Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
2333
620k
  }
2334
2335
970k
  char C = getAndAdvanceChar(CurPtr, Result);
2336
970k
  if (C == '\'') {
2337
26
    if (!isLexingRawMode() && 
!LangOpts.AsmPreprocessor2
)
2338
0
      Diag(BufferPtr, diag::ext_empty_character);
2339
26
    FormTokenWithChars(Result, CurPtr, tok::unknown);
2340
26
    return true;
2341
26
  }
2342
2343
3.59M
  
while (970k
C != '\'') {
2344
    // Skip escaped characters.
2345
2.62M
    if (C == '\\')
2346
13.2k
      C = getAndAdvanceChar(CurPtr, Result);
2347
2348
2.62M
    if (C == '\n' || 
C == '\r'2.62M
|| // Newline.
2349
2.62M
        
(2.62M
C == 02.62M
&&
CurPtr-1 == BufferEnd19
)) { // End of file.
2350
137
      if (!isLexingRawMode() && 
!LangOpts.AsmPreprocessor24
)
2351
21
        Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
2352
137
      FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2353
137
      return true;
2354
137
    }
2355
2356
2.62M
    if (C == 0) {
2357
14
      if (isCodeCompletionPoint(CurPtr-1)) {
2358
6
        PP->CodeCompleteNaturalLanguage();
2359
6
        FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2360
6
        cutOffLexing();
2361
6
        return true;
2362
6
      }
2363
2364
8
      NulCharacter = CurPtr-1;
2365
8
    }
2366
2.62M
    C = getAndAdvanceChar(CurPtr, Result);
2367
2.62M
  }
2368
2369
  // If we are in C++11, lex the optional ud-suffix.
2370
969k
  if (LangOpts.CPlusPlus)
2371
495k
    CurPtr = LexUDSuffix(Result, CurPtr, false);
2372
2373
  // If a nul character existed in the character, warn about it.
2374
969k
  if (NulCharacter && 
!isLexingRawMode()8
)
2375
2
    Diag(NulCharacter, diag::null_in_char_or_string) << 0;
2376
2377
  // Update the location of token as well as BufferPtr.
2378
969k
  const char *TokStart = BufferPtr;
2379
969k
  FormTokenWithChars(Result, CurPtr, Kind);
2380
969k
  Result.setLiteralData(TokStart);
2381
969k
  return true;
2382
970k
}
2383
2384
/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2385
/// Update BufferPtr to point to the next non-whitespace character and return.
2386
///
2387
/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2388
bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2389
155M
                           bool &TokAtPhysicalStartOfLine) {
2390
  // Whitespace - Skip it, then return the token after the whitespace.
2391
155M
  bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2392
2393
155M
  unsigned char Char = *CurPtr;
2394
2395
155M
  const char *lastNewLine = nullptr;
2396
164M
  auto setLastNewLine = [&](const char *Ptr) {
2397
164M
    lastNewLine = Ptr;
2398
164M
    if (!NewLinePtr)
2399
138M
      NewLinePtr = Ptr;
2400
164M
  };
2401
155M
  if (SawNewline)
2402
149M
    setLastNewLine(CurPtr - 1);
2403
2404
  // Skip consecutive spaces efficiently.
2405
170M
  while (true) {
2406
    // Skip horizontal whitespace very aggressively.
2407
525M
    while (isHorizontalWhitespace(Char))
2408
354M
      Char = *++CurPtr;
2409
2410
    // Otherwise if we have something other than whitespace, we're done.
2411
170M
    if (!isVerticalWhitespace(Char))
2412
155M
      break;
2413
2414
15.1M
    if (ParsingPreprocessorDirective) {
2415
      // End of preprocessor directive line, let LexTokenInternal handle this.
2416
1.36k
      BufferPtr = CurPtr;
2417
1.36k
      return false;
2418
1.36k
    }
2419
2420
    // OK, but handle newline.
2421
15.1M
    if (*CurPtr == '\n')
2422
15.1M
      setLastNewLine(CurPtr);
2423
15.1M
    SawNewline = true;
2424
15.1M
    Char = *++CurPtr;
2425
15.1M
  }
2426
2427
  // If the client wants us to return whitespace, return it now.
2428
155M
  if (isKeepWhitespaceMode()) {
2429
166k
    FormTokenWithChars(Result, CurPtr, tok::unknown);
2430
166k
    if (SawNewline) {
2431
163k
      IsAtStartOfLine = true;
2432
163k
      IsAtPhysicalStartOfLine = true;
2433
163k
    }
2434
    // FIXME: The next token will not have LeadingSpace set.
2435
166k
    return true;
2436
166k
  }
2437
2438
  // If this isn't immediately after a newline, there is leading space.
2439
155M
  char PrevChar = CurPtr[-1];
2440
155M
  bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2441
2442
155M
  Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2443
155M
  if (SawNewline) {
2444
149M
    Result.setFlag(Token::StartOfLine);
2445
149M
    TokAtPhysicalStartOfLine = true;
2446
2447
149M
    if (
NewLinePtr149M
&& lastNewLine && NewLinePtr != lastNewLine &&
PP22.0M
) {
2448
21.4M
      if (auto *Handler = PP->getEmptylineHandler())
2449
205
        Handler->HandleEmptyline(SourceRange(getSourceLocation(NewLinePtr + 1),
2450
205
                                             getSourceLocation(lastNewLine)));
2451
21.4M
    }
2452
149M
  }
2453
2454
155M
  BufferPtr = CurPtr;
2455
155M
  return false;
2456
155M
}
2457
2458
/// We have just read the // characters from input.  Skip until we find the
2459
/// newline character that terminates the comment.  Then update BufferPtr and
2460
/// return.
2461
///
2462
/// If we're in KeepCommentMode or any CommentHandler has inserted
2463
/// some tokens, this will store the first token and return true.
2464
bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2465
40.5M
                            bool &TokAtPhysicalStartOfLine) {
2466
  // If Line comments aren't explicitly enabled for this language, emit an
2467
  // extension warning.
2468
40.5M
  if (!LineComment) {
2469
4.62k
    if (!isLexingRawMode()) // There's no PP in raw mode, so can't emit diags.
2470
4.58k
      Diag(BufferPtr, diag::ext_line_comment);
2471
2472
    // Mark them enabled so we only emit one warning for this translation
2473
    // unit.
2474
4.62k
    LineComment = true;
2475
4.62k
  }
2476
2477
  // Scan over the body of the comment.  The common case, when scanning, is that
2478
  // the comment contains normal ascii characters with nothing interesting in
2479
  // them.  As such, optimize for this case with the inner loop.
2480
  //
2481
  // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2482
  // character that ends the line comment.
2483
2484
  // C++23 [lex.phases] p1
2485
  // Diagnose invalid UTF-8 if the corresponding warning is enabled, emitting a
2486
  // diagnostic only once per entire ill-formed subsequence to avoid
2487
  // emiting to many diagnostics (see http://unicode.org/review/pr-121.html).
2488
40.5M
  bool UnicodeDecodingAlreadyDiagnosed = false;
2489
2490
40.5M
  char C;
2491
40.8M
  while (true) {
2492
40.8M
    C = *CurPtr;
2493
    // Skip over characters in the fast loop.
2494
2.34G
    while (isASCII(C) && 
C != 02.34G
&& // Potentially EOF.
2495
2.34G
           
C != '\n'2.34G
&&
C != '\r'2.30G
) { // Newline or DOS-style newline.
2496
2.30G
      C = *++CurPtr;
2497
2.30G
      UnicodeDecodingAlreadyDiagnosed = false;
2498
2.30G
    }
2499
2500
40.8M
    if (!isASCII(C)) {
2501
6.74k
      unsigned Length = llvm::getUTF8SequenceSize(
2502
6.74k
          (const llvm::UTF8 *)CurPtr, (const llvm::UTF8 *)BufferEnd);
2503
6.74k
      if (Length == 0) {
2504
51
        if (!UnicodeDecodingAlreadyDiagnosed && 
!isLexingRawMode()37
)
2505
28
          Diag(CurPtr, diag::warn_invalid_utf8_in_comment);
2506
51
        UnicodeDecodingAlreadyDiagnosed = true;
2507
51
        ++CurPtr;
2508
6.69k
      } else {
2509
6.69k
        UnicodeDecodingAlreadyDiagnosed = false;
2510
6.69k
        CurPtr += Length;
2511
6.69k
      }
2512
6.74k
      continue;
2513
6.74k
    }
2514
2515
40.8M
    const char *NextLine = CurPtr;
2516
40.8M
    if (C != 0) {
2517
      // We found a newline, see if it's escaped.
2518
40.8M
      const char *EscapePtr = CurPtr-1;
2519
40.8M
      bool HasSpace = false;
2520
40.8M
      while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
2521
16.8k
        --EscapePtr;
2522
16.8k
        HasSpace = true;
2523
16.8k
      }
2524
2525
40.8M
      if (*EscapePtr == '\\')
2526
        // Escaped newline.
2527
303k
        CurPtr = EscapePtr;
2528
40.5M
      else if (EscapePtr[0] == '/' && 
EscapePtr[-1] == '?'4.83M
&&
2529
40.5M
               
EscapePtr[-2] == '?'8
&&
LangOpts.Trigraphs8
)
2530
        // Trigraph-escaped newline.
2531
3
        CurPtr = EscapePtr-2;
2532
40.5M
      else
2533
40.5M
        break; // This is a newline, we're done.
2534
2535
      // If there was space between the backslash and newline, warn about it.
2536
303k
      if (HasSpace && 
!isLexingRawMode()8
)
2537
6
        Diag(EscapePtr, diag::backslash_newline_space);
2538
303k
    }
2539
2540
    // Otherwise, this is a hard case.  Fall back on getAndAdvanceChar to
2541
    // properly decode the character.  Read it in raw mode to avoid emitting
2542
    // diagnostics about things like trigraphs.  If we see an escaped newline,
2543
    // we'll handle it below.
2544
308k
    const char *OldPtr = CurPtr;
2545
308k
    bool OldRawMode = isLexingRawMode();
2546
308k
    LexingRawMode = true;
2547
308k
    C = getAndAdvanceChar(CurPtr, Result);
2548
308k
    LexingRawMode = OldRawMode;
2549
2550
    // If we only read only one character, then no special handling is needed.
2551
    // We're done and can skip forward to the newline.
2552
308k
    if (C != 0 && 
CurPtr == OldPtr+1303k
) {
2553
0
      CurPtr = NextLine;
2554
0
      break;
2555
0
    }
2556
2557
    // If we read multiple characters, and one of those characters was a \r or
2558
    // \n, then we had an escaped newline within the comment.  Emit diagnostic
2559
    // unless the next line is also a // comment.
2560
308k
    if (CurPtr != OldPtr + 1 && 
C != '/'303k
&&
2561
308k
        
(9.73k
CurPtr == BufferEnd + 19.73k
||
CurPtr[0] != '/'9.72k
)) {
2562
19.4k
      for (; OldPtr != CurPtr; 
++OldPtr9.71k
)
2563
19.4k
        if (OldPtr[0] == '\n' || 
OldPtr[0] == '\r'9.72k
) {
2564
          // Okay, we found a // comment that ends in a newline, if the next
2565
          // line is also a // comment, but has spaces, don't emit a diagnostic.
2566
9.70k
          if (isWhitespace(C)) {
2567
9.38k
            const char *ForwardPtr = CurPtr;
2568
202k
            while (isWhitespace(*ForwardPtr))  // Skip whitespace.
2569
193k
              ++ForwardPtr;
2570
9.38k
            if (ForwardPtr[0] == '/' && 
ForwardPtr[1] == '/'7.99k
)
2571
7.99k
              break;
2572
9.38k
          }
2573
2574
1.71k
          if (!isLexingRawMode())
2575
1.46k
            Diag(OldPtr-1, diag::ext_multi_line_line_comment);
2576
1.71k
          break;
2577
9.70k
        }
2578
9.70k
    }
2579
2580
308k
    if (C == '\r' || C == '\n' || 
CurPtr == BufferEnd + 1308k
) {
2581
4.83k
      --CurPtr;
2582
4.83k
      break;
2583
4.83k
    }
2584
2585
303k
    if (C == '\0' && 
isCodeCompletionPoint(CurPtr-1)8
) {
2586
8
      PP->CodeCompleteNaturalLanguage();
2587
8
      cutOffLexing();
2588
8
      return false;
2589
8
    }
2590
303k
  }
2591
2592
  // Found but did not consume the newline.  Notify comment handlers about the
2593
  // comment unless we're in a #if 0 block.
2594
40.5M
  if (PP && 
!isLexingRawMode()40.4M
&&
2595
40.5M
      PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2596
36.3M
                                            getSourceLocation(CurPtr)))) {
2597
0
    BufferPtr = CurPtr;
2598
0
    return true; // A token has to be returned.
2599
0
  }
2600
2601
  // If we are returning comments as tokens, return this comment as a token.
2602
40.5M
  if (inKeepCommentMode())
2603
60.2k
    return SaveLineComment(Result, CurPtr);
2604
2605
  // If we are inside a preprocessor directive and we see the end of line,
2606
  // return immediately, so that the lexer can return this as an EOD token.
2607
40.4M
  if (ParsingPreprocessorDirective || 
CurPtr == BufferEnd39.3M
) {
2608
1.08M
    BufferPtr = CurPtr;
2609
1.08M
    return false;
2610
1.08M
  }
2611
2612
  // Otherwise, eat the \n character.  We don't care if this is a \n\r or
2613
  // \r\n sequence.  This is an efficiency hack (because we know the \n can't
2614
  // contribute to another token), it isn't needed for correctness.  Note that
2615
  // this is ok even in KeepWhitespaceMode, because we would have returned the
2616
  // comment above in that mode.
2617
39.3M
  NewLinePtr = CurPtr++;
2618
2619
  // The next returned token is at the start of the line.
2620
39.3M
  Result.setFlag(Token::StartOfLine);
2621
39.3M
  TokAtPhysicalStartOfLine = true;
2622
  // No leading whitespace seen so far.
2623
39.3M
  Result.clearFlag(Token::LeadingSpace);
2624
39.3M
  BufferPtr = CurPtr;
2625
39.3M
  return false;
2626
40.4M
}
2627
2628
/// If in save-comment mode, package up this Line comment in an appropriate
2629
/// way and return it.
2630
60.2k
bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2631
  // If we're not in a preprocessor directive, just return the // comment
2632
  // directly.
2633
60.2k
  FormTokenWithChars(Result, CurPtr, tok::comment);
2634
2635
60.2k
  if (!ParsingPreprocessorDirective || 
LexingRawMode2
)
2636
60.1k
    return true;
2637
2638
  // If this Line-style comment is in a macro definition, transmogrify it into
2639
  // a C-style block comment.
2640
2
  bool Invalid = false;
2641
2
  std::string Spelling = PP->getSpelling(Result, &Invalid);
2642
2
  if (Invalid)
2643
0
    return true;
2644
2645
2
  assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2646
2
  Spelling[1] = '*';   // Change prefix to "/*".
2647
2
  Spelling += "*/";    // add suffix.
2648
2649
2
  Result.setKind(tok::comment);
2650
2
  PP->CreateString(Spelling, Result,
2651
2
                   Result.getLocation(), Result.getLocation());
2652
2
  return true;
2653
2
}
2654
2655
/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2656
/// character (either \\n or \\r) is part of an escaped newline sequence.  Issue
2657
/// a diagnostic if so.  We know that the newline is inside of a block comment.
2658
static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, Lexer *L,
2659
52.5k
                                                  bool Trigraphs) {
2660
52.5k
  assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2661
2662
  // Position of the first trigraph in the ending sequence.
2663
52.5k
  const char *TrigraphPos = nullptr;
2664
  // Position of the first whitespace after a '\' in the ending sequence.
2665
52.5k
  const char *SpacePos = nullptr;
2666
2667
52.5k
  while (true) {
2668
    // Back up off the newline.
2669
52.5k
    --CurPtr;
2670
2671
    // If this is a two-character newline sequence, skip the other character.
2672
52.5k
    if (CurPtr[0] == '\n' || 
CurPtr[0] == '\r'5.26k
) {
2673
      // \n\n or \r\r -> not escaped newline.
2674
47.3k
      if (CurPtr[0] == CurPtr[1])
2675
47.3k
        return false;
2676
      // \n\r or \r\n -> skip the newline.
2677
0
      --CurPtr;
2678
0
    }
2679
2680
    // If we have horizontal whitespace, skip over it.  We allow whitespace
2681
    // between the slash and newline.
2682
5.31k
    
while (5.26k
isHorizontalWhitespace(*CurPtr) ||
*CurPtr == 05.26k
) {
2683
55
      SpacePos = CurPtr;
2684
55
      --CurPtr;
2685
55
    }
2686
2687
    // If we have a slash, this is an escaped newline.
2688
5.26k
    if (*CurPtr == '\\') {
2689
22
      --CurPtr;
2690
5.24k
    } else if (CurPtr[0] == '/' && 
CurPtr[-1] == '?'678
&&
CurPtr[-2] == '?'15
) {
2691
      // This is a trigraph encoding of a slash.
2692
15
      TrigraphPos = CurPtr - 2;
2693
15
      CurPtr -= 3;
2694
5.22k
    } else {
2695
5.22k
      return false;
2696
5.22k
    }
2697
2698
    // If the character preceding the escaped newline is a '*', then after line
2699
    // splicing we have a '*/' ending the comment.
2700
37
    if (*CurPtr == '*')
2701
22
      break;
2702
2703
15
    if (*CurPtr != '\n' && 
*CurPtr != '\r'0
)
2704
0
      return false;
2705
15
  }
2706
2707
22
  if (TrigraphPos) {
2708
    // If no trigraphs are enabled, warn that we ignored this trigraph and
2709
    // ignore this * character.
2710
10
    if (!Trigraphs) {
2711
0
      if (!L->isLexingRawMode())
2712
0
        L->Diag(TrigraphPos, diag::trigraph_ignored_block_comment);
2713
0
      return false;
2714
0
    }
2715
10
    if (!L->isLexingRawMode())
2716
10
      L->Diag(TrigraphPos, diag::trigraph_ends_block_comment);
2717
10
  }
2718
2719
  // Warn about having an escaped newline between the */ characters.
2720
22
  if (!L->isLexingRawMode())
2721
19
    L->Diag(CurPtr + 1, diag::escaped_newline_block_comment_end);
2722
2723
  // If there was space between the backslash and newline, warn about it.
2724
22
  if (SpacePos && 
!L->isLexingRawMode()20
)
2725
17
    L->Diag(SpacePos, diag::backslash_newline_space);
2726
2727
22
  return true;
2728
22
}
2729
2730
#ifdef __SSE2__
2731
#include <emmintrin.h>
2732
#elif __ALTIVEC__
2733
#include <altivec.h>
2734
#undef bool
2735
#endif
2736
2737
/// We have just read from input the / and * characters that started a comment.
2738
/// Read until we find the * and / characters that terminate the comment.
2739
/// Note that we don't bother decoding trigraphs or escaped newlines in block
2740
/// comments, because they cannot cause the comment to end.  The only thing
2741
/// that can happen is the comment could end with an escaped newline between
2742
/// the terminating * and /.
2743
///
2744
/// If we're in KeepCommentMode or any CommentHandler has inserted
2745
/// some tokens, this will store the first token and return true.
2746
bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2747
10.2M
                             bool &TokAtPhysicalStartOfLine) {
2748
  // Scan one character past where we should, looking for a '/' character.  Once
2749
  // we find it, check to see if it was preceded by a *.  This common
2750
  // optimization helps people who like to put a lot of * characters in their
2751
  // comments.
2752
2753
  // The first character we get with newlines and trigraphs skipped to handle
2754
  // the degenerate /*/ case below correctly if the * has an escaped newline
2755
  // after it.
2756
10.2M
  unsigned CharSize;
2757
10.2M
  unsigned char C = getCharAndSize(CurPtr, CharSize);
2758
10.2M
  CurPtr += CharSize;
2759
10.2M
  if (C == 0 && 
CurPtr == BufferEnd+14
) {
2760
3
    if (!isLexingRawMode())
2761
0
      Diag(BufferPtr, diag::err_unterminated_block_comment);
2762
3
    --CurPtr;
2763
2764
    // KeepWhitespaceMode should return this broken comment as a token.  Since
2765
    // it isn't a well formed comment, just return it as an 'unknown' token.
2766
3
    if (isKeepWhitespaceMode()) {
2767
2
      FormTokenWithChars(Result, CurPtr, tok::unknown);
2768
2
      return true;
2769
2
    }
2770
2771
1
    BufferPtr = CurPtr;
2772
1
    return false;
2773
3
  }
2774
2775
  // Check to see if the first character after the '/*' is another /.  If so,
2776
  // then this slash does not end the block comment, it is part of it.
2777
10.2M
  if (C == '/')
2778
232
    C = *CurPtr++;
2779
2780
  // C++23 [lex.phases] p1
2781
  // Diagnose invalid UTF-8 if the corresponding warning is enabled, emitting a
2782
  // diagnostic only once per entire ill-formed subsequence to avoid
2783
  // emiting to many diagnostics (see http://unicode.org/review/pr-121.html).
2784
10.2M
  bool UnicodeDecodingAlreadyDiagnosed = false;
2785
2786
15.2M
  while (true) {
2787
    // Skip over all non-interesting characters until we find end of buffer or a
2788
    // (probably ending) '/' character.
2789
15.2M
    if (CurPtr + 24 < BufferEnd &&
2790
        // If there is a code-completion point avoid the fast scan because it
2791
        // doesn't check for '\0'.
2792
15.2M
        
!(14.9M
PP14.9M
&&
PP->getCodeCompletionFileLoc() == FileLoc14.9M
)) {
2793
      // While not aligned to a 16-byte boundary.
2794
114M
      while (C != '/' && 
(intptr_t)CurPtr % 16 != 0111M
) {
2795
99.4M
        if (!isASCII(C))
2796
37.3k
          goto MultiByteUTF8;
2797
99.3M
        C = *CurPtr++;
2798
99.3M
      }
2799
14.9M
      if (C == '/') 
goto FoundSlash2.53M
;
2800
2801
12.3M
#ifdef __SSE2__
2802
12.3M
      __m128i Slashes = _mm_set1_epi8('/');
2803
395M
      while (CurPtr + 16 < BufferEnd) {
2804
395M
        int Mask = _mm_movemask_epi8(*(const __m128i *)CurPtr);
2805
395M
        if (LLVM_UNLIKELY(Mask != 0)) {
2806
57.1k
          goto MultiByteUTF8;
2807
57.1k
        }
2808
        // look for slashes
2809
395M
        int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2810
395M
                                    Slashes));
2811
395M
        if (cmp != 0) {
2812
          // Adjust the pointer to point directly after the first slash. It's
2813
          // not necessary to set C here, it will be overwritten at the end of
2814
          // the outer loop.
2815
12.2M
          CurPtr += llvm::countr_zero<unsigned>(cmp) + 1;
2816
12.2M
          goto FoundSlash;
2817
12.2M
        }
2818
383M
        CurPtr += 16;
2819
383M
      }
2820
#elif __ALTIVEC__
2821
      __vector unsigned char LongUTF = {0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
2822
                                        0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
2823
                                        0x80, 0x80, 0x80, 0x80};
2824
      __vector unsigned char Slashes = {
2825
        '/', '/', '/', '/',  '/', '/', '/', '/',
2826
        '/', '/', '/', '/',  '/', '/', '/', '/'
2827
      };
2828
      while (CurPtr + 16 < BufferEnd) {
2829
        if (LLVM_UNLIKELY(
2830
                vec_any_ge(*(const __vector unsigned char *)CurPtr, LongUTF)))
2831
          goto MultiByteUTF8;
2832
        if (vec_any_eq(*(const __vector unsigned char *)CurPtr, Slashes)) {
2833
          break;
2834
        }
2835
        CurPtr += 16;
2836
      }
2837
2838
#else
2839
      while (CurPtr + 16 < BufferEnd) {
2840
        bool HasNonASCII = false;
2841
        for (unsigned I = 0; I < 16; ++I)
2842
          HasNonASCII |= !isASCII(CurPtr[I]);
2843
2844
        if (LLVM_UNLIKELY(HasNonASCII))
2845
          goto MultiByteUTF8;
2846
2847
        bool HasSlash = false;
2848
        for (unsigned I = 0; I < 16; ++I)
2849
          HasSlash |= CurPtr[I] == '/';
2850
        if (HasSlash)
2851
          break;
2852
        CurPtr += 16;
2853
      }
2854
#endif
2855
2856
      // It has to be one of the bytes scanned, increment to it and read one.
2857
96.3k
      C = *CurPtr++;
2858
96.3k
    }
2859
2860
    // Loop to scan the remainder, warning on invalid UTF-8
2861
    // if the corresponding warning is enabled, emitting a diagnostic only once
2862
    // per sequence that cannot be decoded.
2863
25.0M
    
while (344k
C != '/' &&
C != '\0'24.5M
) {
2864
24.5M
      if (isASCII(C)) {
2865
22.8M
        UnicodeDecodingAlreadyDiagnosed = false;
2866
22.8M
        C = *CurPtr++;
2867
22.8M
        continue;
2868
22.8M
      }
2869
1.87M
    MultiByteUTF8:
2870
      // CurPtr is 1 code unit past C, so to decode
2871
      // the codepoint, we need to read from the previous position.
2872
1.87M
      unsigned Length = llvm::getUTF8SequenceSize(
2873
1.87M
          (const llvm::UTF8 *)CurPtr - 1, (const llvm::UTF8 *)BufferEnd);
2874
1.87M
      if (Length == 0) {
2875
1.77M
        if (!UnicodeDecodingAlreadyDiagnosed && 
!isLexingRawMode()76.8k
)
2876
62.5k
          Diag(CurPtr - 1, diag::warn_invalid_utf8_in_comment);
2877
1.77M
        UnicodeDecodingAlreadyDiagnosed = true;
2878
1.77M
      } else {
2879
97.4k
        UnicodeDecodingAlreadyDiagnosed = false;
2880
97.4k
        CurPtr += Length - 1;
2881
97.4k
      }
2882
1.87M
      C = *CurPtr++;
2883
1.87M
    }
2884
2885
439k
    if (C == '/') {
2886
15.2M
  FoundSlash:
2887
15.2M
      if (CurPtr[-2] == '*')  // We found the final */.  We're done!
2888
10.2M
        break;
2889
2890
4.95M
      if ((CurPtr[-2] == '\n' || 
CurPtr[-2] == '\r'4.90M
)) {
2891
52.5k
        if (isEndOfBlockCommentWithEscapedNewLine(CurPtr - 2, this,
2892
52.5k
                                                  LangOpts.Trigraphs)) {
2893
          // We found the final */, though it had an escaped newline between the
2894
          // * and /.  We're done!
2895
22
          break;
2896
22
        }
2897
52.5k
      }
2898
4.95M
      if (CurPtr[0] == '*' && 
CurPtr[1] != '/'234
) {
2899
        // If this is a /* inside of the comment, emit a warning.  Don't do this
2900
        // if this is a /*/, which will end the comment.  This misses cases with
2901
        // embedded escaped newlines, but oh well.
2902
13
        if (!isLexingRawMode())
2903
9
          Diag(CurPtr-1, diag::warn_nested_block_comment);
2904
13
      }
2905
4.95M
    } else 
if (14
C == 014
&&
CurPtr == BufferEnd+114
) {
2906
2
      if (!isLexingRawMode())
2907
2
        Diag(BufferPtr, diag::err_unterminated_block_comment);
2908
      // Note: the user probably forgot a */.  We could continue immediately
2909
      // after the /*, but this would involve lexing a lot of what really is the
2910
      // comment, which surely would confuse the parser.
2911
2
      --CurPtr;
2912
2913
      // KeepWhitespaceMode should return this broken comment as a token.  Since
2914
      // it isn't a well formed comment, just return it as an 'unknown' token.
2915
2
      if (isKeepWhitespaceMode()) {
2916
0
        FormTokenWithChars(Result, CurPtr, tok::unknown);
2917
0
        return true;
2918
0
      }
2919
2920
2
      BufferPtr = CurPtr;
2921
2
      return false;
2922
12
    } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2923
9
      PP->CodeCompleteNaturalLanguage();
2924
9
      cutOffLexing();
2925
9
      return false;
2926
9
    }
2927
2928
4.95M
    C = *CurPtr++;
2929
4.95M
  }
2930
2931
  // Notify comment handlers about the comment unless we're in a #if 0 block.
2932
10.2M
  if (PP && 
!isLexingRawMode()10.2M
&&
2933
10.2M
      PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2934
8.88M
                                            getSourceLocation(CurPtr)))) {
2935
0
    BufferPtr = CurPtr;
2936
0
    return true; // A token has to be returned.
2937
0
  }
2938
2939
  // If we are returning comments as tokens, return this comment as a token.
2940
10.2M
  if (inKeepCommentMode()) {
2941
6.63k
    FormTokenWithChars(Result, CurPtr, tok::comment);
2942
6.63k
    return true;
2943
6.63k
  }
2944
2945
  // It is common for the tokens immediately after a /**/ comment to be
2946
  // whitespace.  Instead of going through the big switch, handle it
2947
  // efficiently now.  This is safe even in KeepWhitespaceMode because we would
2948
  // have already returned above with the comment as a token.
2949
10.2M
  if (isHorizontalWhitespace(*CurPtr)) {
2950
68.3k
    SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
2951
68.3k
    return false;
2952
68.3k
  }
2953
2954
  // Otherwise, just return so that the next character will be lexed as a token.
2955
10.1M
  BufferPtr = CurPtr;
2956
10.1M
  Result.setFlag(Token::LeadingSpace);
2957
10.1M
  return false;
2958
10.2M
}
2959
2960
//===----------------------------------------------------------------------===//
2961
// Primary Lexing Entry Points
2962
//===----------------------------------------------------------------------===//
2963
2964
/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2965
/// uninterpreted string.  This switches the lexer out of directive mode.
2966
37.7k
void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
2967
37.7k
  assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2968
37.7k
         "Must be in a preprocessing directive!");
2969
37.7k
  Token Tmp;
2970
37.7k
  Tmp.startToken();
2971
2972
  // CurPtr - Cache BufferPtr in an automatic variable.
2973
37.7k
  const char *CurPtr = BufferPtr;
2974
734k
  while (true) {
2975
734k
    char Char = getAndAdvanceChar(CurPtr, Tmp);
2976
734k
    switch (Char) {
2977
696k
    default:
2978
696k
      if (Result)
2979
696k
        Result->push_back(Char);
2980
696k
      break;
2981
18
    case 0:  // Null.
2982
      // Found end of file?
2983
18
      if (CurPtr-1 != BufferEnd) {
2984
18
        if (isCodeCompletionPoint(CurPtr-1)) {
2985
18
          PP->CodeCompleteNaturalLanguage();
2986
18
          cutOffLexing();
2987
18
          return;
2988
18
        }
2989
2990
        // Nope, normal character, continue.
2991
0
        if (Result)
2992
0
          Result->push_back(Char);
2993
0
        break;
2994
18
      }
2995
      // FALL THROUGH.
2996
18
      
[[fallthrough]];0
2997
2
    case '\r':
2998
37.7k
    case '\n':
2999
      // Okay, we found the end of the line. First, back up past the \0, \r, \n.
3000
37.7k
      assert(CurPtr[-1] == Char && "Trigraphs for newline?");
3001
37.7k
      BufferPtr = CurPtr-1;
3002
3003
      // Next, lex the character, which should handle the EOD transition.
3004
37.7k
      Lex(Tmp);
3005
37.7k
      if (Tmp.is(tok::code_completion)) {
3006
0
        if (PP)
3007
0
          PP->CodeCompleteNaturalLanguage();
3008
0
        Lex(Tmp);
3009
0
      }
3010
37.7k
      assert(Tmp.is(tok::eod) && "Unexpected token!");
3011
3012
      // Finally, we're done;
3013
37.7k
      return;
3014
734k
    }
3015
734k
  }
3016
37.7k
}
3017
3018
/// LexEndOfFile - CurPtr points to the end of this file.  Handle this
3019
/// condition, reporting diagnostics and handling other edge cases as required.
3020
/// This returns true if Result contains a token, false if PP.Lex should be
3021
/// called again.
3022
3.21M
bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
3023
  // If we hit the end of the file while parsing a preprocessor directive,
3024
  // end the preprocessor directive first.  The next token returned will
3025
  // then be the end of file.
3026
3.21M
  if (ParsingPreprocessorDirective) {
3027
    // Done parsing the "line".
3028
1.48k
    ParsingPreprocessorDirective = false;
3029
    // Update the location of token as well as BufferPtr.
3030
1.48k
    FormTokenWithChars(Result, CurPtr, tok::eod);
3031
3032
    // Restore comment saving mode, in case it was disabled for directive.
3033
1.48k
    if (PP)
3034
1.46k
      resetExtendedTokenMode();
3035
1.48k
    return true;  // Have a token.
3036
1.48k
  }
3037
3038
  // If we are in raw mode, return this event as an EOF token.  Let the caller
3039
  // that put us in raw mode handle the event.
3040
3.21M
  if (isLexingRawMode()) {
3041
1.45M
    Result.startToken();
3042
1.45M
    BufferPtr = BufferEnd;
3043
1.45M
    FormTokenWithChars(Result, BufferEnd, tok::eof);
3044
1.45M
    return true;
3045
1.45M
  }
3046
3047
1.76M
  if (PP->isRecordingPreamble() && 
PP->isInPrimaryFile()276
) {
3048
100
    PP->setRecordedPreambleConditionalStack(ConditionalStack);
3049
    // If the preamble cuts off the end of a header guard, consider it guarded.
3050
    // The guard is valid for the preamble content itself, and for tools the
3051
    // most useful answer is "yes, this file has a header guard".
3052
100
    if (!ConditionalStack.empty())
3053
7
      MIOpt.ExitTopLevelConditional();
3054
100
    ConditionalStack.clear();
3055
100
  }
3056
3057
  // Issue diagnostics for unterminated #if and missing newline.
3058
3059
  // If we are in a #if directive, emit an error.
3060
1.76M
  while (!ConditionalStack.empty()) {
3061
9
    if (PP->getCodeCompletionFileLoc() != FileLoc)
3062
9
      PP->Diag(ConditionalStack.back().IfLoc,
3063
9
               diag::err_pp_unterminated_conditional);
3064
9
    ConditionalStack.pop_back();
3065
9
  }
3066
3067
  // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
3068
  // a pedwarn.
3069
1.76M
  if (CurPtr != BufferStart && 
(1.76M
CurPtr[-1] != '\n'1.76M
&&
CurPtr[-1] != '\r'27.2k
)) {
3070
27.2k
    DiagnosticsEngine &Diags = PP->getDiagnostics();
3071
27.2k
    SourceLocation EndLoc = getSourceLocation(BufferEnd);
3072
27.2k
    unsigned DiagID;
3073
3074
27.2k
    if (LangOpts.CPlusPlus11) {
3075
      // C++11 [lex.phases] 2.2 p2
3076
      // Prefer the C++98 pedantic compatibility warning over the generic,
3077
      // non-extension, user-requested "missing newline at EOF" warning.
3078
20.0k
      if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
3079
2
        DiagID = diag::warn_cxx98_compat_no_newline_eof;
3080
20.0k
      } else {
3081
20.0k
        DiagID = diag::warn_no_newline_eof;
3082
20.0k
      }
3083
20.0k
    } else {
3084
7.20k
      DiagID = diag::ext_no_newline_eof;
3085
7.20k
    }
3086
3087
27.2k
    Diag(BufferEnd, DiagID)
3088
27.2k
      << FixItHint::CreateInsertion(EndLoc, "\n");
3089
27.2k
  }
3090
3091
1.76M
  BufferPtr = CurPtr;
3092
3093
  // Finally, let the preprocessor handle this.
3094
1.76M
  return PP->HandleEndOfFile(Result, isPragmaLexer());
3095
3.21M
}
3096
3097
/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
3098
/// the specified lexer will return a tok::l_paren token, 0 if it is something
3099
/// else and 2 if there are no more tokens in the buffer controlled by the
3100
/// lexer.
3101
3.13M
unsigned Lexer::isNextPPTokenLParen() {
3102
3.13M
  assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
3103
3104
3.13M
  if (isDependencyDirectivesLexer()) {
3105
1
    if (NextDepDirectiveTokenIndex == DepDirectives.front().Tokens.size())
3106
0
      return 2;
3107
1
    return DepDirectives.front().Tokens[NextDepDirectiveTokenIndex].is(
3108
1
        tok::l_paren);
3109
1
  }
3110
3111
  // Switch to 'skipping' mode.  This will ensure that we can lex a token
3112
  // without emitting diagnostics, disables macro expansion, and will cause EOF
3113
  // to return an EOF token instead of popping the include stack.
3114
3.13M
  LexingRawMode = true;
3115
3116
  // Save state that can be changed while lexing so that we can restore it.
3117
3.13M
  const char *TmpBufferPtr = BufferPtr;
3118
3.13M
  bool inPPDirectiveMode = ParsingPreprocessorDirective;
3119
3.13M
  bool atStartOfLine = IsAtStartOfLine;
3120
3.13M
  bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
3121
3.13M
  bool leadingSpace = HasLeadingSpace;
3122
3123
3.13M
  Token Tok;
3124
3.13M
  Lex(Tok);
3125
3126
  // Restore state that may have changed.
3127
3.13M
  BufferPtr = TmpBufferPtr;
3128
3.13M
  ParsingPreprocessorDirective = inPPDirectiveMode;
3129
3.13M
  HasLeadingSpace = leadingSpace;
3130
3.13M
  IsAtStartOfLine = atStartOfLine;
3131
3.13M
  IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
3132
3133
  // Restore the lexer back to non-skipping mode.
3134
3.13M
  LexingRawMode = false;
3135
3136
3.13M
  if (Tok.is(tok::eof))
3137
3
    return 2;
3138
3.13M
  return Tok.is(tok::l_paren);
3139
3.13M
}
3140
3141
/// Find the end of a version control conflict marker.
3142
static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
3143
10
                                   ConflictMarkerKind CMK) {
3144
10
  const char *Terminator = CMK == CMK_Perforce ? 
"<<<<\n"5
:
">>>>>>>"5
;
3145
10
  size_t TermLen = CMK == CMK_Perforce ? 
55
:
75
;
3146
10
  auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
3147
10
  size_t Pos = RestOfBuffer.find(Terminator);
3148
11
  while (Pos != StringRef::npos) {
3149
    // Must occur at start of line.
3150
8
    if (Pos == 0 ||
3151
8
        
(7
RestOfBuffer[Pos - 1] != '\r'7
&&
RestOfBuffer[Pos - 1] != '\n'7
)) {
3152
1
      RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
3153
1
      Pos = RestOfBuffer.find(Terminator);
3154
1
      continue;
3155
1
    }
3156
7
    return RestOfBuffer.data()+Pos;
3157
8
  }
3158
3
  return nullptr;
3159
10
}
3160
3161
/// IsStartOfConflictMarker - If the specified pointer is the start of a version
3162
/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
3163
/// and recover nicely.  This returns true if it is a conflict marker and false
3164
/// if not.
3165
25.5k
bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
3166
  // Only a conflict marker if it starts at the beginning of a line.
3167
25.5k
  if (CurPtr != BufferStart &&
3168
25.5k
      CurPtr[-1] != '\n' && 
CurPtr[-1] != '\r'25.5k
)
3169
25.5k
    return false;
3170
3171
  // Check to see if we have <<<<<<< or >>>>.
3172
91
  if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
3173
91
      
!StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> ")61
)
3174
50
    return false;
3175
3176
  // If we have a situation where we don't care about conflict markers, ignore
3177
  // it.
3178
41
  if (CurrentConflictMarkerState || isLexingRawMode())
3179
36
    return false;
3180
3181
5
  ConflictMarkerKind Kind = *CurPtr == '<' ? 
CMK_Normal3
:
CMK_Perforce2
;
3182
3183
  // Check to see if there is an ending marker somewhere in the buffer at the
3184
  // start of a line to terminate this conflict marker.
3185
5
  if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
3186
    // We found a match.  We are really in a conflict marker.
3187
    // Diagnose this, and ignore to the end of line.
3188
4
    Diag(CurPtr, diag::err_conflict_marker);
3189
4
    CurrentConflictMarkerState = Kind;
3190
3191
    // Skip ahead to the end of line.  We know this exists because the
3192
    // end-of-conflict marker starts with \r or \n.
3193
76
    while (*CurPtr != '\r' && *CurPtr != '\n') {
3194
72
      assert(CurPtr != BufferEnd && "Didn't find end of line");
3195
72
      ++CurPtr;
3196
72
    }
3197
4
    BufferPtr = CurPtr;
3198
4
    return true;
3199
4
  }
3200
3201
  // No end of conflict marker found.
3202
1
  return false;
3203
5
}
3204
3205
/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
3206
/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
3207
/// is the end of a conflict marker.  Handle it by ignoring up until the end of
3208
/// the line.  This returns true if it is a conflict marker and false if not.
3209
25.7k
bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
3210
  // Only a conflict marker if it starts at the beginning of a line.
3211
25.7k
  if (CurPtr != BufferStart &&
3212
25.7k
      
CurPtr[-1] != '\n'25.7k
&&
CurPtr[-1] != '\r'25.5k
)
3213
25.5k
    return false;
3214
3215
  // If we have a situation where we don't care about conflict markers, ignore
3216
  // it.
3217
177
  if (!CurrentConflictMarkerState || 
isLexingRawMode()5
)
3218
172
    return false;
3219
3220
  // Check to see if we have the marker (4 characters in a row).
3221
20
  
for (unsigned i = 1; 5
i != 4;
++i15
)
3222
15
    if (CurPtr[i] != CurPtr[0])
3223
0
      return false;
3224
3225
  // If we do have it, search for the end of the conflict marker.  This could
3226
  // fail if it got skipped with a '#if 0' or something.  Note that CurPtr might
3227
  // be the end of conflict marker.
3228
5
  if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
3229
5
                                        CurrentConflictMarkerState)) {
3230
3
    CurPtr = End;
3231
3232
    // Skip ahead to the end of line.
3233
37
    while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
3234
34
      ++CurPtr;
3235
3236
3
    BufferPtr = CurPtr;
3237
3238
    // No longer in the conflict marker.
3239
3
    CurrentConflictMarkerState = CMK_None;
3240
3
    return true;
3241
3
  }
3242
3243
2
  return false;
3244
5
}
3245
3246
static const char *findPlaceholderEnd(const char *CurPtr,
3247
43
                                      const char *BufferEnd) {
3248
43
  if (CurPtr == BufferEnd)
3249
0
    return nullptr;
3250
43
  BufferEnd -= 1; // Scan until the second last character.
3251
404
  for (; CurPtr != BufferEnd; 
++CurPtr361
) {
3252
404
    if (CurPtr[0] == '#' && 
CurPtr[1] == '>'43
)
3253
43
      return CurPtr + 2;
3254
404
  }
3255
0
  return nullptr;
3256
43
}
3257
3258
45
bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
3259
45
  assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
3260
45
  if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || 
LexingRawMode44
)
3261
2
    return false;
3262
43
  const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
3263
43
  if (!End)
3264
0
    return false;
3265
43
  const char *Start = CurPtr - 1;
3266
43
  if (!LangOpts.AllowEditorPlaceholders)
3267
22
    Diag(Start, diag::err_placeholder_in_source);
3268
43
  Result.startToken();
3269
43
  FormTokenWithChars(Result, End, tok::raw_identifier);
3270
43
  Result.setRawIdentifierData(Start);
3271
43
  PP->LookUpIdentifierInfo(Result);
3272
43
  Result.setFlag(Token::IsEditorPlaceholder);
3273
43
  BufferPtr = End;
3274
43
  return true;
3275
43
}
3276
3277
556M
bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
3278
556M
  if (
PP556M
&& PP->isCodeCompletionEnabled()) {
3279
1.20M
    SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
3280
1.20M
    return Loc == PP->getCodeCompletionLoc();
3281
1.20M
  }
3282
3283
555M
  return false;
3284
556M
}
3285
3286
std::optional<uint32_t> Lexer::tryReadNumericUCN(const char *&StartPtr,
3287
                                                 const char *SlashLoc,
3288
557
                                                 Token *Result) {
3289
557
  unsigned CharSize;
3290
557
  char Kind = getCharAndSize(StartPtr, CharSize);
3291
557
  assert((Kind == 'u' || Kind == 'U') && "expected a UCN");
3292
3293
557
  unsigned NumHexDigits;
3294
557
  if (Kind == 'u')
3295
483
    NumHexDigits = 4;
3296
74
  else if (Kind == 'U')
3297
74
    NumHexDigits = 8;
3298
3299
557
  bool Delimited = false;
3300
557
  bool FoundEndDelimiter = false;
3301
557
  unsigned Count = 0;
3302
557
  bool Diagnose = Result && 
!isLexingRawMode()309
;
3303
3304
557
  if (!LangOpts.CPlusPlus && 
!LangOpts.C99273
) {
3305
5
    if (Diagnose)
3306
3
      Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
3307
5
    return std::nullopt;
3308
5
  }
3309
3310
552
  const char *CurPtr = StartPtr + CharSize;
3311
552
  const char *KindLoc = &CurPtr[-1];
3312
3313
552
  uint32_t CodePoint = 0;
3314
2.88k
  while (Count != NumHexDigits || 
Delimited478
) {
3315
2.42k
    char C = getCharAndSize(CurPtr, CharSize);
3316
2.42k
    if (!Delimited && 
Count == 02.26k
&&
C == '{'552
) {
3317
44
      Delimited = true;
3318
44
      CurPtr += CharSize;
3319
44
      continue;
3320
44
    }
3321
3322
2.38k
    if (Delimited && 
C == '}'162
) {
3323
26
      CurPtr += CharSize;
3324
26
      FoundEndDelimiter = true;
3325
26
      break;
3326
26
    }
3327
3328
2.35k
    unsigned Value = llvm::hexDigitValue(C);
3329
2.35k
    if (Value == -1U) {
3330
60
      if (!Delimited)
3331
48
        break;
3332
12
      if (Diagnose)
3333
12
        Diag(SlashLoc, diag::warn_delimited_ucn_incomplete)
3334
12
            << StringRef(KindLoc, 1);
3335
12
      return std::nullopt;
3336
60
    }
3337
3338
2.29k
    if (CodePoint & 0xF000'0000) {
3339
6
      if (Diagnose)
3340
6
        Diag(KindLoc, diag::err_escape_too_large) << 0;
3341
6
      return std::nullopt;
3342
6
    }
3343
3344
2.29k
    CodePoint <<= 4;
3345
2.29k
    CodePoint |= Value;
3346
2.29k
    CurPtr += CharSize;
3347
2.29k
    Count++;
3348
2.29k
  }
3349
3350
534
  if (Count == 0) {
3351
18
    if (Diagnose)
3352
18
      Diag(SlashLoc, FoundEndDelimiter ? 
diag::warn_delimited_ucn_empty6
3353
18
                                       : 
diag::warn_ucn_escape_no_digits12
)
3354
18
          << StringRef(KindLoc, 1);
3355
18
    return std::nullopt;
3356
18
  }
3357
3358
516
  if (Delimited && 
Kind == 'U'20
) {
3359
0
    if (Diagnose)
3360
0
      Diag(SlashLoc, diag::err_hex_escape_no_digits) << StringRef(KindLoc, 1);
3361
0
    return std::nullopt;
3362
0
  }
3363
3364
516
  if (!Delimited && 
Count != NumHexDigits496
) {
3365
36
    if (Diagnose) {
3366
30
      Diag(SlashLoc, diag::warn_ucn_escape_incomplete);
3367
      // If the user wrote \U1234, suggest a fixit to \u.
3368
30
      if (Count == 4 && 
NumHexDigits == 86
) {
3369
6
        CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
3370
6
        Diag(KindLoc, diag::note_ucn_four_not_eight)
3371
6
            << FixItHint::CreateReplacement(URange, "u");
3372
6
      }
3373
30
    }
3374
36
    return std::nullopt;
3375
36
  }
3376
3377
480
  if (Delimited && 
PP20
) {
3378
20
    Diag(SlashLoc, PP->getLangOpts().CPlusPlus23
3379
20
                       ? 
diag::warn_cxx23_delimited_escape_sequence2
3380
20
                       : 
diag::ext_delimited_escape_sequence18
)
3381
20
        << /*delimited*/ 0 << (PP->getLangOpts().CPlusPlus ? 
19
:
011
);
3382
20
  }
3383
3384
480
  if (Result) {
3385
240
    Result->setFlag(Token::HasUCN);
3386
    // If the UCN contains either a trigraph or a line splicing,
3387
    // we need to call getAndAdvanceChar again to set the appropriate flags
3388
    // on Result.
3389
240
    if (CurPtr - StartPtr == (ptrdiff_t)(Count + 1 + (Delimited ? 
213
:
0227
)))
3390
240
      StartPtr = CurPtr;
3391
0
    else
3392
0
      while (StartPtr != CurPtr)
3393
0
        (void)getAndAdvanceChar(StartPtr, *Result);
3394
240
  } else {
3395
240
    StartPtr = CurPtr;
3396
240
  }
3397
480
  return CodePoint;
3398
516
}
3399
3400
std::optional<uint32_t> Lexer::tryReadNamedUCN(const char *&StartPtr,
3401
                                               const char *SlashLoc,
3402
122
                                               Token *Result) {
3403
122
  unsigned CharSize;
3404
122
  bool Diagnose = Result && 
!isLexingRawMode()83
;
3405
3406
122
  char C = getCharAndSize(StartPtr, CharSize);
3407
122
  assert(C == 'N' && "expected \\N{...}");
3408
3409
122
  const char *CurPtr = StartPtr + CharSize;
3410
122
  const char *KindLoc = &CurPtr[-1];
3411
3412
122
  C = getCharAndSize(CurPtr, CharSize);
3413
122
  if (C != '{') {
3414
7
    if (Diagnose)
3415
6
      Diag(SlashLoc, diag::warn_ucn_escape_incomplete);
3416
7
    return std::nullopt;
3417
7
  }
3418
115
  CurPtr += CharSize;
3419
115
  const char *StartName = CurPtr;
3420
115
  bool FoundEndDelimiter = false;
3421
115
  llvm::SmallVector<char, 30> Buffer;
3422
2.25k
  while (C) {
3423
2.25k
    C = getCharAndSize(CurPtr, CharSize);
3424
2.25k
    CurPtr += CharSize;
3425
2.25k
    if (C == '}') {
3426
101
      FoundEndDelimiter = true;
3427
101
      break;
3428
101
    }
3429
3430
2.15k
    if (isVerticalWhitespace(C))
3431
14
      break;
3432
2.14k
    Buffer.push_back(C);
3433
2.14k
  }
3434
3435
115
  if (!FoundEndDelimiter || 
Buffer.empty()101
) {
3436
20
    if (Diagnose)
3437
19
      Diag(SlashLoc, FoundEndDelimiter ? 
diag::warn_delimited_ucn_empty6
3438
19
                                       : 
diag::warn_delimited_ucn_incomplete13
)
3439
19
          << StringRef(KindLoc, 1);
3440
20
    return std::nullopt;
3441
20
  }
3442
3443
95
  StringRef Name(Buffer.data(), Buffer.size());
3444
95
  std::optional<char32_t> Match =
3445
95
      llvm::sys::unicode::nameToCodepointStrict(Name);
3446
95
  std::optional<llvm::sys::unicode::LooseMatchingResult> LooseMatch;
3447
95
  if (!Match) {
3448
36
    LooseMatch = llvm::sys::unicode::nameToCodepointLooseMatching(Name);
3449
36
    if (Diagnose) {
3450
23
      Diag(StartName, diag::err_invalid_ucn_name)
3451
23
          << StringRef(Buffer.data(), Buffer.size())
3452
23
          << makeCharRange(*this, StartName, CurPtr - CharSize);
3453
23
      if (LooseMatch) {
3454
9
        Diag(StartName, diag::note_invalid_ucn_name_loose_matching)
3455
9
            << FixItHint::CreateReplacement(
3456
9
                   makeCharRange(*this, StartName, CurPtr - CharSize),
3457
9
                   LooseMatch->Name);
3458
9
      }
3459
23
    }
3460
    // We do not offer misspelled character names suggestions here
3461
    // as the set of what would be a valid suggestion depends on context,
3462
    // and we should not make invalid suggestions.
3463
36
  }
3464
3465
95
  if (Diagnose && 
Match49
)
3466
26
    Diag(SlashLoc, PP->getLangOpts().CPlusPlus23
3467
26
                       ? 
diag::warn_cxx23_delimited_escape_sequence4
3468
26
                       : 
diag::ext_delimited_escape_sequence22
)
3469
26
        << /*named*/ 1 << (PP->getLangOpts().CPlusPlus ? 
113
:
013
);
3470
3471
  // If no diagnostic has been emitted yet, likely because we are doing a
3472
  // tentative lexing, we do not want to recover here to make sure the token
3473
  // will not be incorrectly considered valid. This function will be called
3474
  // again and a diagnostic emitted then.
3475
95
  if (LooseMatch && 
Diagnose19
)
3476
9
    Match = LooseMatch->CodePoint;
3477
3478
95
  if (Result) {
3479
57
    Result->setFlag(Token::HasUCN);
3480
    // If the UCN contains either a trigraph or a line splicing,
3481
    // we need to call getAndAdvanceChar again to set the appropriate flags
3482
    // on Result.
3483
57
    if (CurPtr - StartPtr == (ptrdiff_t)(Buffer.size() + 3))
3484
46
      StartPtr = CurPtr;
3485
11
    else
3486
372
      
while (11
StartPtr != CurPtr)
3487
361
        (void)getAndAdvanceChar(StartPtr, *Result);
3488
57
  } else {
3489
38
    StartPtr = CurPtr;
3490
38
  }
3491
95
  return Match ? 
std::optional<uint32_t>(*Match)68
:
std::nullopt27
;
3492
115
}
3493
3494
uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
3495
2.93k
                           Token *Result) {
3496
3497
2.93k
  unsigned CharSize;
3498
2.93k
  std::optional<uint32_t> CodePointOpt;
3499
2.93k
  char Kind = getCharAndSize(StartPtr, CharSize);
3500
2.93k
  if (Kind == 'u' || 
Kind == 'U'2.45k
)
3501
557
    CodePointOpt = tryReadNumericUCN(StartPtr, SlashLoc, Result);
3502
2.37k
  else if (Kind == 'N')
3503
122
    CodePointOpt = tryReadNamedUCN(StartPtr, SlashLoc, Result);
3504
3505
2.93k
  if (!CodePointOpt)
3506
2.38k
    return 0;
3507
3508
548
  uint32_t CodePoint = *CodePointOpt;
3509
3510
  // Don't apply C family restrictions to UCNs in assembly mode
3511
548
  if (LangOpts.AsmPreprocessor)
3512
2
    return CodePoint;
3513
3514
  // C23 6.4.3p2: A universal character name shall not designate a code point
3515
  // where the hexadecimal value is:
3516
  // - in the range D800 through DFFF inclusive; or
3517
  // - greater than 10FFFF.
3518
  // A universal-character-name outside the c-char-sequence of a character
3519
  // constant, or the s-char-sequence of a string-literal shall not designate
3520
  // a control character or a character in the basic character set.
3521
3522
  // C++11 [lex.charset]p2: If the hexadecimal value for a
3523
  //   universal-character-name corresponds to a surrogate code point (in the
3524
  //   range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
3525
  //   if the hexadecimal value for a universal-character-name outside the
3526
  //   c-char-sequence, s-char-sequence, or r-char-sequence of a character or
3527
  //   string literal corresponds to a control character (in either of the
3528
  //   ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
3529
  //   basic source character set, the program is ill-formed.
3530
546
  if (CodePoint < 0xA0) {
3531
    // We don't use isLexingRawMode() here because we need to warn about bad
3532
    // UCNs even when skipping preprocessing tokens in a #if block.
3533
142
    if (Result && 
PP90
) {
3534
90
      if (CodePoint < 0x20 || 
CodePoint >= 0x7F74
)
3535
26
        Diag(BufferPtr, diag::err_ucn_control_character);
3536
64
      else {
3537
64
        char C = static_cast<char>(CodePoint);
3538
64
        Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
3539
64
      }
3540
90
    }
3541
3542
142
    return 0;
3543
404
  } else if (CodePoint >= 0xD800 && 
CodePoint <= 0xDFFF81
) {
3544
    // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
3545
    // We don't use isLexingRawMode() here because we need to diagnose bad
3546
    // UCNs even when skipping preprocessing tokens in a #if block.
3547
5
    if (Result && PP) {
3548
5
      if (LangOpts.CPlusPlus && 
!LangOpts.CPlusPlus112
)
3549
1
        Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
3550
4
      else
3551
4
        Diag(BufferPtr, diag::err_ucn_escape_invalid);
3552
5
    }
3553
5
    return 0;
3554
5
  }
3555
3556
399
  return CodePoint;
3557
546
}
3558
3559
bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
3560
357
                                   const char *CurPtr) {
3561
357
  if (!isLexingRawMode() && 
!PP->isPreprocessedOutput()252
&&
3562
357
      
isUnicodeWhitespace(C)224
) {
3563
8
    Diag(BufferPtr, diag::ext_unicode_whitespace)
3564
8
      << makeCharRange(*this, BufferPtr, CurPtr);
3565
3566
8
    Result.setFlag(Token::LeadingSpace);
3567
8
    return true;
3568
8
  }
3569
349
  return false;
3570
357
}
3571
3572
38.6M
void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
3573
38.6M
  IsAtStartOfLine = Result.isAtStartOfLine();
3574
38.6M
  HasLeadingSpace = Result.hasLeadingSpace();
3575
38.6M
  HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
3576
  // Note that this doesn't affect IsAtPhysicalStartOfLine.
3577
38.6M
}
3578
3579
1.66G
bool Lexer::Lex(Token &Result) {
3580
1.66G
  assert(!isDependencyDirectivesLexer());
3581
3582
  // Start a new token.
3583
1.66G
  Result.startToken();
3584
3585
  // Set up misc whitespace flags for LexTokenInternal.
3586
1.66G
  if (IsAtStartOfLine) {
3587
137M
    Result.setFlag(Token::StartOfLine);
3588
137M
    IsAtStartOfLine = false;
3589
137M
  }
3590
3591
1.66G
  if (HasLeadingSpace) {
3592
1.17M
    Result.setFlag(Token::LeadingSpace);
3593
1.17M
    HasLeadingSpace = false;
3594
1.17M
  }
3595
3596
1.66G
  if (HasLeadingEmptyMacro) {
3597
1.43M
    Result.setFlag(Token::LeadingEmptyMacro);
3598
1.43M
    HasLeadingEmptyMacro = false;
3599
1.43M
  }
3600
3601
1.66G
  bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
3602
1.66G
  IsAtPhysicalStartOfLine = false;
3603
1.66G
  bool isRawLex = isLexingRawMode();
3604
1.66G
  (void) isRawLex;
3605
1.66G
  bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
3606
  // (After the LexTokenInternal call, the lexer might be destroyed.)
3607
1.66G
  assert((returnedToken || !isRawLex) && "Raw lex must succeed");
3608
1.66G
  return returnedToken;
3609
1.66G
}
3610
3611
/// LexTokenInternal - This implements a simple C family lexer.  It is an
3612
/// extremely performance critical piece of code.  This assumes that the buffer
3613
/// has a null character at the end of the file.  This returns a preprocessing
3614
/// token, not a normal token, as such, it is an internal interface.  It assumes
3615
/// that the Flags of result have been cleared before calling this.
3616
1.66G
bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
3617
1.83G
LexStart:
3618
1.83G
  assert(!Result.needsCleaning() && "Result needs cleaning");
3619
1.83G
  assert(!Result.hasPtrData() && "Result has not been reset");
3620
3621
  // CurPtr - Cache BufferPtr in an automatic variable.
3622
1.83G
  const char *CurPtr = BufferPtr;
3623
3624
  // Small amounts of horizontal whitespace is very common between tokens.
3625
1.83G
  if (isHorizontalWhitespace(*CurPtr)) {
3626
722M
    do {
3627
722M
      ++CurPtr;
3628
722M
    } while (isHorizontalWhitespace(*CurPtr));
3629
3630
    // If we are keeping whitespace and other tokens, just return what we just
3631
    // skipped.  The next lexer invocation will return the token after the
3632
    // whitespace.
3633
467M
    if (isKeepWhitespaceMode()) {
3634
574k
      FormTokenWithChars(Result, CurPtr, tok::unknown);
3635
      // FIXME: The next token will not have LeadingSpace set.
3636
574k
      return true;
3637
574k
    }
3638
3639
467M
    BufferPtr = CurPtr;
3640
467M
    Result.setFlag(Token::LeadingSpace);
3641
467M
  }
3642
3643
1.83G
  unsigned SizeTmp, SizeTmp2;   // Temporaries for use in cases below.
3644
3645
  // Read a character, advancing over it.
3646
1.83G
  char Char = getAndAdvanceChar(CurPtr, Result);
3647
1.83G
  tok::TokenKind Kind;
3648
3649
1.83G
  if (!isVerticalWhitespace(Char))
3650
1.61G
    NewLinePtr = nullptr;
3651
3652
1.83G
  switch (Char) {
3653
3.21M
  case 0:  // Null.
3654
    // Found end of file?
3655
3.21M
    if (CurPtr-1 == BufferEnd)
3656
3.21M
      return LexEndOfFile(Result, CurPtr-1);
3657
3658
    // Check if we are performing code completion.
3659
1.15k
    if (isCodeCompletionPoint(CurPtr-1)) {
3660
      // Return the code-completion token.
3661
1.14k
      Result.startToken();
3662
1.14k
      FormTokenWithChars(Result, CurPtr, tok::code_completion);
3663
1.14k
      return true;
3664
1.14k
    }
3665
3666
5
    if (!isLexingRawMode())
3667
2
      Diag(CurPtr-1, diag::null_in_file);
3668
5
    Result.setFlag(Token::LeadingSpace);
3669
5
    if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3670
0
      return true; // KeepWhitespaceMode
3671
3672
    // We know the lexer hasn't changed, so just try again with this lexer.
3673
    // (We manually eliminate the tail call to avoid recursion.)
3674
5
    goto LexNextToken;
3675
3676
5
  case 26:  // DOS & CP/M EOF: "^Z".
3677
    // If we're in Microsoft extensions mode, treat this as end of file.
3678
1
    if (LangOpts.MicrosoftExt) {
3679
1
      if (!isLexingRawMode())
3680
1
        Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
3681
1
      return LexEndOfFile(Result, CurPtr-1);
3682
1
    }
3683
3684
    // If Microsoft extensions are disabled, this is just random garbage.
3685
0
    Kind = tok::unknown;
3686
0
    break;
3687
3688
2.72k
  case '\r':
3689
2.72k
    if (CurPtr[0] == '\n')
3690
2.72k
      (void)getAndAdvanceChar(CurPtr, Result);
3691
2.72k
    [[fallthrough]];
3692
217M
  case '\n':
3693
    // If we are inside a preprocessor directive and we see the end of line,
3694
    // we know we are done with the directive, so return an EOD token.
3695
217M
    if (ParsingPreprocessorDirective) {
3696
      // Done parsing the "line".
3697
69.8M
      ParsingPreprocessorDirective = false;
3698
3699
      // Restore comment saving mode, in case it was disabled for directive.
3700
69.8M
      if (PP)
3701
69.7M
        resetExtendedTokenMode();
3702
3703
      // Since we consumed a newline, we are back at the start of a line.
3704
69.8M
      IsAtStartOfLine = true;
3705
69.8M
      IsAtPhysicalStartOfLine = true;
3706
69.8M
      NewLinePtr = CurPtr - 1;
3707
3708
69.8M
      Kind = tok::eod;
3709
69.8M
      break;
3710
69.8M
    }
3711
3712
    // No leading whitespace seen so far.
3713
147M
    Result.clearFlag(Token::LeadingSpace);
3714
3715
147M
    if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3716
163k
      return true; // KeepWhitespaceMode
3717
3718
    // We only saw whitespace, so just try again with this lexer.
3719
    // (We manually eliminate the tail call to avoid recursion.)
3720
147M
    goto LexNextToken;
3721
147M
  case ' ':
3722
6.31M
  case '\t':
3723
6.31M
  case '\f':
3724
6.31M
  case '\v':
3725
8.14M
  SkipHorizontalWhitespace:
3726
8.14M
    Result.setFlag(Token::LeadingSpace);
3727
8.14M
    if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3728
3.18k
      return true; // KeepWhitespaceMode
3729
3730
48.6M
  SkipIgnoredUnits:
3731
48.6M
    CurPtr = BufferPtr;
3732
3733
    // If the next token is obviously a // or /* */ comment, skip it efficiently
3734
    // too (without going through the big switch stmt).
3735
48.6M
    if (CurPtr[0] == '/' && 
CurPtr[1] == '/'35.0M
&&
!inKeepCommentMode()35.0M
&&
3736
48.6M
        
LineComment35.0M
&&
(35.0M
LangOpts.CPlusPlus35.0M
||
!LangOpts.TraditionalCPP12.0M
)) {
3737
35.0M
      if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3738
0
        return true; // There is a token to return.
3739
35.0M
      goto SkipIgnoredUnits;
3740
35.0M
    } else 
if (13.5M
CurPtr[0] == '/'13.5M
&&
CurPtr[1] == '*'6.52k
&&
!inKeepCommentMode()5.83k
) {
3741
5.83k
      if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3742
0
        return true; // There is a token to return.
3743
5.83k
      goto SkipIgnoredUnits;
3744
13.5M
    } else if (isHorizontalWhitespace(*CurPtr)) {
3745
1.82M
      goto SkipHorizontalWhitespace;
3746
1.82M
    }
3747
    // We only saw whitespace, so just try again with this lexer.
3748
    // (We manually eliminate the tail call to avoid recursion.)
3749
11.6M
    goto LexNextToken;
3750
3751
  // C99 6.4.4.1: Integer Constants.
3752
  // C99 6.4.4.2: Floating Constants.
3753
52.0M
  
case '0': 8.32M
case '1': 31.6M
case '2': 42.4M
case '3': 47.8M
case '4':
3754
64.3M
  
case '5': 54.1M
case '6': 57.4M
case '7': 59.0M
case '8': 61.5M
case '9':
3755
    // Notify MIOpt that we read a non-whitespace/non-comment token.
3756
64.3M
    MIOpt.ReadToken();
3757
64.3M
    return LexNumericConstant(Result, CurPtr);
3758
3759
  // Identifier (e.g., uber), or
3760
  // UTF-8 (C23/C++17) or UTF-16 (C11/C++11) character literal, or
3761
  // UTF-8 or UTF-16 string literal (C11/C++11).
3762
17.7M
  case 'u':
3763
    // Notify MIOpt that we read a non-whitespace/non-comment token.
3764
17.7M
    MIOpt.ReadToken();
3765
3766
17.7M
    if (LangOpts.CPlusPlus11 || 
LangOpts.C1110.4M
) {
3767
17.0M
      Char = getCharAndSize(CurPtr, SizeTmp);
3768
3769
      // UTF-16 string literal
3770
17.0M
      if (Char == '"')
3771
219
        return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3772
219
                                tok::utf16_string_literal);
3773
3774
      // UTF-16 character constant
3775
17.0M
      if (Char == '\'')
3776
198
        return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3777
198
                               tok::utf16_char_constant);
3778
3779
      // UTF-16 raw string literal
3780
17.0M
      if (Char == 'R' && 
LangOpts.CPlusPlus1173
&&
3781
17.0M
          
getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"'65
)
3782
57
        return LexRawStringLiteral(Result,
3783
57
                               ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3784
57
                                           SizeTmp2, Result),
3785
57
                               tok::utf16_string_literal);
3786
3787
17.0M
      if (Char == '8') {
3788
6.12k
        char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3789
3790
        // UTF-8 string literal
3791
6.12k
        if (Char2 == '"')
3792
498
          return LexStringLiteral(Result,
3793
498
                               ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3794
498
                                           SizeTmp2, Result),
3795
498
                               tok::utf8_string_literal);
3796
5.62k
        if (Char2 == '\'' && 
(301
LangOpts.CPlusPlus17301
||
LangOpts.C2362
))
3797
259
          return LexCharConstant(
3798
259
              Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3799
259
                                  SizeTmp2, Result),
3800
259
              tok::utf8_char_constant);
3801
3802
5.36k
        if (Char2 == 'R' && 
LangOpts.CPlusPlus1145
) {
3803
37
          unsigned SizeTmp3;
3804
37
          char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3805
          // UTF-8 raw string literal
3806
37
          if (Char3 == '"') {
3807
29
            return LexRawStringLiteral(Result,
3808
29
                   ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3809
29
                                           SizeTmp2, Result),
3810
29
                               SizeTmp3, Result),
3811
29
                   tok::utf8_string_literal);
3812
29
          }
3813
37
        }
3814
5.36k
      }
3815
17.0M
    }
3816
3817
    // treat u like the start of an identifier.
3818
17.7M
    return LexIdentifierContinue(Result, CurPtr);
3819
3820
2.34M
  case 'U': // Identifier (e.g. Uber) or C11/C++11 UTF-32 string literal
3821
    // Notify MIOpt that we read a non-whitespace/non-comment token.
3822
2.34M
    MIOpt.ReadToken();
3823
3824
2.34M
    if (LangOpts.CPlusPlus11 || 
LangOpts.C111.53M
) {
3825
2.30M
      Char = getCharAndSize(CurPtr, SizeTmp);
3826
3827
      // UTF-32 string literal
3828
2.30M
      if (Char == '"')
3829
192
        return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3830
192
                                tok::utf32_string_literal);
3831
3832
      // UTF-32 character constant
3833
2.30M
      if (Char == '\'')
3834
543
        return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3835
543
                               tok::utf32_char_constant);
3836
3837
      // UTF-32 raw string literal
3838
2.29M
      if (Char == 'R' && 
LangOpts.CPlusPlus1131.3k
&&
3839
2.29M
          
getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"'3.61k
)
3840
31
        return LexRawStringLiteral(Result,
3841
31
                               ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3842
31
                                           SizeTmp2, Result),
3843
31
                               tok::utf32_string_literal);
3844
2.29M
    }
3845
3846
    // treat U like the start of an identifier.
3847
2.34M
    return LexIdentifierContinue(Result, CurPtr);
3848
3849
810k
  case 'R': // Identifier or C++0x raw string literal
3850
    // Notify MIOpt that we read a non-whitespace/non-comment token.
3851
810k
    MIOpt.ReadToken();
3852
3853
810k
    if (LangOpts.CPlusPlus11) {
3854
152k
      Char = getCharAndSize(CurPtr, SizeTmp);
3855
3856
152k
      if (Char == '"')
3857
493
        return LexRawStringLiteral(Result,
3858
493
                                   ConsumeChar(CurPtr, SizeTmp, Result),
3859
493
                                   tok::string_literal);
3860
152k
    }
3861
3862
    // treat R like the start of an identifier.
3863
809k
    return LexIdentifierContinue(Result, CurPtr);
3864
3865
555k
  case 'L':   // Identifier (Loony) or wide literal (L'x' or L"xyz").
3866
    // Notify MIOpt that we read a non-whitespace/non-comment token.
3867
555k
    MIOpt.ReadToken();
3868
555k
    Char = getCharAndSize(CurPtr, SizeTmp);
3869
3870
    // Wide string literal.
3871
555k
    if (Char == '"')
3872
2.40k
      return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3873
2.40k
                              tok::wide_string_literal);
3874
3875
    // Wide raw string literal.
3876
552k
    if (LangOpts.CPlusPlus11 && 
Char == 'R'277k
&&
3877
552k
        
getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"'111
)
3878
23
      return LexRawStringLiteral(Result,
3879
23
                               ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3880
23
                                           SizeTmp2, Result),
3881
23
                               tok::wide_string_literal);
3882
3883
    // Wide character constant.
3884
552k
    if (Char == '\'')
3885
2.70k
      return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3886
2.70k
                             tok::wide_char_constant);
3887
    // FALL THROUGH, treating L like the start of an identifier.
3888
552k
    
[[fallthrough]];549k
3889
3890
  // C99 6.4.2: Identifiers.
3891
16.2M
  
case 'A': 4.31M
case 'B': 5.61M
case 'C': 12.8M
case 'D': 14.2M
case 'E': 14.6M
case 'F': 15.6M
case 'G':
3892
24.3M
  
case 'H': 16.5M
case 'I': 18.3M
case 'J': 18.4M
case 'K': /*'L'*/18.6M
case 'M': 20.6M
case 'N':
3893
29.3M
  
case 'O': 25.6M
case 'P': 26.3M
case 'Q': /*'R'*/26.3M
case 'S': 28.1M
case 'T': /*'U'*/
3894
30.3M
  
case 'V': 29.6M
case 'W': 29.9M
case 'X': 30.2M
case 'Y': 30.3M
case 'Z':
3895
150M
  
case 'a': 39.5M
case 'b': 43.4M
case 'c': 62.9M
case 'd': 124M
case 'e': 141M
case 'f': 149M
case 'g':
3896
218M
  
case 'h': 153M
case 'i': 198M
case 'j': 198M
case 'k': 202M
case 'l': 206M
case 'm': 216M
case 'n':
3897
366M
  
case 'o': 222M
case 'p': 228M
case 'q': 229M
case 'r': 237M
case 's': 354M
case 't': /*'u'*/
3898
384M
  
case 'v': 380M
case 'w': 382M
case 'x': 384M
case 'y': 384M
case 'z':
3899
682M
  case '_':
3900
    // Notify MIOpt that we read a non-whitespace/non-comment token.
3901
682M
    MIOpt.ReadToken();
3902
682M
    return LexIdentifierContinue(Result, CurPtr);
3903
3904
27.6k
  case '$':   // $ in identifiers.
3905
27.6k
    if (LangOpts.DollarIdents) {
3906
27.6k
      if (!isLexingRawMode())
3907
26.7k
        Diag(CurPtr-1, diag::ext_dollar_in_identifier);
3908
      // Notify MIOpt that we read a non-whitespace/non-comment token.
3909
27.6k
      MIOpt.ReadToken();
3910
27.6k
      return LexIdentifierContinue(Result, CurPtr);
3911
27.6k
    }
3912
3913
13
    Kind = tok::unknown;
3914
13
    break;
3915
3916
  // C99 6.4.4: Character Constants.
3917
966k
  case '\'':
3918
    // Notify MIOpt that we read a non-whitespace/non-comment token.
3919
966k
    MIOpt.ReadToken();
3920
966k
    return LexCharConstant(Result, CurPtr, tok::char_constant);
3921
3922
  // C99 6.4.5: String Literals.
3923
13.5M
  case '"':
3924
    // Notify MIOpt that we read a non-whitespace/non-comment token.
3925
13.5M
    MIOpt.ReadToken();
3926
13.5M
    return LexStringLiteral(Result, CurPtr,
3927
13.5M
                            ParsingFilename ? 
tok::header_name85.5k
3928
13.5M
                                            : 
tok::string_literal13.4M
);
3929
3930
  // C99 6.4.6: Punctuators.
3931
204k
  case '?':
3932
204k
    Kind = tok::question;
3933
204k
    break;
3934
4.39M
  case '[':
3935
4.39M
    Kind = tok::l_square;
3936
4.39M
    break;
3937
4.39M
  case ']':
3938
4.39M
    Kind = tok::r_square;
3939
4.39M
    break;
3940
189M
  case '(':
3941
189M
    Kind = tok::l_paren;
3942
189M
    break;
3943
238M
  case ')':
3944
238M
    Kind = tok::r_paren;
3945
238M
    break;
3946
13.6M
  case '{':
3947
13.6M
    Kind = tok::l_brace;
3948
13.6M
    break;
3949
13.6M
  case '}':
3950
13.6M
    Kind = tok::r_brace;
3951
13.6M
    break;
3952
5.63M
  case '.':
3953
5.63M
    Char = getCharAndSize(CurPtr, SizeTmp);
3954
5.63M
    if (Char >= '0' && 
Char <= '9'4.03M
) {
3955
      // Notify MIOpt that we read a non-whitespace/non-comment token.
3956
1.10k
      MIOpt.ReadToken();
3957
3958
1.10k
      return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
3959
5.63M
    } else if (LangOpts.CPlusPlus && 
Char == '*'3.60M
) {
3960
11.3k
      Kind = tok::periodstar;
3961
11.3k
      CurPtr += SizeTmp;
3962
5.62M
    } else if (Char == '.' &&
3963
5.62M
               
getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.'1.56M
) {
3964
1.55M
      Kind = tok::ellipsis;
3965
1.55M
      CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3966
1.55M
                           SizeTmp2, Result);
3967
4.06M
    } else {
3968
4.06M
      Kind = tok::period;
3969
4.06M
    }
3970
5.63M
    break;
3971
5.63M
  case '&':
3972
5.17M
    Char = getCharAndSize(CurPtr, SizeTmp);
3973
5.17M
    if (Char == '&') {
3974
2.01M
      Kind = tok::ampamp;
3975
2.01M
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3976
3.15M
    } else if (Char == '=') {
3977
26.5k
      Kind = tok::ampequal;
3978
26.5k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3979
3.12M
    } else {
3980
3.12M
      Kind = tok::amp;
3981
3.12M
    }
3982
5.17M
    break;
3983
11.8M
  case '*':
3984
11.8M
    if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3985
10.5k
      Kind = tok::starequal;
3986
10.5k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3987
11.7M
    } else {
3988
11.7M
      Kind = tok::star;
3989
11.7M
    }
3990
11.8M
    break;
3991
1.88M
  case '+':
3992
1.88M
    Char = getCharAndSize(CurPtr, SizeTmp);
3993
1.88M
    if (Char == '+') {
3994
676k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3995
676k
      Kind = tok::plusplus;
3996
1.20M
    } else if (Char == '=') {
3997
126k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3998
126k
      Kind = tok::plusequal;
3999
1.07M
    } else {
4000
1.07M
      Kind = tok::plus;
4001
1.07M
    }
4002
1.88M
    break;
4003
4.33M
  case '-':
4004
4.33M
    Char = getCharAndSize(CurPtr, SizeTmp);
4005
4.33M
    if (Char == '-') {      // --
4006
137k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4007
137k
      Kind = tok::minusminus;
4008
4.20M
    } else if (Char == '>' && 
LangOpts.CPlusPlus907k
&&
4009
4.20M
               
getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*'819k
) { // C++ ->*
4010
1.78k
      CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4011
1.78k
                           SizeTmp2, Result);
4012
1.78k
      Kind = tok::arrowstar;
4013
4.19M
    } else if (Char == '>') {   // ->
4014
906k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4015
906k
      Kind = tok::arrow;
4016
3.29M
    } else if (Char == '=') {   // -=
4017
59.2k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4018
59.2k
      Kind = tok::minusequal;
4019
3.23M
    } else {
4020
3.23M
      Kind = tok::minus;
4021
3.23M
    }
4022
4.33M
    break;
4023
213k
  case '~':
4024
213k
    Kind = tok::tilde;
4025
213k
    break;
4026
1.81M
  case '!':
4027
1.81M
    if (getCharAndSize(CurPtr, SizeTmp) == '=') {
4028
426k
      Kind = tok::exclaimequal;
4029
426k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4030
1.38M
    } else {
4031
1.38M
      Kind = tok::exclaim;
4032
1.38M
    }
4033
1.81M
    break;
4034
16.0M
  case '/':
4035
    // 6.4.9: Comments
4036
16.0M
    Char = getCharAndSize(CurPtr, SizeTmp);
4037
16.0M
    if (Char == '/') {         // Line comment.
4038
      // Even if Line comments are disabled (e.g. in C89 mode), we generally
4039
      // want to lex this as a comment.  There is one problem with this though,
4040
      // that in one particular corner case, this can change the behavior of the
4041
      // resultant program.  For example, In  "foo //**/ bar", C89 would lex
4042
      // this as "foo / bar" and languages with Line comments would lex it as
4043
      // "foo".  Check to see if the character after the second slash is a '*'.
4044
      // If so, we will lex that as a "/" instead of the start of a comment.
4045
      // However, we never do this if we are just preprocessing.
4046
5.44M
      bool TreatAsComment =
4047
5.44M
          LineComment && 
(5.44M
LangOpts.CPlusPlus5.44M
||
!LangOpts.TraditionalCPP1.72M
);
4048
5.44M
      if (!TreatAsComment)
4049
4.70k
        if (!(PP && 
PP->isPreprocessedOutput()4.69k
))
4050
4.62k
          TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
4051
4052
5.44M
      if (TreatAsComment) {
4053
5.44M
        if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
4054
5.44M
                            TokAtPhysicalStartOfLine))
4055
60.2k
          return true; // There is a token to return.
4056
4057
        // It is common for the tokens immediately after a // comment to be
4058
        // whitespace (indentation for the next line).  Instead of going through
4059
        // the big switch, handle it efficiently now.
4060
5.38M
        goto SkipIgnoredUnits;
4061
5.44M
      }
4062
5.44M
    }
4063
4064
10.5M
    if (Char == '*') {  // /**/ comment.
4065
10.2M
      if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
4066
10.2M
                           TokAtPhysicalStartOfLine))
4067
6.63k
        return true; // There is a token to return.
4068
4069
      // We only saw whitespace, so just try again with this lexer.
4070
      // (We manually eliminate the tail call to avoid recursion.)
4071
10.2M
      goto LexNextToken;
4072
10.2M
    }
4073
4074
309k
    if (Char == '=') {
4075
9.86k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4076
9.86k
      Kind = tok::slashequal;
4077
299k
    } else {
4078
299k
      Kind = tok::slash;
4079
299k
    }
4080
309k
    break;
4081
43.2k
  case '%':
4082
43.2k
    Char = getCharAndSize(CurPtr, SizeTmp);
4083
43.2k
    if (Char == '=') {
4084
5.61k
      Kind = tok::percentequal;
4085
5.61k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4086
37.6k
    } else if (LangOpts.Digraphs && 
Char == '>'36.5k
) {
4087
54
      Kind = tok::r_brace;                             // '%>' -> '}'
4088
54
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4089
37.5k
    } else if (LangOpts.Digraphs && 
Char == ':'36.4k
) {
4090
33
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4091
33
      Char = getCharAndSize(CurPtr, SizeTmp);
4092
33
      if (Char == '%' && 
getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':'6
) {
4093
6
        Kind = tok::hashhash;                          // '%:%:' -> '##'
4094
6
        CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4095
6
                             SizeTmp2, Result);
4096
27
      } else if (Char == '@' && 
LangOpts.MicrosoftExt0
) {// %:@ -> #@ -> Charize
4097
0
        CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4098
0
        if (!isLexingRawMode())
4099
0
          Diag(BufferPtr, diag::ext_charize_microsoft);
4100
0
        Kind = tok::hashat;
4101
27
      } else {                                         // '%:' -> '#'
4102
        // We parsed a # character.  If this occurs at the start of the line,
4103
        // it's actually the start of a preprocessing directive.  Callback to
4104
        // the preprocessor to handle it.
4105
        // TODO: -fpreprocessed mode??
4106
27
        if (TokAtPhysicalStartOfLine && !LexingRawMode && 
!Is_PragmaLexer12
)
4107
12
          goto HandleDirective;
4108
4109
15
        Kind = tok::hash;
4110
15
      }
4111
37.5k
    } else {
4112
37.5k
      Kind = tok::percent;
4113
37.5k
    }
4114
43.2k
    break;
4115
16.0M
  case '<':
4116
16.0M
    Char = getCharAndSize(CurPtr, SizeTmp);
4117
16.0M
    if (ParsingFilename) {
4118
3.74M
      return LexAngledStringLiteral(Result, CurPtr);
4119
12.2M
    } else if (Char == '<') {
4120
422k
      char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
4121
422k
      if (After == '=') {
4122
6.54k
        Kind = tok::lesslessequal;
4123
6.54k
        CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4124
6.54k
                             SizeTmp2, Result);
4125
415k
      } else if (After == '<' && 
IsStartOfConflictMarker(CurPtr-1)444
) {
4126
        // If this is actually a '<<<<<<<' version control conflict marker,
4127
        // recognize it as such and recover nicely.
4128
2
        goto LexNextToken;
4129
415k
      } else if (After == '<' && 
HandleEndOfConflictMarker(CurPtr-1)442
) {
4130
        // If this is '<<<<' and we're in a Perforce-style conflict marker,
4131
        // ignore it.
4132
0
        goto LexNextToken;
4133
415k
      } else if (LangOpts.CUDA && 
After == '<'227
) {
4134
201
        Kind = tok::lesslessless;
4135
201
        CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4136
201
                             SizeTmp2, Result);
4137
415k
      } else {
4138
415k
        CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4139
415k
        Kind = tok::lessless;
4140
415k
      }
4141
11.8M
    } else if (Char == '=') {
4142
228k
      char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
4143
228k
      if (After == '>') {
4144
36.0k
        if (LangOpts.CPlusPlus20) {
4145
1.78k
          if (!isLexingRawMode())
4146
1.50k
            Diag(BufferPtr, diag::warn_cxx17_compat_spaceship);
4147
1.78k
          CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4148
1.78k
                               SizeTmp2, Result);
4149
1.78k
          Kind = tok::spaceship;
4150
1.78k
          break;
4151
1.78k
        }
4152
        // Suggest adding a space between the '<=' and the '>' to avoid a
4153
        // change in semantics if this turns up in C++ <=17 mode.
4154
34.2k
        if (LangOpts.CPlusPlus && !isLexingRawMode()) {
4155
13
          Diag(BufferPtr, diag::warn_cxx20_compat_spaceship)
4156
13
            << FixItHint::CreateInsertion(
4157
13
                   getSourceLocation(CurPtr + SizeTmp, SizeTmp2), " ");
4158
13
        }
4159
34.2k
      }
4160
226k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4161
226k
      Kind = tok::lessequal;
4162
11.6M
    } else if (LangOpts.Digraphs && 
Char == ':'11.4M
) { // '<:' -> '['
4163
650
      if (LangOpts.CPlusPlus11 &&
4164
650
          
getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':'621
) {
4165
        // C++0x [lex.pptoken]p3:
4166
        //  Otherwise, if the next three characters are <:: and the subsequent
4167
        //  character is neither : nor >, the < is treated as a preprocessor
4168
        //  token by itself and not as the first character of the alternative
4169
        //  token <:.
4170
600
        unsigned SizeTmp3;
4171
600
        char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
4172
600
        if (After != ':' && 
After != '>'593
) {
4173
592
          Kind = tok::less;
4174
592
          if (!isLexingRawMode())
4175
535
            Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
4176
592
          break;
4177
592
        }
4178
600
      }
4179
4180
58
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4181
58
      Kind = tok::l_square;
4182
11.6M
    } else if (LangOpts.Digraphs && 
Char == '%'11.4M
) { // '<%' -> '{'
4183
53
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4184
53
      Kind = tok::l_brace;
4185
11.6M
    } else if (Char == '#' && /*Not a trigraph*/ 
SizeTmp == 147
&&
4186
11.6M
               
lexEditorPlaceholder(Result, CurPtr)45
) {
4187
43
      return true;
4188
11.6M
    } else {
4189
11.6M
      Kind = tok::less;
4190
11.6M
    }
4191
12.2M
    break;
4192
12.2M
  case '>':
4193
12.0M
    Char = getCharAndSize(CurPtr, SizeTmp);
4194
12.0M
    if (Char == '=') {
4195
999k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4196
999k
      Kind = tok::greaterequal;
4197
11.0M
    } else if (Char == '>') {
4198
408k
      char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
4199
408k
      if (After == '=') {
4200
4.60k
        CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4201
4.60k
                             SizeTmp2, Result);
4202
4.60k
        Kind = tok::greatergreaterequal;
4203
404k
      } else if (After == '>' && 
IsStartOfConflictMarker(CurPtr-1)25.1k
) {
4204
        // If this is actually a '>>>>' conflict marker, recognize it as such
4205
        // and recover nicely.
4206
2
        goto LexNextToken;
4207
404k
      } else if (After == '>' && 
HandleEndOfConflictMarker(CurPtr-1)25.1k
) {
4208
        // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
4209
0
        goto LexNextToken;
4210
404k
      } else if (LangOpts.CUDA && 
After == '>'269
) {
4211
213
        Kind = tok::greatergreatergreater;
4212
213
        CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4213
213
                             SizeTmp2, Result);
4214
404k
      } else {
4215
404k
        CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4216
404k
        Kind = tok::greatergreater;
4217
404k
      }
4218
10.6M
    } else {
4219
10.6M
      Kind = tok::greater;
4220
10.6M
    }
4221
12.0M
    break;
4222
12.0M
  case '^':
4223
119k
    Char = getCharAndSize(CurPtr, SizeTmp);
4224
119k
    if (Char == '=') {
4225
12.7k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4226
12.7k
      Kind = tok::caretequal;
4227
107k
    } else if (LangOpts.OpenCL && 
Char == '^'802
) {
4228
2
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4229
2
      Kind = tok::caretcaret;
4230
107k
    } else {
4231
107k
      Kind = tok::caret;
4232
107k
    }
4233
119k
    break;
4234
1.06M
  case '|':
4235
1.06M
    Char = getCharAndSize(CurPtr, SizeTmp);
4236
1.06M
    if (Char == '=') {
4237
62.4k
      Kind = tok::pipeequal;
4238
62.4k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4239
1.00M
    } else if (Char == '|') {
4240
      // If this is '|||||||' and we're in a conflict marker, ignore it.
4241
773k
      if (CurPtr[1] == '|' && 
HandleEndOfConflictMarker(CurPtr-1)64
)
4242
1
        goto LexNextToken;
4243
773k
      Kind = tok::pipepipe;
4244
773k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4245
773k
    } else {
4246
233k
      Kind = tok::pipe;
4247
233k
    }
4248
1.06M
    break;
4249
9.27M
  case ':':
4250
9.27M
    Char = getCharAndSize(CurPtr, SizeTmp);
4251
9.27M
    if (LangOpts.Digraphs && 
Char == '>'9.13M
) {
4252
33
      Kind = tok::r_square; // ':>' -> ']'
4253
33
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4254
9.27M
    } else if (Char == ':') {
4255
6.46M
      Kind = tok::coloncolon;
4256
6.46M
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4257
6.46M
    } else {
4258
2.81M
      Kind = tok::colon;
4259
2.81M
    }
4260
9.27M
    break;
4261
60.1M
  case ';':
4262
60.1M
    Kind = tok::semi;
4263
60.1M
    break;
4264
22.2M
  case '=':
4265
22.2M
    Char = getCharAndSize(CurPtr, SizeTmp);
4266
22.2M
    if (Char == '=') {
4267
      // If this is '====' and we're in a conflict marker, ignore it.
4268
705k
      if (CurPtr[1] == '=' && 
HandleEndOfConflictMarker(CurPtr-1)112
)
4269
2
        goto LexNextToken;
4270
4271
705k
      Kind = tok::equalequal;
4272
705k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4273
21.5M
    } else {
4274
21.5M
      Kind = tok::equal;
4275
21.5M
    }
4276
22.2M
    break;
4277
116M
  case ',':
4278
116M
    Kind = tok::comma;
4279
116M
    break;
4280
76.9M
  case '#':
4281
76.9M
    Char = getCharAndSize(CurPtr, SizeTmp);
4282
76.9M
    if (Char == '#') {
4283
173k
      Kind = tok::hashhash;
4284
173k
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4285
76.7M
    } else if (Char == '@' && 
LangOpts.MicrosoftExt3
) { // #@ -> Charize
4286
3
      Kind = tok::hashat;
4287
3
      if (!isLexingRawMode())
4288
3
        Diag(BufferPtr, diag::ext_charize_microsoft);
4289
3
      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4290
76.7M
    } else {
4291
      // We parsed a # character.  If this occurs at the start of the line,
4292
      // it's actually the start of a preprocessing directive.  Callback to
4293
      // the preprocessor to handle it.
4294
      // TODO: -fpreprocessed mode??
4295
76.7M
      if (TokAtPhysicalStartOfLine && 
!LexingRawMode76.7M
&&
!Is_PragmaLexer61.6M
)
4296
61.6M
        goto HandleDirective;
4297
4298
15.0M
      Kind = tok::hash;
4299
15.0M
    }
4300
15.2M
    break;
4301
4302
15.2M
  case '@':
4303
    // Objective C support.
4304
752k
    if (
CurPtr[-1] == '@'752k
&& LangOpts.ObjC)
4305
751k
      Kind = tok::at;
4306
516
    else
4307
516
      Kind = tok::unknown;
4308
752k
    break;
4309
4310
  // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
4311
2.62k
  case '\\':
4312
2.62k
    if (!LangOpts.AsmPreprocessor) {
4313
2.62k
      if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
4314
184
        if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
4315
0
          if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
4316
0
            return true; // KeepWhitespaceMode
4317
4318
          // We only saw whitespace, so just try again with this lexer.
4319
          // (We manually eliminate the tail call to avoid recursion.)
4320
0
          goto LexNextToken;
4321
0
        }
4322
4323
184
        return LexUnicodeIdentifierStart(Result, CodePoint, CurPtr);
4324
184
      }
4325
2.62k
    }
4326
4327
2.44k
    Kind = tok::unknown;
4328
2.44k
    break;
4329
4330
411
  default: {
4331
411
    if (isASCII(Char)) {
4332
172
      Kind = tok::unknown;
4333
172
      break;
4334
172
    }
4335
4336
239
    llvm::UTF32 CodePoint;
4337
4338
    // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
4339
    // an escaped newline.
4340
239
    --CurPtr;
4341
239
    llvm::ConversionResult Status =
4342
239
        llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
4343
239
                                  (const llvm::UTF8 *)BufferEnd,
4344
239
                                  &CodePoint,
4345
239
                                  llvm::strictConversion);
4346
239
    if (Status == llvm::conversionOK) {
4347
173
      if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
4348
8
        if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
4349
0
          return true; // KeepWhitespaceMode
4350
4351
        // We only saw whitespace, so just try again with this lexer.
4352
        // (We manually eliminate the tail call to avoid recursion.)
4353
8
        goto LexNextToken;
4354
8
      }
4355
165
      return LexUnicodeIdentifierStart(Result, CodePoint, CurPtr);
4356
173
    }
4357
4358
66
    if (isLexingRawMode() || 
ParsingPreprocessorDirective4
||
4359
66
        
PP->isPreprocessedOutput()2
) {
4360
65
      ++CurPtr;
4361
65
      Kind = tok::unknown;
4362
65
      break;
4363
65
    }
4364
4365
    // Non-ASCII characters tend to creep into source code unintentionally.
4366
    // Instead of letting the parser complain about the unknown token,
4367
    // just diagnose the invalid UTF-8, then drop the character.
4368
1
    Diag(CurPtr, diag::err_invalid_utf8);
4369
4370
1
    BufferPtr = CurPtr+1;
4371
    // We're pretending the character didn't exist, so just try again with
4372
    // this lexer.
4373
    // (We manually eliminate the tail call to avoid recursion.)
4374
1
    goto LexNextToken;
4375
66
  }
4376
1.83G
  }
4377
4378
  // Notify MIOpt that we read a non-whitespace/non-comment token.
4379
815M
  MIOpt.ReadToken();
4380
4381
  // Update the location of token as well as BufferPtr.
4382
815M
  FormTokenWithChars(Result, CurPtr, Kind);
4383
815M
  return true;
4384
4385
61.6M
HandleDirective:
4386
  // We parsed a # character and it's the start of a preprocessing directive.
4387
4388
61.6M
  FormTokenWithChars(Result, CurPtr, tok::hash);
4389
61.6M
  PP->HandleDirective(Result);
4390
4391
61.6M
  if (PP->hadModuleLoaderFatalFailure())
4392
    // With a fatal failure in the module loader, we abort parsing.
4393
4
    return true;
4394
4395
  // We parsed the directive; lex a token with the new state.
4396
61.6M
  return false;
4397
4398
169M
LexNextToken:
4399
169M
  Result.clearFlag(Token::NeedsCleaning);
4400
169M
  goto LexStart;
4401
61.6M
}
4402
4403
const char *Lexer::convertDependencyDirectiveToken(
4404
2.10k
    const dependency_directives_scan::Token &DDTok, Token &Result) {
4405
2.10k
  const char *TokPtr = BufferStart + DDTok.Offset;
4406
2.10k
  Result.startToken();
4407
2.10k
  Result.setLocation(getSourceLocation(TokPtr));
4408
2.10k
  Result.setKind(DDTok.Kind);
4409
2.10k
  Result.setFlag((Token::TokenFlags)DDTok.Flags);
4410
2.10k
  Result.setLength(DDTok.Length);
4411
2.10k
  BufferPtr = TokPtr + DDTok.Length;
4412
2.10k
  return TokPtr;
4413
2.10k
}
4414
4415
2.53k
bool Lexer::LexDependencyDirectiveToken(Token &Result) {
4416
2.53k
  assert(isDependencyDirectivesLexer());
4417
4418
2.53k
  using namespace dependency_directives_scan;
4419
4420
3.06k
  while (NextDepDirectiveTokenIndex == DepDirectives.front().Tokens.size()) {
4421
995
    if (DepDirectives.front().Kind == pp_eof)
4422
461
      return LexEndOfFile(Result, BufferEnd);
4423
534
    if (DepDirectives.front().Kind == tokens_present_before_eof)
4424
47
      MIOpt.ReadToken();
4425
534
    NextDepDirectiveTokenIndex = 0;
4426
534
    DepDirectives = DepDirectives.drop_front();
4427
534
  }
4428
4429
2.07k
  const dependency_directives_scan::Token &DDTok =
4430
2.07k
      DepDirectives.front().Tokens[NextDepDirectiveTokenIndex++];
4431
2.07k
  if (NextDepDirectiveTokenIndex > 1 || 
DDTok.Kind != tok::hash488
) {
4432
    // Read something other than a preprocessor directive hash.
4433
1.61k
    MIOpt.ReadToken();
4434
1.61k
  }
4435
4436
2.07k
  if (ParsingFilename && 
DDTok.is(tok::less)318
) {
4437
2
    BufferPtr = BufferStart + DDTok.Offset;
4438
2
    LexAngledStringLiteral(Result, BufferPtr + 1);
4439
2
    if (Result.isNot(tok::header_name))
4440
1
      return true;
4441
    // Advance the index of lexed tokens.
4442
7
    
while (1
true) {
4443
7
      const dependency_directives_scan::Token &NextTok =
4444
7
          DepDirectives.front().Tokens[NextDepDirectiveTokenIndex];
4445
7
      if (BufferStart + NextTok.Offset >= BufferPtr)
4446
1
        break;
4447
6
      ++NextDepDirectiveTokenIndex;
4448
6
    }
4449
1
    return true;
4450
2
  }
4451
4452
2.07k
  const char *TokPtr = convertDependencyDirectiveToken(DDTok, Result);
4453
4454
2.07k
  if (Result.is(tok::hash) && 
Result.isAtStartOfLine()458
) {
4455
458
    PP->HandleDirective(Result);
4456
458
    return false;
4457
458
  }
4458
1.61k
  if (Result.is(tok::raw_identifier)) {
4459
692
    Result.setRawIdentifierData(TokPtr);
4460
692
    if (!isLexingRawMode()) {
4461
654
      IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
4462
654
      if (II->isHandleIdentifierCase())
4463
91
        return PP->HandleIdentifier(Result);
4464
654
    }
4465
601
    return true;
4466
692
  }
4467
922
  if (Result.isLiteral()) {
4468
326
    Result.setLiteralData(TokPtr);
4469
326
    return true;
4470
326
  }
4471
596
  if (Result.is(tok::colon)) {
4472
    // Convert consecutive colons to 'tok::coloncolon'.
4473
0
    if (*BufferPtr == ':') {
4474
0
      assert(DepDirectives.front().Tokens[NextDepDirectiveTokenIndex].is(
4475
0
          tok::colon));
4476
0
      ++NextDepDirectiveTokenIndex;
4477
0
      Result.setKind(tok::coloncolon);
4478
0
    }
4479
0
    return true;
4480
0
  }
4481
596
  if (Result.is(tok::eod))
4482
496
    ParsingPreprocessorDirective = false;
4483
4484
596
  return true;
4485
596
}
4486
4487
39
bool Lexer::LexDependencyDirectiveTokenWhileSkipping(Token &Result) {
4488
39
  assert(isDependencyDirectivesLexer());
4489
4490
39
  using namespace dependency_directives_scan;
4491
4492
39
  bool Stop = false;
4493
39
  unsigned NestedIfs = 0;
4494
75
  do {
4495
75
    DepDirectives = DepDirectives.drop_front();
4496
75
    switch (DepDirectives.front().Kind) {
4497
0
    case pp_none:
4498
0
      llvm_unreachable("unexpected 'pp_none'");
4499
32
    case pp_include:
4500
32
    case pp___include_macros:
4501
36
    case pp_define:
4502
36
    case pp_undef:
4503
36
    case pp_import:
4504
36
    case pp_pragma_import:
4505
36
    case pp_pragma_once:
4506
36
    case pp_pragma_push_macro:
4507
36
    case pp_pragma_pop_macro:
4508
36
    case pp_pragma_include_alias:
4509
36
    case pp_pragma_system_header:
4510
36
    case pp_include_next:
4511
36
    case decl_at_import:
4512
36
    case cxx_module_decl:
4513
36
    case cxx_import_decl:
4514
36
    case cxx_export_module_decl:
4515
36
    case cxx_export_import_decl:
4516
36
    case tokens_present_before_eof:
4517
36
      break;
4518
0
    case pp_if:
4519
0
    case pp_ifdef:
4520
0
    case pp_ifndef:
4521
0
      ++NestedIfs;
4522
0
      break;
4523
2
    case pp_elif:
4524
2
    case pp_elifdef:
4525
2
    case pp_elifndef:
4526
2
    case pp_else:
4527
2
      if (!NestedIfs) {
4528
2
        Stop = true;
4529
2
      }
4530
2
      break;
4531
36
    case pp_endif:
4532
36
      if (!NestedIfs) {
4533
36
        Stop = true;
4534
36
      } else {
4535
0
        --NestedIfs;
4536
0
      }
4537
36
      break;
4538
1
    case pp_eof:
4539
1
      NextDepDirectiveTokenIndex = 0;
4540
1
      return LexEndOfFile(Result, BufferEnd);
4541
75
    }
4542
75
  } while (
!Stop74
);
4543
4544
38
  const dependency_directives_scan::Token &DDTok =
4545
38
      DepDirectives.front().Tokens.front();
4546
38
  assert(DDTok.is(tok::hash));
4547
38
  NextDepDirectiveTokenIndex = 1;
4548
4549
38
  convertDependencyDirectiveToken(DDTok, Result);
4550
38
  return false;
4551
38
}