Coverage Report

Created: 2022-01-25 06:29

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Lex/Pragma.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Pragma.cpp - Pragma registration and handling ----------------------===//
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 PragmaHandler/PragmaTable interfaces and implements
10
// pragma related methods of the Preprocessor class.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Lex/Pragma.h"
15
#include "clang/Basic/CLWarnings.h"
16
#include "clang/Basic/Diagnostic.h"
17
#include "clang/Basic/DiagnosticLex.h"
18
#include "clang/Basic/FileManager.h"
19
#include "clang/Basic/IdentifierTable.h"
20
#include "clang/Basic/LLVM.h"
21
#include "clang/Basic/LangOptions.h"
22
#include "clang/Basic/Module.h"
23
#include "clang/Basic/SourceLocation.h"
24
#include "clang/Basic/SourceManager.h"
25
#include "clang/Basic/TokenKinds.h"
26
#include "clang/Lex/HeaderSearch.h"
27
#include "clang/Lex/LexDiagnostic.h"
28
#include "clang/Lex/Lexer.h"
29
#include "clang/Lex/LiteralSupport.h"
30
#include "clang/Lex/MacroInfo.h"
31
#include "clang/Lex/ModuleLoader.h"
32
#include "clang/Lex/PPCallbacks.h"
33
#include "clang/Lex/Preprocessor.h"
34
#include "clang/Lex/PreprocessorLexer.h"
35
#include "clang/Lex/PreprocessorOptions.h"
36
#include "clang/Lex/Token.h"
37
#include "clang/Lex/TokenLexer.h"
38
#include "llvm/ADT/ArrayRef.h"
39
#include "llvm/ADT/DenseMap.h"
40
#include "llvm/ADT/Optional.h"
41
#include "llvm/ADT/STLExtras.h"
42
#include "llvm/ADT/SmallString.h"
43
#include "llvm/ADT/SmallVector.h"
44
#include "llvm/ADT/StringRef.h"
45
#include "llvm/ADT/StringSwitch.h"
46
#include "llvm/Support/Compiler.h"
47
#include "llvm/Support/ErrorHandling.h"
48
#include "llvm/Support/Timer.h"
49
#include <algorithm>
50
#include <cassert>
51
#include <cstddef>
52
#include <cstdint>
53
#include <limits>
54
#include <string>
55
#include <utility>
56
#include <vector>
57
58
using namespace clang;
59
60
// Out-of-line destructor to provide a home for the class.
61
5.26M
PragmaHandler::~PragmaHandler() = default;
62
63
//===----------------------------------------------------------------------===//
64
// EmptyPragmaHandler Implementation.
65
//===----------------------------------------------------------------------===//
66
67
16.0k
EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
68
69
void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
70
                                      PragmaIntroducer Introducer,
71
18
                                      Token &FirstToken) {}
72
73
//===----------------------------------------------------------------------===//
74
// PragmaNamespace Implementation.
75
//===----------------------------------------------------------------------===//
76
77
/// FindHandler - Check to see if there is already a handler for the
78
/// specified name.  If not, return the handler for the null identifier if it
79
/// exists, otherwise return null.  If IgnoreNull is true (the default) then
80
/// the null handler isn't returned on failure to match.
81
PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
82
10.5M
                                            bool IgnoreNull) const {
83
10.5M
  auto I = Handlers.find(Name);
84
10.5M
  if (I != Handlers.end())
85
5.40M
    return I->getValue().get();
86
5.10M
  if (IgnoreNull)
87
5.09M
    return nullptr;
88
921
  I = Handlers.find(StringRef());
89
921
  if (I != Handlers.end())
90
104
    return I->getValue().get();
91
817
  return nullptr;
92
921
}
93
94
5.53M
void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
95
5.53M
  assert(!Handlers.count(Handler->getName()) &&
96
5.53M
         "A handler with this name is already registered in this namespace");
97
0
  Handlers[Handler->getName()].reset(Handler);
98
5.53M
}
99
100
2.66M
void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
101
2.66M
  auto I = Handlers.find(Handler->getName());
102
2.66M
  assert(I != Handlers.end() &&
103
2.66M
         "Handler not registered in this namespace");
104
  // Release ownership back to the caller.
105
0
  I->getValue().release();
106
2.66M
  Handlers.erase(I);
107
2.66M
}
108
109
void PragmaNamespace::HandlePragma(Preprocessor &PP,
110
1.51M
                                   PragmaIntroducer Introducer, Token &Tok) {
111
  // Read the 'namespace' that the directive is in, e.g. STDC.  Do not macro
112
  // expand it, the user can have a STDC #define, that should not affect this.
113
1.51M
  PP.LexUnexpandedToken(Tok);
114
115
  // Get the handler for this token.  If there is no handler, ignore the pragma.
116
1.51M
  PragmaHandler *Handler
117
1.51M
    = FindHandler(Tok.getIdentifierInfo() ? 
Tok.getIdentifierInfo()->getName()1.51M
118
1.51M
                                          : 
StringRef()12
,
119
1.51M
                  /*IgnoreNull=*/false);
120
1.51M
  if (!Handler) {
121
968
    PP.Diag(Tok, diag::warn_pragma_ignored);
122
968
    return;
123
968
  }
124
125
  // Otherwise, pass it down.
126
1.51M
  Handler->HandlePragma(PP, Introducer, Tok);
127
1.51M
}
128
129
//===----------------------------------------------------------------------===//
130
// Preprocessor Pragma Directive Handling.
131
//===----------------------------------------------------------------------===//
132
133
namespace {
134
// TokenCollector provides the option to collect tokens that were "read"
135
// and return them to the stream to be read later.
136
// Currently used when reading _Pragma/__pragma directives.
137
struct TokenCollector {
138
  Preprocessor &Self;
139
  bool Collect;
140
  SmallVector<Token, 3> Tokens;
141
  Token &Tok;
142
143
1.08M
  void lex() {
144
1.08M
    if (Collect)
145
91
      Tokens.push_back(Tok);
146
1.08M
    Self.Lex(Tok);
147
1.08M
  }
148
149
22
  void revert() {
150
22
    assert(Collect && "did not collect tokens");
151
0
    assert(!Tokens.empty() && "collected unexpected number of tokens");
152
153
    // Push the ( "string" ) tokens into the token stream.
154
0
    auto Toks = std::make_unique<Token[]>(Tokens.size());
155
22
    std::copy(Tokens.begin() + 1, Tokens.end(), Toks.get());
156
22
    Toks[Tokens.size() - 1] = Tok;
157
22
    Self.EnterTokenStream(std::move(Toks), Tokens.size(),
158
22
                          /*DisableMacroExpansion*/ true,
159
22
                          /*IsReinject*/ true);
160
161
    // ... and return the pragma token unchanged.
162
22
    Tok = *Tokens.begin();
163
22
  }
164
};
165
} // namespace
166
167
/// HandlePragmaDirective - The "\#pragma" directive has been parsed.  Lex the
168
/// rest of the pragma, passing it to the registered pragma handlers.
169
1.04M
void Preprocessor::HandlePragmaDirective(PragmaIntroducer Introducer) {
170
1.04M
  if (Callbacks)
171
1.04M
    Callbacks->PragmaDirective(Introducer.Loc, Introducer.Kind);
172
173
1.04M
  if (!PragmasEnabled)
174
3
    return;
175
176
1.04M
  ++NumPragma;
177
178
  // Invoke the first level of pragma handlers which reads the namespace id.
179
1.04M
  Token Tok;
180
1.04M
  PragmaHandlers->HandlePragma(*this, Introducer, Tok);
181
182
  // If the pragma handler didn't read the rest of the line, consume it now.
183
1.04M
  if ((CurTokenLexer && 
CurTokenLexer->isParsingPreprocessorDirective()503k
)
184
1.04M
   || 
(1.04M
CurPPLexer1.04M
&&
CurPPLexer->ParsingPreprocessorDirective546k
))
185
110k
    DiscardUntilEndOfDirective();
186
1.04M
}
187
188
/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
189
/// return the first token after the directive.  The _Pragma token has just
190
/// been read into 'Tok'.
191
362k
void Preprocessor::Handle_Pragma(Token &Tok) {
192
  // C11 6.10.3.4/3:
193
  //   all pragma unary operator expressions within [a completely
194
  //   macro-replaced preprocessing token sequence] are [...] processed [after
195
  //   rescanning is complete]
196
  //
197
  // This means that we execute _Pragma operators in two cases:
198
  //
199
  //  1) on token sequences that would otherwise be produced as the output of
200
  //     phase 4 of preprocessing, and
201
  //  2) on token sequences formed as the macro-replaced token sequence of a
202
  //     macro argument
203
  //
204
  // Case #2 appears to be a wording bug: only _Pragmas that would survive to
205
  // the end of phase 4 should actually be executed. Discussion on the WG14
206
  // mailing list suggests that a _Pragma operator is notionally checked early,
207
  // but only pragmas that survive to the end of phase 4 should be executed.
208
  //
209
  // In Case #2, we check the syntax now, but then put the tokens back into the
210
  // token stream for later consumption.
211
212
362k
  TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
213
214
  // Remember the pragma token location.
215
362k
  SourceLocation PragmaLoc = Tok.getLocation();
216
217
  // Read the '('.
218
362k
  Toks.lex();
219
362k
  if (Tok.isNot(tok::l_paren)) {
220
1
    Diag(PragmaLoc, diag::err__Pragma_malformed);
221
1
    return;
222
1
  }
223
224
  // Read the '"..."'.
225
362k
  Toks.lex();
226
362k
  if (!tok::isStringLiteral(Tok.getKind())) {
227
4
    Diag(PragmaLoc, diag::err__Pragma_malformed);
228
    // Skip bad tokens, and the ')', if present.
229
4
    if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
230
3
      Lex(Tok);
231
7
    while (Tok.isNot(tok::r_paren) &&
232
7
           
!Tok.isAtStartOfLine()5
&&
233
7
           
Tok.isNot(tok::eof)5
)
234
3
      Lex(Tok);
235
4
    if (Tok.is(tok::r_paren))
236
2
      Lex(Tok);
237
4
    return;
238
4
  }
239
240
362k
  if (Tok.hasUDSuffix()) {
241
1
    Diag(Tok, diag::err_invalid_string_udl);
242
    // Skip this token, and the ')', if present.
243
1
    Lex(Tok);
244
1
    if (Tok.is(tok::r_paren))
245
1
      Lex(Tok);
246
1
    return;
247
1
  }
248
249
  // Remember the string.
250
362k
  Token StrTok = Tok;
251
252
  // Read the ')'.
253
362k
  Toks.lex();
254
362k
  if (Tok.isNot(tok::r_paren)) {
255
0
    Diag(PragmaLoc, diag::err__Pragma_malformed);
256
0
    return;
257
0
  }
258
259
  // If we're expanding a macro argument, put the tokens back.
260
362k
  if (InMacroArgPreExpansion) {
261
16
    Toks.revert();
262
16
    return;
263
16
  }
264
265
362k
  SourceLocation RParenLoc = Tok.getLocation();
266
362k
  std::string StrVal = getSpelling(StrTok);
267
268
  // The _Pragma is lexically sound.  Destringize according to C11 6.10.9.1:
269
  // "The string literal is destringized by deleting any encoding prefix,
270
  // deleting the leading and trailing double-quotes, replacing each escape
271
  // sequence \" by a double-quote, and replacing each escape sequence \\ by a
272
  // single backslash."
273
362k
  if (StrVal[0] == 'L' || 
StrVal[0] == 'U'362k
||
274
362k
      
(362k
StrVal[0] == 'u'362k
&&
StrVal[1] != '8'3
))
275
4
    StrVal.erase(StrVal.begin());
276
362k
  else if (StrVal[0] == 'u')
277
2
    StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
278
279
362k
  if (StrVal[0] == 'R') {
280
    // FIXME: C++11 does not specify how to handle raw-string-literals here.
281
    // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
282
3
    assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
283
3
           "Invalid raw string token!");
284
285
    // Measure the length of the d-char-sequence.
286
0
    unsigned NumDChars = 0;
287
4
    while (StrVal[2 + NumDChars] != '(') {
288
1
      assert(NumDChars < (StrVal.size() - 5) / 2 &&
289
1
             "Invalid raw string token!");
290
0
      ++NumDChars;
291
1
    }
292
3
    assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
293
294
    // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
295
    // parens below.
296
0
    StrVal.erase(0, 2 + NumDChars);
297
3
    StrVal.erase(StrVal.size() - 1 - NumDChars);
298
362k
  } else {
299
362k
    assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
300
362k
           "Invalid string token!");
301
302
    // Remove escaped quotes and escapes.
303
0
    unsigned ResultPos = 1;
304
10.1M
    for (size_t i = 1, e = StrVal.size() - 1; i != e; 
++i9.77M
) {
305
      // Skip escapes.  \\ -> '\' and \" -> '"'.
306
9.77M
      if (StrVal[i] == '\\' && 
i + 1 < e199k
&&
307
9.77M
          
(199k
StrVal[i + 1] == '\\'199k
||
StrVal[i + 1] == '"'199k
))
308
199k
        ++i;
309
9.77M
      StrVal[ResultPos++] = StrVal[i];
310
9.77M
    }
311
362k
    StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
312
362k
  }
313
314
  // Remove the front quote, replacing it with a space, so that the pragma
315
  // contents appear to have a space before them.
316
0
  StrVal[0] = ' ';
317
318
  // Replace the terminating quote with a \n.
319
362k
  StrVal[StrVal.size()-1] = '\n';
320
321
  // Plop the string (including the newline and trailing null) into a buffer
322
  // where we can lex it.
323
362k
  Token TmpTok;
324
362k
  TmpTok.startToken();
325
362k
  CreateString(StrVal, TmpTok);
326
362k
  SourceLocation TokLoc = TmpTok.getLocation();
327
328
  // Make and enter a lexer object so that we lex and expand the tokens just
329
  // like any others.
330
362k
  Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
331
362k
                                        StrVal.size(), *this);
332
333
362k
  EnterSourceFileWithLexer(TL, nullptr);
334
335
  // With everything set up, lex this as a #pragma directive.
336
362k
  HandlePragmaDirective({PIK__Pragma, PragmaLoc});
337
338
  // Finally, return whatever came after the pragma directive.
339
362k
  return Lex(Tok);
340
362k
}
341
342
/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
343
/// is not enclosed within a string literal.
344
35
void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
345
  // During macro pre-expansion, check the syntax now but put the tokens back
346
  // into the token stream for later consumption. Same as Handle_Pragma.
347
35
  TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
348
349
  // Remember the pragma token location.
350
35
  SourceLocation PragmaLoc = Tok.getLocation();
351
352
  // Read the '('.
353
35
  Toks.lex();
354
35
  if (Tok.isNot(tok::l_paren)) {
355
0
    Diag(PragmaLoc, diag::err__Pragma_malformed);
356
0
    return;
357
0
  }
358
359
  // Get the tokens enclosed within the __pragma(), as well as the final ')'.
360
35
  SmallVector<Token, 32> PragmaToks;
361
35
  int NumParens = 0;
362
35
  Toks.lex();
363
192
  while (Tok.isNot(tok::eof)) {
364
192
    PragmaToks.push_back(Tok);
365
192
    if (Tok.is(tok::l_paren))
366
31
      NumParens++;
367
161
    else if (Tok.is(tok::r_paren) && 
NumParens-- == 066
)
368
35
      break;
369
157
    Toks.lex();
370
157
  }
371
372
35
  if (Tok.is(tok::eof)) {
373
0
    Diag(PragmaLoc, diag::err_unterminated___pragma);
374
0
    return;
375
0
  }
376
377
  // If we're expanding a macro argument, put the tokens back.
378
35
  if (InMacroArgPreExpansion) {
379
6
    Toks.revert();
380
6
    return;
381
6
  }
382
383
29
  PragmaToks.front().setFlag(Token::LeadingSpace);
384
385
  // Replace the ')' with an EOD to mark the end of the pragma.
386
29
  PragmaToks.back().setKind(tok::eod);
387
388
29
  Token *TokArray = new Token[PragmaToks.size()];
389
29
  std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
390
391
  // Push the tokens onto the stack.
392
29
  EnterTokenStream(TokArray, PragmaToks.size(), true, true,
393
29
                   /*IsReinject*/ false);
394
395
  // With everything set up, lex this as a #pragma directive.
396
29
  HandlePragmaDirective({PIK___pragma, PragmaLoc});
397
398
  // Finally, return whatever came after the pragma directive.
399
29
  return Lex(Tok);
400
35
}
401
402
/// HandlePragmaOnce - Handle \#pragma once.  OnceTok is the 'once'.
403
273
void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
404
  // Don't honor the 'once' when handling the primary source file, unless
405
  // this is a prefix to a TU, which indicates we're generating a PCH file, or
406
  // when the main file is a header (e.g. when -xc-header is provided on the
407
  // commandline).
408
273
  if (isInPrimaryFile() && 
TUKind != TU_Prefix6
&&
!getLangOpts().IsHeaderFile4
) {
409
3
    Diag(OnceTok, diag::pp_pragma_once_in_main_file);
410
3
    return;
411
3
  }
412
413
  // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
414
  // Mark the file as a once-only file now.
415
270
  HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
416
270
}
417
418
37.5k
void Preprocessor::HandlePragmaMark(Token &MarkTok) {
419
37.5k
  assert(CurPPLexer && "No current lexer?");
420
421
0
  SmallString<64> Buffer;
422
37.5k
  CurLexer->ReadToEndOfLine(&Buffer);
423
37.5k
  if (Callbacks)
424
37.5k
    Callbacks->PragmaMark(MarkTok.getLocation(), Buffer);
425
37.5k
}
426
427
/// HandlePragmaPoison - Handle \#pragma GCC poison.  PoisonTok is the 'poison'.
428
5
void Preprocessor::HandlePragmaPoison() {
429
5
  Token Tok;
430
431
10
  while (true) {
432
    // Read the next token to poison.  While doing this, pretend that we are
433
    // skipping while reading the identifier to poison.
434
    // This avoids errors on code like:
435
    //   #pragma GCC poison X
436
    //   #pragma GCC poison X
437
10
    if (CurPPLexer) CurPPLexer->LexingRawMode = true;
438
10
    LexUnexpandedToken(Tok);
439
10
    if (CurPPLexer) CurPPLexer->LexingRawMode = false;
440
441
    // If we reached the end of line, we're done.
442
10
    if (Tok.is(tok::eod)) 
return5
;
443
444
    // Can only poison identifiers.
445
5
    if (Tok.isNot(tok::raw_identifier)) {
446
0
      Diag(Tok, diag::err_pp_invalid_poison);
447
0
      return;
448
0
    }
449
450
    // Look up the identifier info for the token.  We disabled identifier lookup
451
    // by saying we're skipping contents, so we need to do this manually.
452
5
    IdentifierInfo *II = LookUpIdentifierInfo(Tok);
453
454
    // Already poisoned.
455
5
    if (II->isPoisoned()) 
continue1
;
456
457
    // If this is a macro identifier, emit a warning.
458
4
    if (isMacroDefined(II))
459
0
      Diag(Tok, diag::pp_poisoning_existing_macro);
460
461
    // Finally, poison it!
462
4
    II->setIsPoisoned();
463
4
    if (II->isFromAST())
464
0
      II->setChangedSinceDeserialization();
465
4
  }
466
5
}
467
468
/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header.  We know
469
/// that the whole directive has been parsed.
470
133k
void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
471
133k
  if (isInPrimaryFile()) {
472
1
    Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
473
1
    return;
474
1
  }
475
476
  // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
477
133k
  PreprocessorLexer *TheLexer = getCurrentFileLexer();
478
479
  // Mark the file as a system header.
480
133k
  HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
481
482
133k
  PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
483
133k
  if (PLoc.isInvalid())
484
0
    return;
485
486
133k
  unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
487
488
  // Notify the client, if desired, that we are in a new source file.
489
133k
  if (Callbacks)
490
133k
    Callbacks->FileChanged(SysHeaderTok.getLocation(),
491
133k
                           PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
492
493
  // Emit a line marker.  This will change any source locations from this point
494
  // forward to realize they are in a system header.
495
  // Create a line note with this information.
496
133k
  SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
497
133k
                        FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
498
133k
                        SrcMgr::C_System);
499
133k
}
500
501
static llvm::Optional<Token> LexHeader(Preprocessor &PP,
502
                                       Optional<FileEntryRef> &File,
503
20
                                       bool SuppressIncludeNotFoundError) {
504
20
  Token FilenameTok;
505
20
  if (PP.LexHeaderName(FilenameTok, /*AllowConcatenation*/ false))
506
0
    return llvm::None;
507
508
  // If the next token wasn't a header-name, diagnose the error.
509
20
  if (FilenameTok.isNot(tok::header_name)) {
510
1
    PP.Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
511
1
    return llvm::None;
512
1
  }
513
514
  // Reserve a buffer to get the spelling.
515
19
  SmallString<128> FilenameBuffer;
516
19
  bool Invalid = false;
517
19
  StringRef Filename = PP.getSpelling(FilenameTok, FilenameBuffer, &Invalid);
518
19
  if (Invalid)
519
0
    return llvm::None;
520
521
19
  bool isAngled =
522
19
      PP.GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
523
  // If GetIncludeFilenameSpelling set the start ptr to null, there was an
524
  // error.
525
19
  if (Filename.empty())
526
0
    return llvm::None;
527
528
  // Search include directories for this file.
529
19
  File = PP.LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
530
19
                       nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
531
19
                       nullptr);
532
19
  if (!File) {
533
3
    if (!SuppressIncludeNotFoundError)
534
3
      PP.Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
535
3
    return llvm::None;
536
3
  }
537
538
16
  return FilenameTok;
539
19
}
540
541
/// HandlePragmaIncludeInstead - Handle \#pragma clang include_instead(header).
542
18
void Preprocessor::HandlePragmaIncludeInstead(Token &Tok) {
543
  // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
544
18
  PreprocessorLexer *TheLexer = getCurrentFileLexer();
545
546
18
  if (!SourceMgr.isInSystemHeader(Tok.getLocation())) {
547
1
    Diag(Tok, diag::err_pragma_include_instead_not_sysheader);
548
1
    return;
549
1
  }
550
551
17
  Lex(Tok);
552
17
  if (Tok.isNot(tok::l_paren)) {
553
1
    Diag(Tok, diag::err_expected) << "(";
554
1
    return;
555
1
  }
556
557
16
  Optional<FileEntryRef> File;
558
16
  llvm::Optional<Token> FilenameTok =
559
16
      LexHeader(*this, File, SuppressIncludeNotFoundError);
560
16
  if (!FilenameTok)
561
1
    return;
562
563
15
  Lex(Tok);
564
15
  if (Tok.isNot(tok::r_paren)) {
565
1
    Diag(Tok, diag::err_expected) << ")";
566
1
    return;
567
1
  }
568
569
14
  SmallString<128> FilenameBuffer;
570
14
  StringRef Filename = getSpelling(*FilenameTok, FilenameBuffer);
571
14
  HeaderInfo.AddFileAlias(TheLexer->getFileEntry(), Filename);
572
14
}
573
574
/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
575
4
void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
576
4
  Optional<FileEntryRef> File;
577
4
  llvm::Optional<Token> FilenameTok =
578
4
      LexHeader(*this, File, SuppressIncludeNotFoundError);
579
4
  if (!FilenameTok)
580
3
    return;
581
582
1
  const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
583
584
  // If this file is older than the file it depends on, emit a diagnostic.
585
1
  if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
586
    // Lex tokens at the end of the message and include them in the message.
587
0
    std::string Message;
588
0
    Lex(DependencyTok);
589
0
    while (DependencyTok.isNot(tok::eod)) {
590
0
      Message += getSpelling(DependencyTok) + " ";
591
0
      Lex(DependencyTok);
592
0
    }
593
594
    // Remove the trailing ' ' if present.
595
0
    if (!Message.empty())
596
0
      Message.erase(Message.end()-1);
597
0
    Diag(*FilenameTok, diag::pp_out_of_date_dependency) << Message;
598
0
  }
599
1
}
600
601
/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
602
/// Return the IdentifierInfo* associated with the macro to push or pop.
603
46.9k
IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
604
  // Remember the pragma token location.
605
46.9k
  Token PragmaTok = Tok;
606
607
  // Read the '('.
608
46.9k
  Lex(Tok);
609
46.9k
  if (Tok.isNot(tok::l_paren)) {
610
0
    Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
611
0
      << getSpelling(PragmaTok);
612
0
    return nullptr;
613
0
  }
614
615
  // Read the macro name string.
616
46.9k
  Lex(Tok);
617
46.9k
  if (Tok.isNot(tok::string_literal)) {
618
0
    Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
619
0
      << getSpelling(PragmaTok);
620
0
    return nullptr;
621
0
  }
622
623
46.9k
  if (Tok.hasUDSuffix()) {
624
1
    Diag(Tok, diag::err_invalid_string_udl);
625
1
    return nullptr;
626
1
  }
627
628
  // Remember the macro string.
629
46.9k
  std::string StrVal = getSpelling(Tok);
630
631
  // Read the ')'.
632
46.9k
  Lex(Tok);
633
46.9k
  if (Tok.isNot(tok::r_paren)) {
634
0
    Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
635
0
      << getSpelling(PragmaTok);
636
0
    return nullptr;
637
0
  }
638
639
46.9k
  assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
640
46.9k
         "Invalid string token!");
641
642
  // Create a Token from the string.
643
0
  Token MacroTok;
644
46.9k
  MacroTok.startToken();
645
46.9k
  MacroTok.setKind(tok::raw_identifier);
646
46.9k
  CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
647
648
  // Get the IdentifierInfo of MacroToPushTok.
649
46.9k
  return LookUpIdentifierInfo(MacroTok);
650
46.9k
}
651
652
/// Handle \#pragma push_macro.
653
///
654
/// The syntax is:
655
/// \code
656
///   #pragma push_macro("macro")
657
/// \endcode
658
23.4k
void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
659
  // Parse the pragma directive and get the macro IdentifierInfo*.
660
23.4k
  IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
661
23.4k
  if (!IdentInfo) 
return1
;
662
663
  // Get the MacroInfo associated with IdentInfo.
664
23.4k
  MacroInfo *MI = getMacroInfo(IdentInfo);
665
666
23.4k
  if (MI) {
667
    // Allow the original MacroInfo to be redefined later.
668
56
    MI->setIsAllowRedefinitionsWithoutWarning(true);
669
56
  }
670
671
  // Push the cloned MacroInfo so we can retrieve it later.
672
23.4k
  PragmaPushMacroInfo[IdentInfo].push_back(MI);
673
23.4k
}
674
675
/// Handle \#pragma pop_macro.
676
///
677
/// The syntax is:
678
/// \code
679
///   #pragma pop_macro("macro")
680
/// \endcode
681
23.4k
void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
682
23.4k
  SourceLocation MessageLoc = PopMacroTok.getLocation();
683
684
  // Parse the pragma directive and get the macro IdentifierInfo*.
685
23.4k
  IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
686
23.4k
  if (!IdentInfo) 
return0
;
687
688
  // Find the vector<MacroInfo*> associated with the macro.
689
23.4k
  llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter =
690
23.4k
    PragmaPushMacroInfo.find(IdentInfo);
691
23.4k
  if (iter != PragmaPushMacroInfo.end()) {
692
    // Forget the MacroInfo currently associated with IdentInfo.
693
23.4k
    if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
694
129
      if (MI->isWarnIfUnused())
695
0
        WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
696
129
      appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
697
129
    }
698
699
    // Get the MacroInfo we want to reinstall.
700
23.4k
    MacroInfo *MacroToReInstall = iter->second.back();
701
702
23.4k
    if (MacroToReInstall)
703
      // Reinstall the previously pushed macro.
704
55
      appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
705
706
    // Pop PragmaPushMacroInfo stack.
707
23.4k
    iter->second.pop_back();
708
23.4k
    if (iter->second.empty())
709
23.4k
      PragmaPushMacroInfo.erase(iter);
710
23.4k
  } else {
711
0
    Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
712
0
      << IdentInfo->getName();
713
0
  }
714
23.4k
}
715
716
24
void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
717
  // We will either get a quoted filename or a bracketed filename, and we
718
  // have to track which we got.  The first filename is the source name,
719
  // and the second name is the mapped filename.  If the first is quoted,
720
  // the second must be as well (cannot mix and match quotes and brackets).
721
722
  // Get the open paren
723
24
  Lex(Tok);
724
24
  if (Tok.isNot(tok::l_paren)) {
725
0
    Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
726
0
    return;
727
0
  }
728
729
  // We expect either a quoted string literal, or a bracketed name
730
24
  Token SourceFilenameTok;
731
24
  if (LexHeaderName(SourceFilenameTok))
732
0
    return;
733
734
24
  StringRef SourceFileName;
735
24
  SmallString<128> FileNameBuffer;
736
24
  if (SourceFilenameTok.is(tok::header_name)) {
737
22
    SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
738
22
  } else {
739
2
    Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
740
2
    return;
741
2
  }
742
22
  FileNameBuffer.clear();
743
744
  // Now we expect a comma, followed by another include name
745
22
  Lex(Tok);
746
22
  if (Tok.isNot(tok::comma)) {
747
2
    Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
748
2
    return;
749
2
  }
750
751
20
  Token ReplaceFilenameTok;
752
20
  if (LexHeaderName(ReplaceFilenameTok))
753
0
    return;
754
755
20
  StringRef ReplaceFileName;
756
20
  if (ReplaceFilenameTok.is(tok::header_name)) {
757
20
    ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
758
20
  } else {
759
0
    Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
760
0
    return;
761
0
  }
762
763
  // Finally, we expect the closing paren
764
20
  Lex(Tok);
765
20
  if (Tok.isNot(tok::r_paren)) {
766
0
    Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
767
0
    return;
768
0
  }
769
770
  // Now that we have the source and target filenames, we need to make sure
771
  // they're both of the same type (angled vs non-angled)
772
20
  StringRef OriginalSource = SourceFileName;
773
774
20
  bool SourceIsAngled =
775
20
    GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
776
20
                                SourceFileName);
777
20
  bool ReplaceIsAngled =
778
20
    GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
779
20
                                ReplaceFileName);
780
20
  if (!SourceFileName.empty() && 
!ReplaceFileName.empty()18
&&
781
20
      
(SourceIsAngled != ReplaceIsAngled)16
) {
782
4
    unsigned int DiagID;
783
4
    if (SourceIsAngled)
784
2
      DiagID = diag::warn_pragma_include_alias_mismatch_angle;
785
2
    else
786
2
      DiagID = diag::warn_pragma_include_alias_mismatch_quote;
787
788
4
    Diag(SourceFilenameTok.getLocation(), DiagID)
789
4
      << SourceFileName
790
4
      << ReplaceFileName;
791
792
4
    return;
793
4
  }
794
795
  // Now we can let the include handler know about this mapping
796
16
  getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
797
16
}
798
799
// Lex a component of a module name: either an identifier or a string literal;
800
// for components that can be expressed both ways, the two forms are equivalent.
801
static bool LexModuleNameComponent(
802
    Preprocessor &PP, Token &Tok,
803
    std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent,
804
438
    bool First) {
805
438
  PP.LexUnexpandedToken(Tok);
806
438
  if (Tok.is(tok::string_literal) && 
!Tok.hasUDSuffix()7
) {
807
7
    StringLiteralParser Literal(Tok, PP);
808
7
    if (Literal.hadError)
809
0
      return true;
810
7
    ModuleNameComponent = std::make_pair(
811
7
        PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation());
812
431
  } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
813
422
    ModuleNameComponent =
814
422
        std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
815
422
  } else {
816
9
    PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
817
9
    return true;
818
9
  }
819
429
  return false;
820
438
}
821
822
static bool LexModuleName(
823
    Preprocessor &PP, Token &Tok,
824
    llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
825
272
        &ModuleName) {
826
362
  while (true) {
827
362
    std::pair<IdentifierInfo*, SourceLocation> NameComponent;
828
362
    if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
829
8
      return true;
830
354
    ModuleName.push_back(NameComponent);
831
832
354
    PP.LexUnexpandedToken(Tok);
833
354
    if (Tok.isNot(tok::period))
834
264
      return false;
835
354
  }
836
272
}
837
838
76
void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
839
76
  SourceLocation Loc = Tok.getLocation();
840
841
76
  std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
842
76
  if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
843
1
    return;
844
75
  IdentifierInfo *ModuleName = ModuleNameLoc.first;
845
846
75
  LexUnexpandedToken(Tok);
847
75
  if (Tok.isNot(tok::eod)) {
848
0
    Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
849
0
    DiscardUntilEndOfDirective();
850
0
  }
851
852
75
  CurLexer->LexingRawMode = true;
853
854
1.91k
  auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
855
1.91k
    if (Tok.getKind() != tok::raw_identifier ||
856
1.91k
        
Tok.getRawIdentifier() != Ident1.83k
)
857
792
      return false;
858
1.12k
    CurLexer->Lex(Tok);
859
1.12k
    return true;
860
1.91k
  };
861
862
  // Scan forward looking for the end of the module.
863
75
  const char *Start = CurLexer->getBufferLocation();
864
75
  const char *End = nullptr;
865
75
  unsigned NestingLevel = 1;
866
5.94k
  while (true) {
867
5.94k
    End = CurLexer->getBufferLocation();
868
5.94k
    CurLexer->Lex(Tok);
869
870
5.94k
    if (Tok.is(tok::eof)) {
871
1
      Diag(Loc, diag::err_pp_module_build_missing_end);
872
1
      break;
873
1
    }
874
875
5.94k
    if (Tok.isNot(tok::hash) || 
!Tok.isAtStartOfLine()520
) {
876
      // Token was part of module; keep going.
877
5.42k
      continue;
878
5.42k
    }
879
880
    // We hit something directive-shaped; check to see if this is the end
881
    // of the module build.
882
520
    CurLexer->ParsingPreprocessorDirective = true;
883
520
    CurLexer->Lex(Tok);
884
520
    if (TryConsumeIdentifier("pragma") && 
TryConsumeIdentifier("clang")349
&&
885
520
        
TryConsumeIdentifier("module")349
) {
886
349
      if (TryConsumeIdentifier("build"))
887
        // #pragma clang module build -> entering a nested module build.
888
1
        ++NestingLevel;
889
348
      else if (TryConsumeIdentifier("endbuild")) {
890
        // #pragma clang module endbuild -> leaving a module build.
891
75
        if (--NestingLevel == 0)
892
74
          break;
893
75
      }
894
      // We should either be looking at the EOD or more of the current directive
895
      // preceding the EOD. Either way we can ignore this token and keep going.
896
275
      assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
897
275
    }
898
520
  }
899
900
75
  CurLexer->LexingRawMode = false;
901
902
  // Load the extracted text as a preprocessed module.
903
75
  assert(CurLexer->getBuffer().begin() <= Start &&
904
75
         Start <= CurLexer->getBuffer().end() &&
905
75
         CurLexer->getBuffer().begin() <= End &&
906
75
         End <= CurLexer->getBuffer().end() &&
907
75
         "module source range not contained within same file buffer");
908
0
  TheModuleLoader.createModuleFromSource(Loc, ModuleName->getName(),
909
75
                                         StringRef(Start, End - Start));
910
75
}
911
912
7
void Preprocessor::HandlePragmaHdrstop(Token &Tok) {
913
7
  Lex(Tok);
914
7
  if (Tok.is(tok::l_paren)) {
915
2
    Diag(Tok.getLocation(), diag::warn_pp_hdrstop_filename_ignored);
916
917
2
    std::string FileName;
918
2
    if (!LexStringLiteral(Tok, FileName, "pragma hdrstop", false))
919
0
      return;
920
921
2
    if (Tok.isNot(tok::r_paren)) {
922
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
923
0
      return;
924
0
    }
925
2
    Lex(Tok);
926
2
  }
927
7
  if (Tok.isNot(tok::eod))
928
0
    Diag(Tok.getLocation(), diag::ext_pp_extra_tokens_at_eol)
929
0
        << "pragma hdrstop";
930
931
7
  if (creatingPCHWithPragmaHdrStop() &&
932
7
      
SourceMgr.isInMainFile(Tok.getLocation())2
) {
933
2
    assert(CurLexer && "no lexer for #pragma hdrstop processing");
934
0
    Token &Result = Tok;
935
2
    Result.startToken();
936
2
    CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
937
2
    CurLexer->cutOffLexing();
938
2
  }
939
7
  if (usingPCHWithPragmaHdrStop())
940
5
    SkippingUntilPragmaHdrStop = false;
941
7
}
942
943
/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
944
/// If 'Namespace' is non-null, then it is a token required to exist on the
945
/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
946
void Preprocessor::AddPragmaHandler(StringRef Namespace,
947
4.83M
                                    PragmaHandler *Handler) {
948
4.83M
  PragmaNamespace *InsertNS = PragmaHandlers.get();
949
950
  // If this is specified to be in a namespace, step down into it.
951
4.83M
  if (!Namespace.empty()) {
952
    // If there is already a pragma handler with the name of this namespace,
953
    // we either have an error (directive with the same name as a namespace) or
954
    // we already have the namespace to insert into.
955
2.87M
    if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
956
2.60M
      InsertNS = Existing->getIfNamespace();
957
2.60M
      assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
958
2.60M
             " handler with the same name!");
959
2.60M
    } else {
960
      // Otherwise, this namespace doesn't exist yet, create and insert the
961
      // handler for it.
962
262k
      InsertNS = new PragmaNamespace(Namespace);
963
262k
      PragmaHandlers->AddPragma(InsertNS);
964
262k
    }
965
2.87M
  }
966
967
  // Check to make sure we don't already have a pragma for this identifier.
968
0
  assert(!InsertNS->FindHandler(Handler->getName()) &&
969
4.83M
         "Pragma handler already exists for this identifier!");
970
0
  InsertNS->AddPragma(Handler);
971
4.83M
}
972
973
/// RemovePragmaHandler - Remove the specific pragma handler from the
974
/// preprocessor. If \arg Namespace is non-null, then it should be the
975
/// namespace that \arg Handler was added to. It is an error to remove
976
/// a handler that has not been registered.
977
void Preprocessor::RemovePragmaHandler(StringRef Namespace,
978
2.57M
                                       PragmaHandler *Handler) {
979
2.57M
  PragmaNamespace *NS = PragmaHandlers.get();
980
981
  // If this is specified to be in a namespace, step down into it.
982
2.57M
  if (!Namespace.empty()) {
983
1.28M
    PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
984
1.28M
    assert(Existing && "Namespace containing handler does not exist!");
985
986
0
    NS = Existing->getIfNamespace();
987
1.28M
    assert(NS && "Invalid namespace, registered as a regular pragma handler!");
988
1.28M
  }
989
990
0
  NS->RemovePragmaHandler(Handler);
991
992
  // If this is a non-default namespace and it is now empty, remove it.
993
2.57M
  if (NS != PragmaHandlers.get() && 
NS->IsEmpty()1.28M
) {
994
86.5k
    PragmaHandlers->RemovePragmaHandler(NS);
995
86.5k
    delete NS;
996
86.5k
  }
997
2.57M
}
998
999
79
bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
1000
79
  Token Tok;
1001
79
  LexUnexpandedToken(Tok);
1002
1003
79
  if (Tok.isNot(tok::identifier)) {
1004
4
    Diag(Tok, diag::ext_on_off_switch_syntax);
1005
4
    return true;
1006
4
  }
1007
75
  IdentifierInfo *II = Tok.getIdentifierInfo();
1008
75
  if (II->isStr("ON"))
1009
49
    Result = tok::OOS_ON;
1010
26
  else if (II->isStr("OFF"))
1011
17
    Result = tok::OOS_OFF;
1012
9
  else if (II->isStr("DEFAULT"))
1013
3
    Result = tok::OOS_DEFAULT;
1014
6
  else {
1015
6
    Diag(Tok, diag::ext_on_off_switch_syntax);
1016
6
    return true;
1017
6
  }
1018
1019
  // Verify that this is followed by EOD.
1020
69
  LexUnexpandedToken(Tok);
1021
69
  if (Tok.isNot(tok::eod))
1022
1
    Diag(Tok, diag::ext_pragma_syntax_eod);
1023
69
  return false;
1024
75
}
1025
1026
namespace {
1027
1028
/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
1029
struct PragmaOnceHandler : public PragmaHandler {
1030
87.9k
  PragmaOnceHandler() : PragmaHandler("once") {}
1031
1032
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1033
273
                    Token &OnceTok) override {
1034
273
    PP.CheckEndOfDirective("pragma once");
1035
273
    PP.HandlePragmaOnce(OnceTok);
1036
273
  }
1037
};
1038
1039
/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
1040
/// rest of the line is not lexed.
1041
struct PragmaMarkHandler : public PragmaHandler {
1042
87.9k
  PragmaMarkHandler() : PragmaHandler("mark") {}
1043
1044
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1045
37.5k
                    Token &MarkTok) override {
1046
37.5k
    PP.HandlePragmaMark(MarkTok);
1047
37.5k
  }
1048
};
1049
1050
/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
1051
struct PragmaPoisonHandler : public PragmaHandler {
1052
175k
  PragmaPoisonHandler() : PragmaHandler("poison") {}
1053
1054
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1055
5
                    Token &PoisonTok) override {
1056
5
    PP.HandlePragmaPoison();
1057
5
  }
1058
};
1059
1060
/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
1061
/// as a system header, which silences warnings in it.
1062
struct PragmaSystemHeaderHandler : public PragmaHandler {
1063
187k
  PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
1064
1065
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1066
133k
                    Token &SHToken) override {
1067
133k
    PP.HandlePragmaSystemHeader(SHToken);
1068
133k
    PP.CheckEndOfDirective("pragma");
1069
133k
  }
1070
};
1071
1072
/// PragmaIncludeInsteadHandler - "\#pragma clang include_instead(header)" marks
1073
/// the current file as non-includable if the including header is not a system
1074
/// header.
1075
struct PragmaIncludeInsteadHandler : public PragmaHandler {
1076
87.9k
  PragmaIncludeInsteadHandler() : PragmaHandler("include_instead") {}
1077
1078
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1079
18
                    Token &IIToken) override {
1080
18
    PP.HandlePragmaIncludeInstead(IIToken);
1081
18
  }
1082
};
1083
1084
struct PragmaDependencyHandler : public PragmaHandler {
1085
175k
  PragmaDependencyHandler() : PragmaHandler("dependency") {}
1086
1087
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1088
4
                    Token &DepToken) override {
1089
4
    PP.HandlePragmaDependency(DepToken);
1090
4
  }
1091
};
1092
1093
struct PragmaDebugHandler : public PragmaHandler {
1094
87.9k
  PragmaDebugHandler() : PragmaHandler("__debug") {}
1095
1096
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1097
131
                    Token &DebugToken) override {
1098
131
    Token Tok;
1099
131
    PP.LexUnexpandedToken(Tok);
1100
131
    if (Tok.isNot(tok::identifier)) {
1101
0
      PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1102
0
      return;
1103
0
    }
1104
131
    IdentifierInfo *II = Tok.getIdentifierInfo();
1105
1106
131
    if (II->isStr("assert")) {
1107
2
      if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1108
1
        llvm_unreachable("This is an assertion!");
1109
129
    } else if (II->isStr("crash")) {
1110
13
      llvm::Timer T("crash", "pragma crash");
1111
13
      llvm::TimeRegion R(&T);
1112
13
      if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1113
9
        LLVM_BUILTIN_TRAP;
1114
116
    } else if (II->isStr("parser_crash")) {
1115
19
      if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash) {
1116
12
        Token Crasher;
1117
12
        Crasher.startToken();
1118
12
        Crasher.setKind(tok::annot_pragma_parser_crash);
1119
12
        Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
1120
12
        PP.EnterToken(Crasher, /*IsReinject*/ false);
1121
12
      }
1122
97
    } else if (II->isStr("dump")) {
1123
21
      Token Identifier;
1124
21
      PP.LexUnexpandedToken(Identifier);
1125
21
      if (auto *DumpII = Identifier.getIdentifierInfo()) {
1126
21
        Token DumpAnnot;
1127
21
        DumpAnnot.startToken();
1128
21
        DumpAnnot.setKind(tok::annot_pragma_dump);
1129
21
        DumpAnnot.setAnnotationRange(
1130
21
            SourceRange(Tok.getLocation(), Identifier.getLocation()));
1131
21
        DumpAnnot.setAnnotationValue(DumpII);
1132
21
        PP.DiscardUntilEndOfDirective();
1133
21
        PP.EnterToken(DumpAnnot, /*IsReinject*/false);
1134
21
      } else {
1135
0
        PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
1136
0
            << II->getName();
1137
0
      }
1138
76
    } else if (II->isStr("diag_mapping")) {
1139
3
      Token DiagName;
1140
3
      PP.LexUnexpandedToken(DiagName);
1141
3
      if (DiagName.is(tok::eod))
1142
0
        PP.getDiagnostics().dump();
1143
3
      else if (DiagName.is(tok::string_literal) && !DiagName.hasUDSuffix()) {
1144
3
        StringLiteralParser Literal(DiagName, PP);
1145
3
        if (Literal.hadError)
1146
0
          return;
1147
3
        PP.getDiagnostics().dump(Literal.GetString());
1148
3
      } else {
1149
0
        PP.Diag(DiagName, diag::warn_pragma_debug_missing_argument)
1150
0
            << II->getName();
1151
0
      }
1152
73
    } else if (II->isStr("llvm_fatal_error")) {
1153
2
      if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1154
1
        llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1155
71
    } else if (II->isStr("llvm_unreachable")) {
1156
2
      if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1157
1
        llvm_unreachable("#pragma clang __debug llvm_unreachable");
1158
69
    } else if (II->isStr("macro")) {
1159
10
      Token MacroName;
1160
10
      PP.LexUnexpandedToken(MacroName);
1161
10
      auto *MacroII = MacroName.getIdentifierInfo();
1162
10
      if (MacroII)
1163
10
        PP.dumpMacroInfo(MacroII);
1164
0
      else
1165
0
        PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1166
0
            << II->getName();
1167
59
    } else if (II->isStr("module_map")) {
1168
0
      llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1169
0
          ModuleName;
1170
0
      if (LexModuleName(PP, Tok, ModuleName))
1171
0
        return;
1172
0
      ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
1173
0
      Module *M = nullptr;
1174
0
      for (auto IIAndLoc : ModuleName) {
1175
0
        M = MM.lookupModuleQualified(IIAndLoc.first->getName(), M);
1176
0
        if (!M) {
1177
0
          PP.Diag(IIAndLoc.second, diag::warn_pragma_debug_unknown_module)
1178
0
              << IIAndLoc.first;
1179
0
          return;
1180
0
        }
1181
0
      }
1182
0
      M->dump();
1183
59
    } else if (II->isStr("overflow_stack")) {
1184
0
      if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1185
0
        DebugOverflowStack();
1186
59
    } else if (II->isStr("captured")) {
1187
59
      HandleCaptured(PP);
1188
59
    } else 
if (0
II->isStr("modules")0
) {
1189
0
      struct ModuleVisitor {
1190
0
        Preprocessor &PP;
1191
0
        void visit(Module *M, bool VisibleOnly) {
1192
0
          SourceLocation ImportLoc = PP.getModuleImportLoc(M);
1193
0
          if (!VisibleOnly || ImportLoc.isValid()) {
1194
0
            llvm::errs() << M->getFullModuleName() << " ";
1195
0
            if (ImportLoc.isValid()) {
1196
0
              llvm::errs() << M << " visible ";
1197
0
              ImportLoc.print(llvm::errs(), PP.getSourceManager());
1198
0
            }
1199
0
            llvm::errs() << "\n";
1200
0
          }
1201
0
          for (Module *Sub : M->submodules()) {
1202
0
            if (!VisibleOnly || ImportLoc.isInvalid() || Sub->IsExplicit)
1203
0
              visit(Sub, VisibleOnly);
1204
0
          }
1205
0
        }
1206
0
        void visitAll(bool VisibleOnly) {
1207
0
          for (auto &NameAndMod :
1208
0
               PP.getHeaderSearchInfo().getModuleMap().modules())
1209
0
            visit(NameAndMod.second, VisibleOnly);
1210
0
        }
1211
0
      } Visitor{PP};
1212
1213
0
      Token Kind;
1214
0
      PP.LexUnexpandedToken(Kind);
1215
0
      auto *DumpII = Kind.getIdentifierInfo();
1216
0
      if (!DumpII) {
1217
0
        PP.Diag(Kind, diag::warn_pragma_debug_missing_argument)
1218
0
            << II->getName();
1219
0
      } else if (DumpII->isStr("all")) {
1220
0
        Visitor.visitAll(false);
1221
0
      } else if (DumpII->isStr("visible")) {
1222
0
        Visitor.visitAll(true);
1223
0
      } else if (DumpII->isStr("building")) {
1224
0
        for (auto &Building : PP.getBuildingSubmodules()) {
1225
0
          llvm::errs() << "in " << Building.M->getFullModuleName();
1226
0
          if (Building.ImportLoc.isValid()) {
1227
0
            llvm::errs() << " imported ";
1228
0
            if (Building.IsPragma)
1229
0
              llvm::errs() << "via pragma ";
1230
0
            llvm::errs() << "at ";
1231
0
            Building.ImportLoc.print(llvm::errs(), PP.getSourceManager());
1232
0
            llvm::errs() << "\n";
1233
0
          }
1234
0
        }
1235
0
      } else {
1236
0
        PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1237
0
          << DumpII->getName();
1238
0
      }
1239
0
    } else {
1240
0
      PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1241
0
        << II->getName();
1242
0
    }
1243
1244
122
    PPCallbacks *Callbacks = PP.getPPCallbacks();
1245
122
    if (Callbacks)
1246
118
      Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1247
122
  }
1248
1249
59
  void HandleCaptured(Preprocessor &PP) {
1250
59
    Token Tok;
1251
59
    PP.LexUnexpandedToken(Tok);
1252
1253
59
    if (Tok.isNot(tok::eod)) {
1254
1
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1255
1
        << "pragma clang __debug captured";
1256
1
      return;
1257
1
    }
1258
1259
58
    SourceLocation NameLoc = Tok.getLocation();
1260
58
    MutableArrayRef<Token> Toks(
1261
58
        PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1262
58
    Toks[0].startToken();
1263
58
    Toks[0].setKind(tok::annot_pragma_captured);
1264
58
    Toks[0].setLocation(NameLoc);
1265
1266
58
    PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
1267
58
                        /*IsReinject=*/false);
1268
58
  }
1269
1270
// Disable MSVC warning about runtime stack overflow.
1271
#ifdef _MSC_VER
1272
    #pragma warning(disable : 4717)
1273
#endif
1274
0
  static void DebugOverflowStack(void (*P)() = nullptr) {
1275
0
    void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1276
0
    Self(reinterpret_cast<void(*)()>(Self));
1277
0
  }
1278
#ifdef _MSC_VER
1279
    #pragma warning(default : 4717)
1280
#endif
1281
};
1282
1283
/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
1284
struct PragmaDiagnosticHandler : public PragmaHandler {
1285
private:
1286
  const char *Namespace;
1287
1288
public:
1289
  explicit PragmaDiagnosticHandler(const char *NS)
1290
175k
      : PragmaHandler("diagnostic"), Namespace(NS) {}
1291
1292
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1293
119k
                    Token &DiagToken) override {
1294
119k
    SourceLocation DiagLoc = DiagToken.getLocation();
1295
119k
    Token Tok;
1296
119k
    PP.LexUnexpandedToken(Tok);
1297
119k
    if (Tok.isNot(tok::identifier)) {
1298
0
      PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1299
0
      return;
1300
0
    }
1301
119k
    IdentifierInfo *II = Tok.getIdentifierInfo();
1302
119k
    PPCallbacks *Callbacks = PP.getPPCallbacks();
1303
1304
119k
    if (II->isStr("pop")) {
1305
31.0k
      if (!PP.getDiagnostics().popMappings(DiagLoc))
1306
2
        PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1307
31.0k
      else if (Callbacks)
1308
31.0k
        Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
1309
31.0k
      return;
1310
88.6k
    } else if (II->isStr("push")) {
1311
31.0k
      PP.getDiagnostics().pushMappings(DiagLoc);
1312
31.0k
      if (Callbacks)
1313
31.0k
        Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
1314
31.0k
      return;
1315
31.0k
    }
1316
1317
57.5k
    diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1318
57.5k
                            .Case("ignored", diag::Severity::Ignored)
1319
57.5k
                            .Case("warning", diag::Severity::Warning)
1320
57.5k
                            .Case("error", diag::Severity::Error)
1321
57.5k
                            .Case("fatal", diag::Severity::Fatal)
1322
57.5k
                            .Default(diag::Severity());
1323
1324
57.5k
    if (SV == diag::Severity()) {
1325
3
      PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1326
3
      return;
1327
3
    }
1328
1329
57.5k
    PP.LexUnexpandedToken(Tok);
1330
57.5k
    SourceLocation StringLoc = Tok.getLocation();
1331
1332
57.5k
    std::string WarningName;
1333
57.5k
    if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1334
57.5k
                                   /*AllowMacroExpansion=*/false))
1335
2
      return;
1336
1337
57.5k
    if (Tok.isNot(tok::eod)) {
1338
2
      PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1339
2
      return;
1340
2
    }
1341
1342
57.5k
    if (WarningName.size() < 3 || WarningName[0] != '-' ||
1343
57.5k
        
(57.5k
WarningName[1] != 'W'57.5k
&&
WarningName[1] != 'R'0
)) {
1344
2
      PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
1345
2
      return;
1346
2
    }
1347
1348
57.5k
    diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1349
57.5k
                                                : 
diag::Flavor::Remark0
;
1350
57.5k
    StringRef Group = StringRef(WarningName).substr(2);
1351
57.5k
    bool unknownDiag = false;
1352
57.5k
    if (Group == "everything") {
1353
      // Special handling for pragma clang diagnostic ... "-Weverything".
1354
      // There is no formal group named "everything", so there has to be a
1355
      // special case for it.
1356
19
      PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1357
19
    } else
1358
57.5k
      unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1359
57.5k
                                                            DiagLoc);
1360
57.5k
    if (unknownDiag)
1361
2
      PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1362
2
        << WarningName;
1363
57.5k
    else if (Callbacks)
1364
57.5k
      Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
1365
57.5k
  }
1366
};
1367
1368
/// "\#pragma hdrstop [<header-name-string>]"
1369
struct PragmaHdrstopHandler : public PragmaHandler {
1370
11.2k
  PragmaHdrstopHandler() : PragmaHandler("hdrstop") {}
1371
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1372
2
                    Token &DepToken) override {
1373
2
    PP.HandlePragmaHdrstop(DepToken);
1374
2
  }
1375
};
1376
1377
/// "\#pragma warning(...)".  MSVC's diagnostics do not map cleanly to clang's
1378
/// diagnostics, so we don't really implement this pragma.  We parse it and
1379
/// ignore it to avoid -Wunknown-pragma warnings.
1380
struct PragmaWarningHandler : public PragmaHandler {
1381
11.2k
  PragmaWarningHandler() : PragmaHandler("warning") {}
1382
1383
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1384
86
                    Token &Tok) override {
1385
    // Parse things like:
1386
    // warning(push, 1)
1387
    // warning(pop)
1388
    // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1389
86
    SourceLocation DiagLoc = Tok.getLocation();
1390
86
    PPCallbacks *Callbacks = PP.getPPCallbacks();
1391
1392
86
    PP.Lex(Tok);
1393
86
    if (Tok.isNot(tok::l_paren)) {
1394
2
      PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1395
2
      return;
1396
2
    }
1397
1398
84
    PP.Lex(Tok);
1399
84
    IdentifierInfo *II = Tok.getIdentifierInfo();
1400
1401
84
    if (II && 
II->isStr("push")72
) {
1402
      // #pragma warning( push[ ,n ] )
1403
32
      int Level = -1;
1404
32
      PP.Lex(Tok);
1405
32
      if (Tok.is(tok::comma)) {
1406
17
        PP.Lex(Tok);
1407
17
        uint64_t Value;
1408
17
        if (Tok.is(tok::numeric_constant) &&
1409
17
            
PP.parseSimpleIntegerLiteral(Tok, Value)15
)
1410
14
          Level = int(Value);
1411
17
        if (Level < 0 || 
Level > 414
) {
1412
5
          PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1413
5
          return;
1414
5
        }
1415
17
      }
1416
27
      PP.getDiagnostics().pushMappings(DiagLoc);
1417
27
      if (Callbacks)
1418
27
        Callbacks->PragmaWarningPush(DiagLoc, Level);
1419
52
    } else if (II && 
II->isStr("pop")40
) {
1420
      // #pragma warning( pop )
1421
13
      PP.Lex(Tok);
1422
13
      if (!PP.getDiagnostics().popMappings(DiagLoc))
1423
0
        PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1424
13
      else if (Callbacks)
1425
13
        Callbacks->PragmaWarningPop(DiagLoc);
1426
39
    } else {
1427
      // #pragma warning( warning-specifier : warning-number-list
1428
      //                  [; warning-specifier : warning-number-list...] )
1429
45
      while (true) {
1430
45
        II = Tok.getIdentifierInfo();
1431
45
        if (!II && 
!Tok.is(tok::numeric_constant)14
) {
1432
4
          PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1433
4
          return;
1434
4
        }
1435
1436
        // Figure out which warning specifier this is.
1437
41
        bool SpecifierValid;
1438
41
        PPCallbacks::PragmaWarningSpecifier Specifier;
1439
41
        if (II) {
1440
31
          int SpecifierInt = llvm::StringSwitch<int>(II->getName())
1441
31
                                 .Case("default", PPCallbacks::PWS_Default)
1442
31
                                 .Case("disable", PPCallbacks::PWS_Disable)
1443
31
                                 .Case("error", PPCallbacks::PWS_Error)
1444
31
                                 .Case("once", PPCallbacks::PWS_Once)
1445
31
                                 .Case("suppress", PPCallbacks::PWS_Suppress)
1446
31
                                 .Default(-1);
1447
31
          if ((SpecifierValid = SpecifierInt != -1))
1448
29
            Specifier =
1449
29
                static_cast<PPCallbacks::PragmaWarningSpecifier>(SpecifierInt);
1450
1451
          // If we read a correct specifier, snatch next token (that should be
1452
          // ":", checked later).
1453
31
          if (SpecifierValid)
1454
29
            PP.Lex(Tok);
1455
31
        } else {
1456
          // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1457
10
          uint64_t Value;
1458
10
          if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1459
10
            if ((SpecifierValid = (Value >= 1) && (Value <= 4)))
1460
8
              Specifier = static_cast<PPCallbacks::PragmaWarningSpecifier>(
1461
8
                  PPCallbacks::PWS_Level1 + Value - 1);
1462
10
          } else
1463
0
            SpecifierValid = false;
1464
          // Next token already snatched by parseSimpleIntegerLiteral.
1465
10
        }
1466
1467
41
        if (!SpecifierValid) {
1468
4
          PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1469
4
          return;
1470
4
        }
1471
37
        if (Tok.isNot(tok::colon)) {
1472
4
          PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1473
4
          return;
1474
4
        }
1475
1476
        // Collect the warning ids.
1477
33
        SmallVector<int, 4> Ids;
1478
33
        PP.Lex(Tok);
1479
76
        while (Tok.is(tok::numeric_constant)) {
1480
45
          uint64_t Value;
1481
45
          if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1482
45
              
Value > INT_MAX43
) {
1483
2
            PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1484
2
            return;
1485
2
          }
1486
43
          Ids.push_back(int(Value));
1487
43
        }
1488
1489
        // Only act on disable for now.
1490
31
        diag::Severity SV = diag::Severity();
1491
31
        if (Specifier == PPCallbacks::PWS_Disable)
1492
13
          SV = diag::Severity::Ignored;
1493
31
        if (SV != diag::Severity())
1494
19
          
for (int Id : Ids)13
{
1495
19
            if (auto Group = diagGroupFromCLWarningID(Id)) {
1496
2
              bool unknownDiag = PP.getDiagnostics().setSeverityForGroup(
1497
2
                  diag::Flavor::WarningOrError, *Group, SV, DiagLoc);
1498
2
              assert(!unknownDiag &&
1499
2
                     "wd table should only contain known diags");
1500
0
              (void)unknownDiag;
1501
2
            }
1502
19
          }
1503
1504
31
        if (Callbacks)
1505
31
          Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1506
1507
        // Parse the next specifier if there is a semicolon.
1508
31
        if (Tok.isNot(tok::semi))
1509
25
          break;
1510
6
        PP.Lex(Tok);
1511
6
      }
1512
39
    }
1513
1514
65
    if (Tok.isNot(tok::r_paren)) {
1515
6
      PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1516
6
      return;
1517
6
    }
1518
1519
59
    PP.Lex(Tok);
1520
59
    if (Tok.isNot(tok::eod))
1521
2
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1522
59
  }
1523
};
1524
1525
/// "\#pragma execution_character_set(...)". MSVC supports this pragma only
1526
/// for "UTF-8". We parse it and ignore it if UTF-8 is provided and warn
1527
/// otherwise to avoid -Wunknown-pragma warnings.
1528
struct PragmaExecCharsetHandler : public PragmaHandler {
1529
11.2k
  PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {}
1530
1531
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1532
32
                    Token &Tok) override {
1533
    // Parse things like:
1534
    // execution_character_set(push, "UTF-8")
1535
    // execution_character_set(pop)
1536
32
    SourceLocation DiagLoc = Tok.getLocation();
1537
32
    PPCallbacks *Callbacks = PP.getPPCallbacks();
1538
1539
32
    PP.Lex(Tok);
1540
32
    if (Tok.isNot(tok::l_paren)) {
1541
2
      PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << "(";
1542
2
      return;
1543
2
    }
1544
1545
30
    PP.Lex(Tok);
1546
30
    IdentifierInfo *II = Tok.getIdentifierInfo();
1547
1548
30
    if (II && 
II->isStr("push")26
) {
1549
      // #pragma execution_character_set( push[ , string ] )
1550
16
      PP.Lex(Tok);
1551
16
      if (Tok.is(tok::comma)) {
1552
12
        PP.Lex(Tok);
1553
1554
12
        std::string ExecCharset;
1555
12
        if (!PP.FinishLexStringLiteral(Tok, ExecCharset,
1556
12
                                       "pragma execution_character_set",
1557
12
                                       /*AllowMacroExpansion=*/false))
1558
6
          return;
1559
1560
        // MSVC supports either of these, but nothing else.
1561
6
        if (ExecCharset != "UTF-8" && 
ExecCharset != "utf-8"4
) {
1562
2
          PP.Diag(Tok, diag::warn_pragma_exec_charset_push_invalid) << ExecCharset;
1563
2
          return;
1564
2
        }
1565
6
      }
1566
8
      if (Callbacks)
1567
8
        Callbacks->PragmaExecCharsetPush(DiagLoc, "UTF-8");
1568
14
    } else if (II && 
II->isStr("pop")10
) {
1569
      // #pragma execution_character_set( pop )
1570
6
      PP.Lex(Tok);
1571
6
      if (Callbacks)
1572
6
        Callbacks->PragmaExecCharsetPop(DiagLoc);
1573
8
    } else {
1574
8
      PP.Diag(Tok, diag::warn_pragma_exec_charset_spec_invalid);
1575
8
      return;
1576
8
    }
1577
1578
14
    if (Tok.isNot(tok::r_paren)) {
1579
6
      PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << ")";
1580
6
      return;
1581
6
    }
1582
1583
8
    PP.Lex(Tok);
1584
8
    if (Tok.isNot(tok::eod))
1585
0
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma execution_character_set";
1586
8
  }
1587
};
1588
1589
/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1590
struct PragmaIncludeAliasHandler : public PragmaHandler {
1591
11.2k
  PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1592
1593
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1594
24
                    Token &IncludeAliasTok) override {
1595
24
    PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1596
24
  }
1597
};
1598
1599
/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1600
/// extension.  The syntax is:
1601
/// \code
1602
///   #pragma message(string)
1603
/// \endcode
1604
/// OR, in GCC mode:
1605
/// \code
1606
///   #pragma message string
1607
/// \endcode
1608
/// string is a string, which is fully macro expanded, and permits string
1609
/// concatenation, embedded escape characters, etc... See MSDN for more details.
1610
/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1611
/// form as \#pragma message.
1612
struct PragmaMessageHandler : public PragmaHandler {
1613
private:
1614
  const PPCallbacks::PragmaMessageKind Kind;
1615
  const StringRef Namespace;
1616
1617
  static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1618
263k
                                bool PragmaNameOnly = false) {
1619
263k
    switch (Kind) {
1620
87.9k
      case PPCallbacks::PMK_Message:
1621
87.9k
        return PragmaNameOnly ? 
"message"87.9k
:
"pragma message"15
;
1622
87.9k
      case PPCallbacks::PMK_Warning:
1623
87.9k
        return PragmaNameOnly ? 
"warning"87.9k
:
"pragma warning"10
;
1624
87.9k
      case PPCallbacks::PMK_Error:
1625
87.9k
        return PragmaNameOnly ? 
"error"87.9k
:
"pragma error"10
;
1626
263k
    }
1627
0
    llvm_unreachable("Unknown PragmaMessageKind!");
1628
0
  }
1629
1630
public:
1631
  PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1632
                       StringRef Namespace = StringRef())
1633
      : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
1634
263k
        Namespace(Namespace) {}
1635
1636
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1637
37
                    Token &Tok) override {
1638
37
    SourceLocation MessageLoc = Tok.getLocation();
1639
37
    PP.Lex(Tok);
1640
37
    bool ExpectClosingParen = false;
1641
37
    switch (Tok.getKind()) {
1642
18
    case tok::l_paren:
1643
      // We have a MSVC style pragma message.
1644
18
      ExpectClosingParen = true;
1645
      // Read the string.
1646
18
      PP.Lex(Tok);
1647
18
      break;
1648
17
    case tok::string_literal:
1649
      // We have a GCC style pragma message, and we just read the string.
1650
17
      break;
1651
2
    default:
1652
2
      PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1653
2
      return;
1654
37
    }
1655
1656
35
    std::string MessageString;
1657
35
    if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1658
35
                                   /*AllowMacroExpansion=*/true))
1659
4
      return;
1660
1661
31
    if (ExpectClosingParen) {
1662
14
      if (Tok.isNot(tok::r_paren)) {
1663
2
        PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1664
2
        return;
1665
2
      }
1666
12
      PP.Lex(Tok);  // eat the r_paren.
1667
12
    }
1668
1669
29
    if (Tok.isNot(tok::eod)) {
1670
0
      PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1671
0
      return;
1672
0
    }
1673
1674
    // Output the message.
1675
29
    PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1676
29
                          ? 
diag::err_pragma_message8
1677
29
                          : 
diag::warn_pragma_message21
) << MessageString;
1678
1679
    // If the pragma is lexically sound, notify any interested PPCallbacks.
1680
29
    if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1681
29
      Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1682
29
  }
1683
};
1684
1685
/// Handle the clang \#pragma module import extension. The syntax is:
1686
/// \code
1687
///   #pragma clang module import some.module.name
1688
/// \endcode
1689
struct PragmaModuleImportHandler : public PragmaHandler {
1690
87.9k
  PragmaModuleImportHandler() : PragmaHandler("import") {}
1691
1692
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1693
121
                    Token &Tok) override {
1694
121
    SourceLocation ImportLoc = Tok.getLocation();
1695
1696
    // Read the module name.
1697
121
    llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1698
121
        ModuleName;
1699
121
    if (LexModuleName(PP, Tok, ModuleName))
1700
6
      return;
1701
1702
115
    if (Tok.isNot(tok::eod))
1703
2
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1704
1705
    // If we have a non-empty module path, load the named module.
1706
115
    Module *Imported =
1707
115
        PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1708
115
                                      /*IsInclusionDirective=*/false);
1709
115
    if (!Imported)
1710
0
      return;
1711
1712
115
    PP.makeModuleVisible(Imported, ImportLoc);
1713
115
    PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1714
115
                            tok::annot_module_include, Imported);
1715
115
    if (auto *CB = PP.getPPCallbacks())
1716
115
      CB->moduleImport(ImportLoc, ModuleName, Imported);
1717
115
  }
1718
};
1719
1720
/// Handle the clang \#pragma module begin extension. The syntax is:
1721
/// \code
1722
///   #pragma clang module begin some.module.name
1723
///   ...
1724
///   #pragma clang module end
1725
/// \endcode
1726
struct PragmaModuleBeginHandler : public PragmaHandler {
1727
87.9k
  PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1728
1729
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1730
145
                    Token &Tok) override {
1731
145
    SourceLocation BeginLoc = Tok.getLocation();
1732
1733
    // Read the module name.
1734
145
    llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1735
145
        ModuleName;
1736
145
    if (LexModuleName(PP, Tok, ModuleName))
1737
2
      return;
1738
1739
143
    if (Tok.isNot(tok::eod))
1740
2
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1741
1742
    // We can only enter submodules of the current module.
1743
143
    StringRef Current = PP.getLangOpts().CurrentModule;
1744
143
    if (ModuleName.front().first->getName() != Current) {
1745
0
      PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1746
0
        << ModuleName.front().first << (ModuleName.size() > 1)
1747
0
        << Current.empty() << Current;
1748
0
      return;
1749
0
    }
1750
1751
    // Find the module we're entering. We require that a module map for it
1752
    // be loaded or implicitly loadable.
1753
143
    auto &HSI = PP.getHeaderSearchInfo();
1754
143
    Module *M = HSI.lookupModule(Current, ModuleName.front().second);
1755
143
    if (!M) {
1756
0
      PP.Diag(ModuleName.front().second,
1757
0
              diag::err_pp_module_begin_no_module_map) << Current;
1758
0
      return;
1759
0
    }
1760
190
    
for (unsigned I = 1; 143
I != ModuleName.size();
++I47
) {
1761
47
      auto *NewM = M->findOrInferSubmodule(ModuleName[I].first->getName());
1762
47
      if (!NewM) {
1763
0
        PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1764
0
          << M->getFullModuleName() << ModuleName[I].first;
1765
0
        return;
1766
0
      }
1767
47
      M = NewM;
1768
47
    }
1769
1770
    // If the module isn't available, it doesn't make sense to enter it.
1771
143
    if (Preprocessor::checkModuleIsAvailable(
1772
143
            PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
1773
1
      PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1774
1
        << M->getTopLevelModuleName();
1775
1
      return;
1776
1
    }
1777
1778
    // Enter the scope of the submodule.
1779
142
    PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1780
142
    PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1781
142
                            tok::annot_module_begin, M);
1782
142
  }
1783
};
1784
1785
/// Handle the clang \#pragma module end extension.
1786
struct PragmaModuleEndHandler : public PragmaHandler {
1787
87.9k
  PragmaModuleEndHandler() : PragmaHandler("end") {}
1788
1789
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1790
143
                    Token &Tok) override {
1791
143
    SourceLocation Loc = Tok.getLocation();
1792
1793
143
    PP.LexUnexpandedToken(Tok);
1794
143
    if (Tok.isNot(tok::eod))
1795
2
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1796
1797
143
    Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1798
143
    if (M)
1799
140
      PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1800
3
    else
1801
3
      PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
1802
143
  }
1803
};
1804
1805
/// Handle the clang \#pragma module build extension.
1806
struct PragmaModuleBuildHandler : public PragmaHandler {
1807
87.9k
  PragmaModuleBuildHandler() : PragmaHandler("build") {}
1808
1809
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1810
76
                    Token &Tok) override {
1811
76
    PP.HandlePragmaModuleBuild(Tok);
1812
76
  }
1813
};
1814
1815
/// Handle the clang \#pragma module load extension.
1816
struct PragmaModuleLoadHandler : public PragmaHandler {
1817
87.9k
  PragmaModuleLoadHandler() : PragmaHandler("load") {}
1818
1819
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1820
6
                    Token &Tok) override {
1821
6
    SourceLocation Loc = Tok.getLocation();
1822
1823
    // Read the module name.
1824
6
    llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1825
6
        ModuleName;
1826
6
    if (LexModuleName(PP, Tok, ModuleName))
1827
0
      return;
1828
1829
6
    if (Tok.isNot(tok::eod))
1830
0
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1831
1832
    // Load the module, don't make it visible.
1833
6
    PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1834
6
                                    /*IsInclusionDirective=*/false);
1835
6
  }
1836
};
1837
1838
/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1839
/// macro on the top of the stack.
1840
struct PragmaPushMacroHandler : public PragmaHandler {
1841
87.9k
  PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1842
1843
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1844
23.4k
                    Token &PushMacroTok) override {
1845
23.4k
    PP.HandlePragmaPushMacro(PushMacroTok);
1846
23.4k
  }
1847
};
1848
1849
/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1850
/// macro to the value on the top of the stack.
1851
struct PragmaPopMacroHandler : public PragmaHandler {
1852
87.9k
  PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1853
1854
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1855
23.4k
                    Token &PopMacroTok) override {
1856
23.4k
    PP.HandlePragmaPopMacro(PopMacroTok);
1857
23.4k
  }
1858
};
1859
1860
/// PragmaARCCFCodeAuditedHandler -
1861
///   \#pragma clang arc_cf_code_audited begin/end
1862
struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1863
87.9k
  PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1864
1865
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1866
63.6k
                    Token &NameTok) override {
1867
63.6k
    SourceLocation Loc = NameTok.getLocation();
1868
63.6k
    bool IsBegin;
1869
1870
63.6k
    Token Tok;
1871
1872
    // Lex the 'begin' or 'end'.
1873
63.6k
    PP.LexUnexpandedToken(Tok);
1874
63.6k
    const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1875
63.6k
    if (BeginEnd && BeginEnd->isStr("begin")) {
1876
31.8k
      IsBegin = true;
1877
31.8k
    } else 
if (31.8k
BeginEnd31.8k
&&
BeginEnd->isStr("end")31.8k
) {
1878
31.8k
      IsBegin = false;
1879
31.8k
    } else {
1880
1
      PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1881
1
      return;
1882
1
    }
1883
1884
    // Verify that this is followed by EOD.
1885
63.6k
    PP.LexUnexpandedToken(Tok);
1886
63.6k
    if (Tok.isNot(tok::eod))
1887
1
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1888
1889
    // The start location of the active audit.
1890
63.6k
    SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedInfo().second;
1891
1892
    // The start location we want after processing this.
1893
63.6k
    SourceLocation NewLoc;
1894
1895
63.6k
    if (IsBegin) {
1896
      // Complain about attempts to re-enter an audit.
1897
31.8k
      if (BeginLoc.isValid()) {
1898
1
        PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1899
1
        PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1900
1
      }
1901
31.8k
      NewLoc = Loc;
1902
31.8k
    } else {
1903
      // Complain about attempts to leave an audit that doesn't exist.
1904
31.8k
      if (!BeginLoc.isValid()) {
1905
1
        PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1906
1
        return;
1907
1
      }
1908
31.8k
      NewLoc = SourceLocation();
1909
31.8k
    }
1910
1911
63.6k
    PP.setPragmaARCCFCodeAuditedInfo(NameTok.getIdentifierInfo(), NewLoc);
1912
63.6k
  }
1913
};
1914
1915
/// PragmaAssumeNonNullHandler -
1916
///   \#pragma clang assume_nonnull begin/end
1917
struct PragmaAssumeNonNullHandler : public PragmaHandler {
1918
87.9k
  PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1919
1920
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1921
143k
                    Token &NameTok) override {
1922
143k
    SourceLocation Loc = NameTok.getLocation();
1923
143k
    bool IsBegin;
1924
1925
143k
    Token Tok;
1926
1927
    // Lex the 'begin' or 'end'.
1928
143k
    PP.LexUnexpandedToken(Tok);
1929
143k
    const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1930
143k
    if (BeginEnd && BeginEnd->isStr("begin")) {
1931
71.6k
      IsBegin = true;
1932
71.6k
    } else 
if (71.6k
BeginEnd71.6k
&&
BeginEnd->isStr("end")71.6k
) {
1933
71.6k
      IsBegin = false;
1934
71.6k
    } else {
1935
1
      PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1936
1
      return;
1937
1
    }
1938
1939
    // Verify that this is followed by EOD.
1940
143k
    PP.LexUnexpandedToken(Tok);
1941
143k
    if (Tok.isNot(tok::eod))
1942
0
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1943
1944
    // The start location of the active audit.
1945
143k
    SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1946
1947
    // The start location we want after processing this.
1948
143k
    SourceLocation NewLoc;
1949
143k
    PPCallbacks *Callbacks = PP.getPPCallbacks();
1950
1951
143k
    if (IsBegin) {
1952
      // Complain about attempts to re-enter an audit.
1953
71.6k
      if (BeginLoc.isValid()) {
1954
1
        PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1955
1
        PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1956
1
      }
1957
71.6k
      NewLoc = Loc;
1958
71.6k
      if (Callbacks)
1959
71.6k
        Callbacks->PragmaAssumeNonNullBegin(NewLoc);
1960
71.6k
    } else {
1961
      // Complain about attempts to leave an audit that doesn't exist.
1962
71.6k
      if (!BeginLoc.isValid()) {
1963
0
        PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1964
0
        return;
1965
0
      }
1966
71.6k
      NewLoc = SourceLocation();
1967
71.6k
      if (Callbacks)
1968
71.6k
        Callbacks->PragmaAssumeNonNullEnd(NewLoc);
1969
71.6k
    }
1970
1971
143k
    PP.setPragmaAssumeNonNullLoc(NewLoc);
1972
143k
  }
1973
};
1974
1975
/// Handle "\#pragma region [...]"
1976
///
1977
/// The syntax is
1978
/// \code
1979
///   #pragma region [optional name]
1980
///   #pragma endregion [optional comment]
1981
/// \endcode
1982
///
1983
/// \note This is
1984
/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1985
/// pragma, just skipped by compiler.
1986
struct PragmaRegionHandler : public PragmaHandler {
1987
175k
  PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
1988
1989
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1990
11
                    Token &NameTok) override {
1991
    // #pragma region: endregion matches can be verified
1992
    // __pragma(region): no sense, but ignored by msvc
1993
    // _Pragma is not valid for MSVC, but there isn't any point
1994
    // to handle a _Pragma differently.
1995
11
  }
1996
};
1997
1998
/// This handles parsing pragmas that take a macro name and optional message
1999
static IdentifierInfo *HandleMacroAnnotationPragma(Preprocessor &PP, Token &Tok,
2000
                                                   const char *Pragma,
2001
42
                                                   std::string &MessageString) {
2002
42
  std::string Macro;
2003
2004
42
  PP.Lex(Tok);
2005
42
  if (Tok.isNot(tok::l_paren)) {
2006
2
    PP.Diag(Tok, diag::err_expected) << "(";
2007
2
    return nullptr;
2008
2
  }
2009
2010
40
  PP.LexUnexpandedToken(Tok);
2011
40
  if (!Tok.is(tok::identifier)) {
2012
2
    PP.Diag(Tok, diag::err_expected) << tok::identifier;
2013
2
    return nullptr;
2014
2
  }
2015
38
  IdentifierInfo *II = Tok.getIdentifierInfo();
2016
2017
38
  if (!II->hasMacroDefinition()) {
2018
3
    PP.Diag(Tok, diag::err_pp_visibility_non_macro) << II;
2019
3
    return nullptr;
2020
3
  }
2021
2022
35
  PP.Lex(Tok);
2023
35
  if (Tok.is(tok::comma)) {
2024
8
    PP.Lex(Tok);
2025
8
    if (!PP.FinishLexStringLiteral(Tok, MessageString, Pragma,
2026
8
                                   /*AllowMacroExpansion=*/true))
2027
0
      return nullptr;
2028
8
  }
2029
2030
35
  if (Tok.isNot(tok::r_paren)) {
2031
2
    PP.Diag(Tok, diag::err_expected) << ")";
2032
2
    return nullptr;
2033
2
  }
2034
33
  return II;
2035
35
}
2036
2037
/// "\#pragma clang deprecated(...)"
2038
///
2039
/// The syntax is
2040
/// \code
2041
///   #pragma clang deprecate(MACRO_NAME [, Message])
2042
/// \endcode
2043
struct PragmaDeprecatedHandler : public PragmaHandler {
2044
87.9k
  PragmaDeprecatedHandler() : PragmaHandler("deprecated") {}
2045
2046
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2047
32
                    Token &Tok) override {
2048
32
    std::string MessageString;
2049
2050
32
    if (IdentifierInfo *II = HandleMacroAnnotationPragma(
2051
32
            PP, Tok, "#pragma clang deprecated", MessageString)) {
2052
26
      II->setIsDeprecatedMacro(true);
2053
26
      PP.addMacroDeprecationMsg(II, std::move(MessageString),
2054
26
                                Tok.getLocation());
2055
26
    }
2056
32
  }
2057
};
2058
2059
/// "\#pragma clang restrict_expansion(...)"
2060
///
2061
/// The syntax is
2062
/// \code
2063
///   #pragma clang restrict_expansion(MACRO_NAME [, Message])
2064
/// \endcode
2065
struct PragmaRestrictExpansionHandler : public PragmaHandler {
2066
87.9k
  PragmaRestrictExpansionHandler() : PragmaHandler("restrict_expansion") {}
2067
2068
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2069
10
                    Token &Tok) override {
2070
10
    std::string MessageString;
2071
2072
10
    if (IdentifierInfo *II = HandleMacroAnnotationPragma(
2073
10
            PP, Tok, "#pragma clang restrict_expansion", MessageString)) {
2074
7
      II->setIsRestrictExpansion(true);
2075
7
      PP.addRestrictExpansionMsg(II, std::move(MessageString),
2076
7
                                 Tok.getLocation());
2077
7
    }
2078
10
  }
2079
};
2080
2081
/// "\#pragma clang final(...)"
2082
///
2083
/// The syntax is
2084
/// \code
2085
///   #pragma clang final(MACRO_NAME)
2086
/// \endcode
2087
struct PragmaFinalHandler : public PragmaHandler {
2088
87.9k
  PragmaFinalHandler() : PragmaHandler("final") {}
2089
2090
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2091
8
                    Token &Tok) override {
2092
8
    std::string Macro;
2093
2094
8
    PP.Lex(Tok);
2095
8
    if (Tok.isNot(tok::l_paren)) {
2096
2
      PP.Diag(Tok, diag::err_expected) << "(";
2097
2
      return;
2098
2
    }
2099
2100
6
    PP.LexUnexpandedToken(Tok);
2101
6
    if (!Tok.is(tok::identifier)) {
2102
1
      PP.Diag(Tok, diag::err_expected) << tok::identifier;
2103
1
      return;
2104
1
    }
2105
5
    IdentifierInfo *II = Tok.getIdentifierInfo();
2106
2107
5
    if (!II->hasMacroDefinition()) {
2108
1
      PP.Diag(Tok, diag::err_pp_visibility_non_macro) << II;
2109
1
      return;
2110
1
    }
2111
2112
4
    PP.Lex(Tok);
2113
4
    if (Tok.isNot(tok::r_paren)) {
2114
1
      PP.Diag(Tok, diag::err_expected) << ")";
2115
1
      return;
2116
1
    }
2117
3
    II->setIsFinal(true);
2118
3
    PP.addFinalLoc(II, Tok.getLocation());
2119
3
  }
2120
};
2121
2122
} // namespace
2123
2124
/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
2125
/// \#pragma GCC poison/system_header/dependency and \#pragma once.
2126
87.9k
void Preprocessor::RegisterBuiltinPragmas() {
2127
87.9k
  AddPragmaHandler(new PragmaOnceHandler());
2128
87.9k
  AddPragmaHandler(new PragmaMarkHandler());
2129
87.9k
  AddPragmaHandler(new PragmaPushMacroHandler());
2130
87.9k
  AddPragmaHandler(new PragmaPopMacroHandler());
2131
87.9k
  AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
2132
2133
  // #pragma GCC ...
2134
87.9k
  AddPragmaHandler("GCC", new PragmaPoisonHandler());
2135
87.9k
  AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
2136
87.9k
  AddPragmaHandler("GCC", new PragmaDependencyHandler());
2137
87.9k
  AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
2138
87.9k
  AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
2139
87.9k
                                                   "GCC"));
2140
87.9k
  AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
2141
87.9k
                                                   "GCC"));
2142
  // #pragma clang ...
2143
87.9k
  AddPragmaHandler("clang", new PragmaPoisonHandler());
2144
87.9k
  AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
2145
87.9k
  AddPragmaHandler("clang", new PragmaIncludeInsteadHandler());
2146
87.9k
  AddPragmaHandler("clang", new PragmaDebugHandler());
2147
87.9k
  AddPragmaHandler("clang", new PragmaDependencyHandler());
2148
87.9k
  AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
2149
87.9k
  AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
2150
87.9k
  AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
2151
87.9k
  AddPragmaHandler("clang", new PragmaDeprecatedHandler());
2152
87.9k
  AddPragmaHandler("clang", new PragmaRestrictExpansionHandler());
2153
87.9k
  AddPragmaHandler("clang", new PragmaFinalHandler());
2154
2155
  // #pragma clang module ...
2156
87.9k
  auto *ModuleHandler = new PragmaNamespace("module");
2157
87.9k
  AddPragmaHandler("clang", ModuleHandler);
2158
87.9k
  ModuleHandler->AddPragma(new PragmaModuleImportHandler());
2159
87.9k
  ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
2160
87.9k
  ModuleHandler->AddPragma(new PragmaModuleEndHandler());
2161
87.9k
  ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
2162
87.9k
  ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
2163
2164
  // Add region pragmas.
2165
87.9k
  AddPragmaHandler(new PragmaRegionHandler("region"));
2166
87.9k
  AddPragmaHandler(new PragmaRegionHandler("endregion"));
2167
2168
  // MS extensions.
2169
87.9k
  if (LangOpts.MicrosoftExt) {
2170
11.2k
    AddPragmaHandler(new PragmaWarningHandler());
2171
11.2k
    AddPragmaHandler(new PragmaExecCharsetHandler());
2172
11.2k
    AddPragmaHandler(new PragmaIncludeAliasHandler());
2173
11.2k
    AddPragmaHandler(new PragmaHdrstopHandler());
2174
11.2k
    AddPragmaHandler(new PragmaSystemHeaderHandler());
2175
11.2k
  }
2176
2177
  // Pragmas added by plugins
2178
87.9k
  for (const PragmaHandlerRegistry::entry &handler :
2179
87.9k
       PragmaHandlerRegistry::entries()) {
2180
0
    AddPragmaHandler(handler.instantiate().release());
2181
0
  }
2182
87.9k
}
2183
2184
/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
2185
/// warn about those pragmas being unknown.
2186
1.64k
void Preprocessor::IgnorePragmas() {
2187
1.64k
  AddPragmaHandler(new EmptyPragmaHandler());
2188
  // Also ignore all pragmas in all namespaces created
2189
  // in Preprocessor::RegisterBuiltinPragmas().
2190
1.64k
  AddPragmaHandler("GCC", new EmptyPragmaHandler());
2191
1.64k
  AddPragmaHandler("clang", new EmptyPragmaHandler());
2192
1.64k
}