Coverage Report

Created: 2021-09-21 08:58

/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/Diagnostic.h"
16
#include "clang/Basic/DiagnosticLex.h"
17
#include "clang/Basic/FileManager.h"
18
#include "clang/Basic/IdentifierTable.h"
19
#include "clang/Basic/LLVM.h"
20
#include "clang/Basic/LangOptions.h"
21
#include "clang/Basic/Module.h"
22
#include "clang/Basic/SourceLocation.h"
23
#include "clang/Basic/SourceManager.h"
24
#include "clang/Basic/TokenKinds.h"
25
#include "clang/Lex/HeaderSearch.h"
26
#include "clang/Lex/LexDiagnostic.h"
27
#include "clang/Lex/Lexer.h"
28
#include "clang/Lex/LiteralSupport.h"
29
#include "clang/Lex/MacroInfo.h"
30
#include "clang/Lex/ModuleLoader.h"
31
#include "clang/Lex/PPCallbacks.h"
32
#include "clang/Lex/Preprocessor.h"
33
#include "clang/Lex/PreprocessorLexer.h"
34
#include "clang/Lex/PreprocessorOptions.h"
35
#include "clang/Lex/Token.h"
36
#include "clang/Lex/TokenLexer.h"
37
#include "llvm/ADT/ArrayRef.h"
38
#include "llvm/ADT/DenseMap.h"
39
#include "llvm/ADT/Optional.h"
40
#include "llvm/ADT/STLExtras.h"
41
#include "llvm/ADT/SmallString.h"
42
#include "llvm/ADT/SmallVector.h"
43
#include "llvm/ADT/StringRef.h"
44
#include "llvm/ADT/StringSwitch.h"
45
#include "llvm/Support/Compiler.h"
46
#include "llvm/Support/ErrorHandling.h"
47
#include "llvm/Support/Timer.h"
48
#include <algorithm>
49
#include <cassert>
50
#include <cstddef>
51
#include <cstdint>
52
#include <limits>
53
#include <string>
54
#include <utility>
55
#include <vector>
56
57
using namespace clang;
58
59
// Out-of-line destructor to provide a home for the class.
60
5.76M
PragmaHandler::~PragmaHandler() = default;
61
62
//===----------------------------------------------------------------------===//
63
// EmptyPragmaHandler Implementation.
64
//===----------------------------------------------------------------------===//
65
66
16.0k
EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
67
68
void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
69
                                      PragmaIntroducer Introducer,
70
164
                                      Token &FirstToken) {}
71
72
//===----------------------------------------------------------------------===//
73
// PragmaNamespace Implementation.
74
//===----------------------------------------------------------------------===//
75
76
/// FindHandler - Check to see if there is already a handler for the
77
/// specified name.  If not, return the handler for the null identifier if it
78
/// exists, otherwise return null.  If IgnoreNull is true (the default) then
79
/// the null handler isn't returned on failure to match.
80
PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
81
11.2M
                                            bool IgnoreNull) const {
82
11.2M
  auto I = Handlers.find(Name);
83
11.2M
  if (I != Handlers.end())
84
5.72M
    return I->getValue().get();
85
5.56M
  if (IgnoreNull)
86
5.56M
    return nullptr;
87
1.08k
  I = Handlers.find(StringRef());
88
1.08k
  if (I != Handlers.end())
89
250
    return I->getValue().get();
90
838
  return nullptr;
91
1.08k
}
92
93
6.05M
void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
94
6.05M
  assert(!Handlers.count(Handler->getName()) &&
95
6.05M
         "A handler with this name is already registered in this namespace");
96
0
  Handlers[Handler->getName()].reset(Handler);
97
6.05M
}
98
99
2.94M
void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
100
2.94M
  auto I = Handlers.find(Handler->getName());
101
2.94M
  assert(I != Handlers.end() &&
102
2.94M
         "Handler not registered in this namespace");
103
  // Release ownership back to the caller.
104
0
  I->getValue().release();
105
2.94M
  Handlers.erase(I);
106
2.94M
}
107
108
void PragmaNamespace::HandlePragma(Preprocessor &PP,
109
1.46M
                                   PragmaIntroducer Introducer, Token &Tok) {
110
  // Read the 'namespace' that the directive is in, e.g. STDC.  Do not macro
111
  // expand it, the user can have a STDC #define, that should not affect this.
112
1.46M
  PP.LexUnexpandedToken(Tok);
113
114
  // Get the handler for this token.  If there is no handler, ignore the pragma.
115
1.46M
  PragmaHandler *Handler
116
1.46M
    = FindHandler(Tok.getIdentifierInfo() ? 
Tok.getIdentifierInfo()->getName()1.46M
117
1.46M
                                          : 
StringRef()12
,
118
1.46M
                  /*IgnoreNull=*/false);
119
1.46M
  if (!Handler) {
120
969
    PP.Diag(Tok, diag::warn_pragma_ignored);
121
969
    return;
122
969
  }
123
124
  // Otherwise, pass it down.
125
1.46M
  Handler->HandlePragma(PP, Introducer, Tok);
126
1.46M
}
127
128
//===----------------------------------------------------------------------===//
129
// Preprocessor Pragma Directive Handling.
130
//===----------------------------------------------------------------------===//
131
132
namespace {
133
// TokenCollector provides the option to collect tokens that were "read"
134
// and return them to the stream to be read later.
135
// Currently used when reading _Pragma/__pragma directives.
136
struct TokenCollector {
137
  Preprocessor &Self;
138
  bool Collect;
139
  SmallVector<Token, 3> Tokens;
140
  Token &Tok;
141
142
1.05M
  void lex() {
143
1.05M
    if (Collect)
144
91
      Tokens.push_back(Tok);
145
1.05M
    Self.Lex(Tok);
146
1.05M
  }
147
148
22
  void revert() {
149
22
    assert(Collect && "did not collect tokens");
150
0
    assert(!Tokens.empty() && "collected unexpected number of tokens");
151
152
    // Push the ( "string" ) tokens into the token stream.
153
0
    auto Toks = std::make_unique<Token[]>(Tokens.size());
154
22
    std::copy(Tokens.begin() + 1, Tokens.end(), Toks.get());
155
22
    Toks[Tokens.size() - 1] = Tok;
156
22
    Self.EnterTokenStream(std::move(Toks), Tokens.size(),
157
22
                          /*DisableMacroExpansion*/ true,
158
22
                          /*IsReinject*/ true);
159
160
    // ... and return the pragma token unchanged.
161
22
    Tok = *Tokens.begin();
162
22
  }
163
};
164
} // namespace
165
166
/// HandlePragmaDirective - The "\#pragma" directive has been parsed.  Lex the
167
/// rest of the pragma, passing it to the registered pragma handlers.
168
1.01M
void Preprocessor::HandlePragmaDirective(PragmaIntroducer Introducer) {
169
1.01M
  if (Callbacks)
170
1.01M
    Callbacks->PragmaDirective(Introducer.Loc, Introducer.Kind);
171
172
1.01M
  if (!PragmasEnabled)
173
3
    return;
174
175
1.01M
  ++NumPragma;
176
177
  // Invoke the first level of pragma handlers which reads the namespace id.
178
1.01M
  Token Tok;
179
1.01M
  PragmaHandlers->HandlePragma(*this, Introducer, Tok);
180
181
  // If the pragma handler didn't read the rest of the line, consume it now.
182
1.01M
  if ((CurTokenLexer && 
CurTokenLexer->isParsingPreprocessorDirective()503k
)
183
1.01M
   || 
(1.01M
CurPPLexer1.01M
&&
CurPPLexer->ParsingPreprocessorDirective515k
))
184
97.5k
    DiscardUntilEndOfDirective();
185
1.01M
}
186
187
/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
188
/// return the first token after the directive.  The _Pragma token has just
189
/// been read into 'Tok'.
190
349k
void Preprocessor::Handle_Pragma(Token &Tok) {
191
  // C11 6.10.3.4/3:
192
  //   all pragma unary operator expressions within [a completely
193
  //   macro-replaced preprocessing token sequence] are [...] processed [after
194
  //   rescanning is complete]
195
  //
196
  // This means that we execute _Pragma operators in two cases:
197
  //
198
  //  1) on token sequences that would otherwise be produced as the output of
199
  //     phase 4 of preprocessing, and
200
  //  2) on token sequences formed as the macro-replaced token sequence of a
201
  //     macro argument
202
  //
203
  // Case #2 appears to be a wording bug: only _Pragmas that would survive to
204
  // the end of phase 4 should actually be executed. Discussion on the WG14
205
  // mailing list suggests that a _Pragma operator is notionally checked early,
206
  // but only pragmas that survive to the end of phase 4 should be executed.
207
  //
208
  // In Case #2, we check the syntax now, but then put the tokens back into the
209
  // token stream for later consumption.
210
211
349k
  TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
212
213
  // Remember the pragma token location.
214
349k
  SourceLocation PragmaLoc = Tok.getLocation();
215
216
  // Read the '('.
217
349k
  Toks.lex();
218
349k
  if (Tok.isNot(tok::l_paren)) {
219
1
    Diag(PragmaLoc, diag::err__Pragma_malformed);
220
1
    return;
221
1
  }
222
223
  // Read the '"..."'.
224
349k
  Toks.lex();
225
349k
  if (!tok::isStringLiteral(Tok.getKind())) {
226
4
    Diag(PragmaLoc, diag::err__Pragma_malformed);
227
    // Skip bad tokens, and the ')', if present.
228
4
    if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
229
3
      Lex(Tok);
230
7
    while (Tok.isNot(tok::r_paren) &&
231
7
           
!Tok.isAtStartOfLine()5
&&
232
7
           
Tok.isNot(tok::eof)5
)
233
3
      Lex(Tok);
234
4
    if (Tok.is(tok::r_paren))
235
2
      Lex(Tok);
236
4
    return;
237
4
  }
238
239
349k
  if (Tok.hasUDSuffix()) {
240
1
    Diag(Tok, diag::err_invalid_string_udl);
241
    // Skip this token, and the ')', if present.
242
1
    Lex(Tok);
243
1
    if (Tok.is(tok::r_paren))
244
1
      Lex(Tok);
245
1
    return;
246
1
  }
247
248
  // Remember the string.
249
349k
  Token StrTok = Tok;
250
251
  // Read the ')'.
252
349k
  Toks.lex();
253
349k
  if (Tok.isNot(tok::r_paren)) {
254
0
    Diag(PragmaLoc, diag::err__Pragma_malformed);
255
0
    return;
256
0
  }
257
258
  // If we're expanding a macro argument, put the tokens back.
259
349k
  if (InMacroArgPreExpansion) {
260
16
    Toks.revert();
261
16
    return;
262
16
  }
263
264
349k
  SourceLocation RParenLoc = Tok.getLocation();
265
349k
  std::string StrVal = getSpelling(StrTok);
266
267
  // The _Pragma is lexically sound.  Destringize according to C11 6.10.9.1:
268
  // "The string literal is destringized by deleting any encoding prefix,
269
  // deleting the leading and trailing double-quotes, replacing each escape
270
  // sequence \" by a double-quote, and replacing each escape sequence \\ by a
271
  // single backslash."
272
349k
  if (StrVal[0] == 'L' || 
StrVal[0] == 'U'349k
||
273
349k
      
(349k
StrVal[0] == 'u'349k
&&
StrVal[1] != '8'3
))
274
4
    StrVal.erase(StrVal.begin());
275
349k
  else if (StrVal[0] == 'u')
276
2
    StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
277
278
349k
  if (StrVal[0] == 'R') {
279
    // FIXME: C++11 does not specify how to handle raw-string-literals here.
280
    // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
281
3
    assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
282
3
           "Invalid raw string token!");
283
284
    // Measure the length of the d-char-sequence.
285
0
    unsigned NumDChars = 0;
286
4
    while (StrVal[2 + NumDChars] != '(') {
287
1
      assert(NumDChars < (StrVal.size() - 5) / 2 &&
288
1
             "Invalid raw string token!");
289
0
      ++NumDChars;
290
1
    }
291
3
    assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
292
293
    // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
294
    // parens below.
295
0
    StrVal.erase(0, 2 + NumDChars);
296
3
    StrVal.erase(StrVal.size() - 1 - NumDChars);
297
349k
  } else {
298
349k
    assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
299
349k
           "Invalid string token!");
300
301
    // Remove escaped quotes and escapes.
302
0
    unsigned ResultPos = 1;
303
9.93M
    for (size_t i = 1, e = StrVal.size() - 1; i != e; 
++i9.58M
) {
304
      // Skip escapes.  \\ -> '\' and \" -> '"'.
305
9.58M
      if (StrVal[i] == '\\' && 
i + 1 < e173k
&&
306
9.58M
          
(173k
StrVal[i + 1] == '\\'173k
||
StrVal[i + 1] == '"'173k
))
307
173k
        ++i;
308
9.58M
      StrVal[ResultPos++] = StrVal[i];
309
9.58M
    }
310
349k
    StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
311
349k
  }
312
313
  // Remove the front quote, replacing it with a space, so that the pragma
314
  // contents appear to have a space before them.
315
0
  StrVal[0] = ' ';
316
317
  // Replace the terminating quote with a \n.
318
349k
  StrVal[StrVal.size()-1] = '\n';
319
320
  // Plop the string (including the newline and trailing null) into a buffer
321
  // where we can lex it.
322
349k
  Token TmpTok;
323
349k
  TmpTok.startToken();
324
349k
  CreateString(StrVal, TmpTok);
325
349k
  SourceLocation TokLoc = TmpTok.getLocation();
326
327
  // Make and enter a lexer object so that we lex and expand the tokens just
328
  // like any others.
329
349k
  Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
330
349k
                                        StrVal.size(), *this);
331
332
349k
  EnterSourceFileWithLexer(TL, nullptr);
333
334
  // With everything set up, lex this as a #pragma directive.
335
349k
  HandlePragmaDirective({PIK__Pragma, PragmaLoc});
336
337
  // Finally, return whatever came after the pragma directive.
338
349k
  return Lex(Tok);
339
349k
}
340
341
/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
342
/// is not enclosed within a string literal.
343
32
void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
344
  // During macro pre-expansion, check the syntax now but put the tokens back
345
  // into the token stream for later consumption. Same as Handle_Pragma.
346
32
  TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
347
348
  // Remember the pragma token location.
349
32
  SourceLocation PragmaLoc = Tok.getLocation();
350
351
  // Read the '('.
352
32
  Toks.lex();
353
32
  if (Tok.isNot(tok::l_paren)) {
354
0
    Diag(PragmaLoc, diag::err__Pragma_malformed);
355
0
    return;
356
0
  }
357
358
  // Get the tokens enclosed within the __pragma(), as well as the final ')'.
359
32
  SmallVector<Token, 32> PragmaToks;
360
32
  int NumParens = 0;
361
32
  Toks.lex();
362
175
  while (Tok.isNot(tok::eof)) {
363
175
    PragmaToks.push_back(Tok);
364
175
    if (Tok.is(tok::l_paren))
365
28
      NumParens++;
366
147
    else if (Tok.is(tok::r_paren) && 
NumParens-- == 060
)
367
32
      break;
368
143
    Toks.lex();
369
143
  }
370
371
32
  if (Tok.is(tok::eof)) {
372
0
    Diag(PragmaLoc, diag::err_unterminated___pragma);
373
0
    return;
374
0
  }
375
376
  // If we're expanding a macro argument, put the tokens back.
377
32
  if (InMacroArgPreExpansion) {
378
6
    Toks.revert();
379
6
    return;
380
6
  }
381
382
26
  PragmaToks.front().setFlag(Token::LeadingSpace);
383
384
  // Replace the ')' with an EOD to mark the end of the pragma.
385
26
  PragmaToks.back().setKind(tok::eod);
386
387
26
  Token *TokArray = new Token[PragmaToks.size()];
388
26
  std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
389
390
  // Push the tokens onto the stack.
391
26
  EnterTokenStream(TokArray, PragmaToks.size(), true, true,
392
26
                   /*IsReinject*/ false);
393
394
  // With everything set up, lex this as a #pragma directive.
395
26
  HandlePragmaDirective({PIK___pragma, PragmaLoc});
396
397
  // Finally, return whatever came after the pragma directive.
398
26
  return Lex(Tok);
399
32
}
400
401
/// HandlePragmaOnce - Handle \#pragma once.  OnceTok is the 'once'.
402
468
void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
403
  // Don't honor the 'once' when handling the primary source file, unless
404
  // this is a prefix to a TU, which indicates we're generating a PCH file, or
405
  // when the main file is a header (e.g. when -xc-header is provided on the
406
  // commandline).
407
468
  if (isInPrimaryFile() && 
TUKind != TU_Prefix6
&&
!getLangOpts().IsHeaderFile4
) {
408
3
    Diag(OnceTok, diag::pp_pragma_once_in_main_file);
409
3
    return;
410
3
  }
411
412
  // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
413
  // Mark the file as a once-only file now.
414
465
  HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
415
465
}
416
417
37.8k
void Preprocessor::HandlePragmaMark(Token &MarkTok) {
418
37.8k
  assert(CurPPLexer && "No current lexer?");
419
420
0
  SmallString<64> Buffer;
421
37.8k
  CurLexer->ReadToEndOfLine(&Buffer);
422
37.8k
  if (Callbacks)
423
37.8k
    Callbacks->PragmaMark(MarkTok.getLocation(), Buffer);
424
37.8k
}
425
426
/// HandlePragmaPoison - Handle \#pragma GCC poison.  PoisonTok is the 'poison'.
427
5
void Preprocessor::HandlePragmaPoison() {
428
5
  Token Tok;
429
430
10
  while (true) {
431
    // Read the next token to poison.  While doing this, pretend that we are
432
    // skipping while reading the identifier to poison.
433
    // This avoids errors on code like:
434
    //   #pragma GCC poison X
435
    //   #pragma GCC poison X
436
10
    if (CurPPLexer) CurPPLexer->LexingRawMode = true;
437
10
    LexUnexpandedToken(Tok);
438
10
    if (CurPPLexer) CurPPLexer->LexingRawMode = false;
439
440
    // If we reached the end of line, we're done.
441
10
    if (Tok.is(tok::eod)) 
return5
;
442
443
    // Can only poison identifiers.
444
5
    if (Tok.isNot(tok::raw_identifier)) {
445
0
      Diag(Tok, diag::err_pp_invalid_poison);
446
0
      return;
447
0
    }
448
449
    // Look up the identifier info for the token.  We disabled identifier lookup
450
    // by saying we're skipping contents, so we need to do this manually.
451
5
    IdentifierInfo *II = LookUpIdentifierInfo(Tok);
452
453
    // Already poisoned.
454
5
    if (II->isPoisoned()) 
continue1
;
455
456
    // If this is a macro identifier, emit a warning.
457
4
    if (isMacroDefined(II))
458
0
      Diag(Tok, diag::pp_poisoning_existing_macro);
459
460
    // Finally, poison it!
461
4
    II->setIsPoisoned();
462
4
    if (II->isFromAST())
463
0
      II->setChangedSinceDeserialization();
464
4
  }
465
5
}
466
467
/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header.  We know
468
/// that the whole directive has been parsed.
469
115k
void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
470
115k
  if (isInPrimaryFile()) {
471
1
    Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
472
1
    return;
473
1
  }
474
475
  // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
476
115k
  PreprocessorLexer *TheLexer = getCurrentFileLexer();
477
478
  // Mark the file as a system header.
479
115k
  HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
480
481
115k
  PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
482
115k
  if (PLoc.isInvalid())
483
0
    return;
484
485
115k
  unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
486
487
  // Notify the client, if desired, that we are in a new source file.
488
115k
  if (Callbacks)
489
115k
    Callbacks->FileChanged(SysHeaderTok.getLocation(),
490
115k
                           PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
491
492
  // Emit a line marker.  This will change any source locations from this point
493
  // forward to realize they are in a system header.
494
  // Create a line note with this information.
495
115k
  SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
496
115k
                        FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
497
115k
                        SrcMgr::C_System);
498
115k
}
499
500
static llvm::Optional<Token> LexHeader(Preprocessor &PP,
501
                                       Optional<FileEntryRef> &File,
502
20
                                       bool SuppressIncludeNotFoundError) {
503
20
  Token FilenameTok;
504
20
  if (PP.LexHeaderName(FilenameTok, /*AllowConcatenation*/ false))
505
0
    return llvm::None;
506
507
  // If the next token wasn't a header-name, diagnose the error.
508
20
  if (FilenameTok.isNot(tok::header_name)) {
509
1
    PP.Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
510
1
    return llvm::None;
511
1
  }
512
513
  // Reserve a buffer to get the spelling.
514
19
  SmallString<128> FilenameBuffer;
515
19
  bool Invalid = false;
516
19
  StringRef Filename = PP.getSpelling(FilenameTok, FilenameBuffer, &Invalid);
517
19
  if (Invalid)
518
0
    return llvm::None;
519
520
19
  bool isAngled =
521
19
      PP.GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
522
  // If GetIncludeFilenameSpelling set the start ptr to null, there was an
523
  // error.
524
19
  if (Filename.empty())
525
0
    return llvm::None;
526
527
  // Search include directories for this file.
528
19
  const DirectoryLookup *CurDir;
529
19
  File = PP.LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
530
19
                       nullptr, CurDir, 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
35.6k
IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
604
  // Remember the pragma token location.
605
35.6k
  Token PragmaTok = Tok;
606
607
  // Read the '('.
608
35.6k
  Lex(Tok);
609
35.6k
  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
35.6k
  Lex(Tok);
617
35.6k
  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
35.6k
  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
35.6k
  std::string StrVal = getSpelling(Tok);
630
631
  // Read the ')'.
632
35.6k
  Lex(Tok);
633
35.6k
  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
35.6k
  assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
640
35.6k
         "Invalid string token!");
641
642
  // Create a Token from the string.
643
0
  Token MacroTok;
644
35.6k
  MacroTok.startToken();
645
35.6k
  MacroTok.setKind(tok::raw_identifier);
646
35.6k
  CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
647
648
  // Get the IdentifierInfo of MacroToPushTok.
649
35.6k
  return LookUpIdentifierInfo(MacroTok);
650
35.6k
}
651
652
/// Handle \#pragma push_macro.
653
///
654
/// The syntax is:
655
/// \code
656
///   #pragma push_macro("macro")
657
/// \endcode
658
17.8k
void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
659
  // Parse the pragma directive and get the macro IdentifierInfo*.
660
17.8k
  IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
661
17.8k
  if (!IdentInfo) 
return1
;
662
663
  // Get the MacroInfo associated with IdentInfo.
664
17.8k
  MacroInfo *MI = getMacroInfo(IdentInfo);
665
666
17.8k
  if (MI) {
667
    // Allow the original MacroInfo to be redefined later.
668
102
    MI->setIsAllowRedefinitionsWithoutWarning(true);
669
102
  }
670
671
  // Push the cloned MacroInfo so we can retrieve it later.
672
17.8k
  PragmaPushMacroInfo[IdentInfo].push_back(MI);
673
17.8k
}
674
675
/// Handle \#pragma pop_macro.
676
///
677
/// The syntax is:
678
/// \code
679
///   #pragma pop_macro("macro")
680
/// \endcode
681
17.8k
void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
682
17.8k
  SourceLocation MessageLoc = PopMacroTok.getLocation();
683
684
  // Parse the pragma directive and get the macro IdentifierInfo*.
685
17.8k
  IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
686
17.8k
  if (!IdentInfo) 
return0
;
687
688
  // Find the vector<MacroInfo*> associated with the macro.
689
17.8k
  llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter =
690
17.8k
    PragmaPushMacroInfo.find(IdentInfo);
691
17.8k
  if (iter != PragmaPushMacroInfo.end()) {
692
    // Forget the MacroInfo currently associated with IdentInfo.
693
17.8k
    if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
694
314
      if (MI->isWarnIfUnused())
695
0
        WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
696
314
      appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
697
314
    }
698
699
    // Get the MacroInfo we want to reinstall.
700
17.8k
    MacroInfo *MacroToReInstall = iter->second.back();
701
702
17.8k
    if (MacroToReInstall)
703
      // Reinstall the previously pushed macro.
704
101
      appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
705
706
    // Pop PragmaPushMacroInfo stack.
707
17.8k
    iter->second.pop_back();
708
17.8k
    if (iter->second.empty())
709
17.8k
      PragmaPushMacroInfo.erase(iter);
710
17.8k
  } else {
711
2
    Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
712
2
      << IdentInfo->getName();
713
2
  }
714
17.8k
}
715
716
22
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
22
  Lex(Tok);
724
22
  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
22
  Token SourceFilenameTok;
731
22
  if (LexHeaderName(SourceFilenameTok))
732
0
    return;
733
734
22
  StringRef SourceFileName;
735
22
  SmallString<128> FileNameBuffer;
736
22
  if (SourceFilenameTok.is(tok::header_name)) {
737
20
    SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
738
20
  } else {
739
2
    Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
740
2
    return;
741
2
  }
742
20
  FileNameBuffer.clear();
743
744
  // Now we expect a comma, followed by another include name
745
20
  Lex(Tok);
746
20
  if (Tok.isNot(tok::comma)) {
747
2
    Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
748
2
    return;
749
2
  }
750
751
18
  Token ReplaceFilenameTok;
752
18
  if (LexHeaderName(ReplaceFilenameTok))
753
0
    return;
754
755
18
  StringRef ReplaceFileName;
756
18
  if (ReplaceFilenameTok.is(tok::header_name)) {
757
18
    ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
758
18
  } 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
18
  Lex(Tok);
765
18
  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
18
  StringRef OriginalSource = SourceFileName;
773
774
18
  bool SourceIsAngled =
775
18
    GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
776
18
                                SourceFileName);
777
18
  bool ReplaceIsAngled =
778
18
    GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
779
18
                                ReplaceFileName);
780
18
  if (!SourceFileName.empty() && 
!ReplaceFileName.empty()16
&&
781
18
      
(SourceIsAngled != ReplaceIsAngled)14
) {
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
14
  getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
797
14
}
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
441
    bool First) {
805
441
  PP.LexUnexpandedToken(Tok);
806
441
  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
434
  } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
813
425
    ModuleNameComponent =
814
425
        std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
815
425
  } else {
816
9
    PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
817
9
    return true;
818
9
  }
819
432
  return false;
820
441
}
821
822
static bool LexModuleName(
823
    Preprocessor &PP, Token &Tok,
824
    llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
825
273
        &ModuleName) {
826
364
  while (true) {
827
364
    std::pair<IdentifierInfo*, SourceLocation> NameComponent;
828
364
    if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
829
8
      return true;
830
356
    ModuleName.push_back(NameComponent);
831
832
356
    PP.LexUnexpandedToken(Tok);
833
356
    if (Tok.isNot(tok::period))
834
265
      return false;
835
356
  }
836
273
}
837
838
77
void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
839
77
  SourceLocation Loc = Tok.getLocation();
840
841
77
  std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
842
77
  if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
843
1
    return;
844
76
  IdentifierInfo *ModuleName = ModuleNameLoc.first;
845
846
76
  LexUnexpandedToken(Tok);
847
76
  if (Tok.isNot(tok::eod)) {
848
0
    Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
849
0
    DiscardUntilEndOfDirective();
850
0
  }
851
852
76
  CurLexer->LexingRawMode = true;
853
854
1.93k
  auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
855
1.93k
    if (Tok.getKind() != tok::raw_identifier ||
856
1.93k
        
Tok.getRawIdentifier() != Ident1.85k
)
857
800
      return false;
858
1.13k
    CurLexer->Lex(Tok);
859
1.13k
    return true;
860
1.93k
  };
861
862
  // Scan forward looking for the end of the module.
863
76
  const char *Start = CurLexer->getBufferLocation();
864
76
  const char *End = nullptr;
865
76
  unsigned NestingLevel = 1;
866
5.96k
  while (true) {
867
5.96k
    End = CurLexer->getBufferLocation();
868
5.96k
    CurLexer->Lex(Tok);
869
870
5.96k
    if (Tok.is(tok::eof)) {
871
1
      Diag(Loc, diag::err_pp_module_build_missing_end);
872
1
      break;
873
1
    }
874
875
5.96k
    if (Tok.isNot(tok::hash) || 
!Tok.isAtStartOfLine()525
) {
876
      // Token was part of module; keep going.
877
5.44k
      continue;
878
5.44k
    }
879
880
    // We hit something directive-shaped; check to see if this is the end
881
    // of the module build.
882
525
    CurLexer->ParsingPreprocessorDirective = true;
883
525
    CurLexer->Lex(Tok);
884
525
    if (TryConsumeIdentifier("pragma") && 
TryConsumeIdentifier("clang")353
&&
885
525
        
TryConsumeIdentifier("module")353
) {
886
353
      if (TryConsumeIdentifier("build"))
887
        // #pragma clang module build -> entering a nested module build.
888
1
        ++NestingLevel;
889
352
      else if (TryConsumeIdentifier("endbuild")) {
890
        // #pragma clang module endbuild -> leaving a module build.
891
76
        if (--NestingLevel == 0)
892
75
          break;
893
76
      }
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
278
      assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
897
278
    }
898
525
  }
899
900
76
  CurLexer->LexingRawMode = false;
901
902
  // Load the extracted text as a preprocessed module.
903
76
  assert(CurLexer->getBuffer().begin() <= Start &&
904
76
         Start <= CurLexer->getBuffer().end() &&
905
76
         CurLexer->getBuffer().begin() <= End &&
906
76
         End <= CurLexer->getBuffer().end() &&
907
76
         "module source range not contained within same file buffer");
908
0
  TheModuleLoader.createModuleFromSource(Loc, ModuleName->getName(),
909
76
                                         StringRef(Start, End - Start));
910
76
}
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
5.26M
                                    PragmaHandler *Handler) {
948
5.26M
  PragmaNamespace *InsertNS = PragmaHandlers.get();
949
950
  // If this is specified to be in a namespace, step down into it.
951
5.26M
  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
3.11M
    if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
956
2.82M
      InsertNS = Existing->getIfNamespace();
957
2.82M
      assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
958
2.82M
             " handler with the same name!");
959
2.82M
    } else {
960
      // Otherwise, this namespace doesn't exist yet, create and insert the
961
      // handler for it.
962
293k
      InsertNS = new PragmaNamespace(Namespace);
963
293k
      PragmaHandlers->AddPragma(InsertNS);
964
293k
    }
965
3.11M
  }
966
967
  // Check to make sure we don't already have a pragma for this identifier.
968
0
  assert(!InsertNS->FindHandler(Handler->getName()) &&
969
5.26M
         "Pragma handler already exists for this identifier!");
970
0
  InsertNS->AddPragma(Handler);
971
5.26M
}
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.84M
                                       PragmaHandler *Handler) {
979
2.84M
  PragmaNamespace *NS = PragmaHandlers.get();
980
981
  // If this is specified to be in a namespace, step down into it.
982
2.84M
  if (!Namespace.empty()) {
983
1.43M
    PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
984
1.43M
    assert(Existing && "Namespace containing handler does not exist!");
985
986
0
    NS = Existing->getIfNamespace();
987
1.43M
    assert(NS && "Invalid namespace, registered as a regular pragma handler!");
988
1.43M
  }
989
990
0
  NS->RemovePragmaHandler(Handler);
991
992
  // If this is a non-default namespace and it is now empty, remove it.
993
2.84M
  if (NS != PragmaHandlers.get() && 
NS->IsEmpty()1.43M
) {
994
96.9k
    PragmaHandlers->RemovePragmaHandler(NS);
995
96.9k
    delete NS;
996
96.9k
  }
997
2.84M
}
998
999
76
bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
1000
76
  Token Tok;
1001
76
  LexUnexpandedToken(Tok);
1002
1003
76
  if (Tok.isNot(tok::identifier)) {
1004
4
    Diag(Tok, diag::ext_on_off_switch_syntax);
1005
4
    return true;
1006
4
  }
1007
72
  IdentifierInfo *II = Tok.getIdentifierInfo();
1008
72
  if (II->isStr("ON"))
1009
47
    Result = tok::OOS_ON;
1010
25
  else if (II->isStr("OFF"))
1011
16
    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
66
  LexUnexpandedToken(Tok);
1021
66
  if (Tok.isNot(tok::eod))
1022
1
    Diag(Tok, diag::ext_pragma_syntax_eod);
1023
66
  return false;
1024
72
}
1025
1026
namespace {
1027
1028
/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
1029
struct PragmaOnceHandler : public PragmaHandler {
1030
98.4k
  PragmaOnceHandler() : PragmaHandler("once") {}
1031
1032
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1033
468
                    Token &OnceTok) override {
1034
468
    PP.CheckEndOfDirective("pragma once");
1035
468
    PP.HandlePragmaOnce(OnceTok);
1036
468
  }
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
98.4k
  PragmaMarkHandler() : PragmaHandler("mark") {}
1043
1044
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1045
37.8k
                    Token &MarkTok) override {
1046
37.8k
    PP.HandlePragmaMark(MarkTok);
1047
37.8k
  }
1048
};
1049
1050
/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
1051
struct PragmaPoisonHandler : public PragmaHandler {
1052
196k
  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
207k
  PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
1064
1065
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1066
115k
                    Token &SHToken) override {
1067
115k
    PP.HandlePragmaSystemHeader(SHToken);
1068
115k
    PP.CheckEndOfDirective("pragma");
1069
115k
  }
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
98.4k
  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
196k
  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
98.4k
  PragmaDebugHandler() : PragmaHandler("__debug") {}
1095
1096
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1097
129
                    Token &DebugToken) override {
1098
129
    Token Tok;
1099
129
    PP.LexUnexpandedToken(Tok);
1100
129
    if (Tok.isNot(tok::identifier)) {
1101
0
      PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1102
0
      return;
1103
0
    }
1104
129
    IdentifierInfo *II = Tok.getIdentifierInfo();
1105
1106
129
    if (II->isStr("assert")) {
1107
2
      if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1108
1
        llvm_unreachable("This is an assertion!");
1109
127
    } else if (II->isStr("crash")) {
1110
11
      llvm::Timer T("crash", "pragma crash");
1111
11
      llvm::TimeRegion R(&T);
1112
11
      if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1113
8
        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
121
    PPCallbacks *Callbacks = PP.getPPCallbacks();
1245
121
    if (Callbacks)
1246
117
      Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1247
121
  }
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
196k
      : PragmaHandler("diagnostic"), Namespace(NS) {}
1291
1292
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1293
116k
                    Token &DiagToken) override {
1294
116k
    SourceLocation DiagLoc = DiagToken.getLocation();
1295
116k
    Token Tok;
1296
116k
    PP.LexUnexpandedToken(Tok);
1297
116k
    if (Tok.isNot(tok::identifier)) {
1298
0
      PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1299
0
      return;
1300
0
    }
1301
116k
    IdentifierInfo *II = Tok.getIdentifierInfo();
1302
116k
    PPCallbacks *Callbacks = PP.getPPCallbacks();
1303
1304
116k
    if (II->isStr("pop")) {
1305
30.2k
      if (!PP.getDiagnostics().popMappings(DiagLoc))
1306
2
        PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1307
30.2k
      else if (Callbacks)
1308
30.2k
        Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
1309
30.2k
      return;
1310
86.3k
    } else if (II->isStr("push")) {
1311
30.2k
      PP.getDiagnostics().pushMappings(DiagLoc);
1312
30.2k
      if (Callbacks)
1313
30.2k
        Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
1314
30.2k
      return;
1315
30.2k
    }
1316
1317
56.1k
    diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1318
56.1k
                            .Case("ignored", diag::Severity::Ignored)
1319
56.1k
                            .Case("warning", diag::Severity::Warning)
1320
56.1k
                            .Case("error", diag::Severity::Error)
1321
56.1k
                            .Case("fatal", diag::Severity::Fatal)
1322
56.1k
                            .Default(diag::Severity());
1323
1324
56.1k
    if (SV == diag::Severity()) {
1325
3
      PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1326
3
      return;
1327
3
    }
1328
1329
56.1k
    PP.LexUnexpandedToken(Tok);
1330
56.1k
    SourceLocation StringLoc = Tok.getLocation();
1331
1332
56.1k
    std::string WarningName;
1333
56.1k
    if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1334
56.1k
                                   /*AllowMacroExpansion=*/false))
1335
2
      return;
1336
1337
56.1k
    if (Tok.isNot(tok::eod)) {
1338
2
      PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1339
2
      return;
1340
2
    }
1341
1342
56.1k
    if (WarningName.size() < 3 || WarningName[0] != '-' ||
1343
56.1k
        
(56.1k
WarningName[1] != 'W'56.1k
&&
WarningName[1] != 'R'0
)) {
1344
2
      PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
1345
2
      return;
1346
2
    }
1347
1348
56.1k
    diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1349
56.1k
                                                : 
diag::Flavor::Remark0
;
1350
56.1k
    StringRef Group = StringRef(WarningName).substr(2);
1351
56.1k
    bool unknownDiag = false;
1352
56.1k
    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
56.0k
      unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1359
56.0k
                                                            DiagLoc);
1360
56.1k
    if (unknownDiag)
1361
2
      PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1362
2
        << WarningName;
1363
56.1k
    else if (Callbacks)
1364
56.1k
      Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
1365
56.1k
  }
1366
};
1367
1368
/// "\#pragma hdrstop [<header-name-string>]"
1369
struct PragmaHdrstopHandler : public PragmaHandler {
1370
10.7k
  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
10.7k
  PragmaWarningHandler() : PragmaHandler("warning") {}
1382
1383
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1384
79
                    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
79
    SourceLocation DiagLoc = Tok.getLocation();
1390
79
    PPCallbacks *Callbacks = PP.getPPCallbacks();
1391
1392
79
    PP.Lex(Tok);
1393
79
    if (Tok.isNot(tok::l_paren)) {
1394
2
      PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1395
2
      return;
1396
2
    }
1397
1398
77
    PP.Lex(Tok);
1399
77
    IdentifierInfo *II = Tok.getIdentifierInfo();
1400
1401
77
    if (II && 
II->isStr("push")65
) {
1402
      // #pragma warning( push[ ,n ] )
1403
30
      int Level = -1;
1404
30
      PP.Lex(Tok);
1405
30
      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
25
      if (Callbacks)
1417
25
        Callbacks->PragmaWarningPush(DiagLoc, Level);
1418
47
    } else if (II && 
II->isStr("pop")35
) {
1419
      // #pragma warning( pop )
1420
11
      PP.Lex(Tok);
1421
11
      if (Callbacks)
1422
11
        Callbacks->PragmaWarningPop(DiagLoc);
1423
36
    } else {
1424
      // #pragma warning( warning-specifier : warning-number-list
1425
      //                  [; warning-specifier : warning-number-list...] )
1426
42
      while (true) {
1427
42
        II = Tok.getIdentifierInfo();
1428
42
        if (!II && 
!Tok.is(tok::numeric_constant)14
) {
1429
4
          PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1430
4
          return;
1431
4
        }
1432
1433
        // Figure out which warning specifier this is.
1434
38
        bool SpecifierValid;
1435
38
        StringRef Specifier;
1436
38
        llvm::SmallString<1> SpecifierBuf;
1437
38
        if (II) {
1438
28
          Specifier = II->getName();
1439
28
          SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1440
28
                               .Cases("default", "disable", "error", "once",
1441
28
                                      "suppress", true)
1442
28
                               .Default(false);
1443
          // If we read a correct specifier, snatch next token (that should be
1444
          // ":", checked later).
1445
28
          if (SpecifierValid)
1446
26
            PP.Lex(Tok);
1447
28
        } else {
1448
          // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1449
10
          uint64_t Value;
1450
10
          Specifier = PP.getSpelling(Tok, SpecifierBuf);
1451
10
          if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1452
10
            SpecifierValid = (Value >= 1) && (Value <= 4);
1453
10
          } else
1454
0
            SpecifierValid = false;
1455
          // Next token already snatched by parseSimpleIntegerLiteral.
1456
10
        }
1457
1458
38
        if (!SpecifierValid) {
1459
4
          PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1460
4
          return;
1461
4
        }
1462
34
        if (Tok.isNot(tok::colon)) {
1463
4
          PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1464
4
          return;
1465
4
        }
1466
1467
        // Collect the warning ids.
1468
30
        SmallVector<int, 4> Ids;
1469
30
        PP.Lex(Tok);
1470
70
        while (Tok.is(tok::numeric_constant)) {
1471
42
          uint64_t Value;
1472
42
          if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1473
42
              
Value > INT_MAX40
) {
1474
2
            PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1475
2
            return;
1476
2
          }
1477
40
          Ids.push_back(int(Value));
1478
40
        }
1479
28
        if (Callbacks)
1480
28
          Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1481
1482
        // Parse the next specifier if there is a semicolon.
1483
28
        if (Tok.isNot(tok::semi))
1484
22
          break;
1485
6
        PP.Lex(Tok);
1486
6
      }
1487
36
    }
1488
1489
58
    if (Tok.isNot(tok::r_paren)) {
1490
6
      PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1491
6
      return;
1492
6
    }
1493
1494
52
    PP.Lex(Tok);
1495
52
    if (Tok.isNot(tok::eod))
1496
2
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1497
52
  }
1498
};
1499
1500
/// "\#pragma execution_character_set(...)". MSVC supports this pragma only
1501
/// for "UTF-8". We parse it and ignore it if UTF-8 is provided and warn
1502
/// otherwise to avoid -Wunknown-pragma warnings.
1503
struct PragmaExecCharsetHandler : public PragmaHandler {
1504
10.7k
  PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {}
1505
1506
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1507
32
                    Token &Tok) override {
1508
    // Parse things like:
1509
    // execution_character_set(push, "UTF-8")
1510
    // execution_character_set(pop)
1511
32
    SourceLocation DiagLoc = Tok.getLocation();
1512
32
    PPCallbacks *Callbacks = PP.getPPCallbacks();
1513
1514
32
    PP.Lex(Tok);
1515
32
    if (Tok.isNot(tok::l_paren)) {
1516
2
      PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << "(";
1517
2
      return;
1518
2
    }
1519
1520
30
    PP.Lex(Tok);
1521
30
    IdentifierInfo *II = Tok.getIdentifierInfo();
1522
1523
30
    if (II && 
II->isStr("push")26
) {
1524
      // #pragma execution_character_set( push[ , string ] )
1525
16
      PP.Lex(Tok);
1526
16
      if (Tok.is(tok::comma)) {
1527
12
        PP.Lex(Tok);
1528
1529
12
        std::string ExecCharset;
1530
12
        if (!PP.FinishLexStringLiteral(Tok, ExecCharset,
1531
12
                                       "pragma execution_character_set",
1532
12
                                       /*AllowMacroExpansion=*/false))
1533
6
          return;
1534
1535
        // MSVC supports either of these, but nothing else.
1536
6
        if (ExecCharset != "UTF-8" && 
ExecCharset != "utf-8"4
) {
1537
2
          PP.Diag(Tok, diag::warn_pragma_exec_charset_push_invalid) << ExecCharset;
1538
2
          return;
1539
2
        }
1540
6
      }
1541
8
      if (Callbacks)
1542
8
        Callbacks->PragmaExecCharsetPush(DiagLoc, "UTF-8");
1543
14
    } else if (II && 
II->isStr("pop")10
) {
1544
      // #pragma execution_character_set( pop )
1545
6
      PP.Lex(Tok);
1546
6
      if (Callbacks)
1547
6
        Callbacks->PragmaExecCharsetPop(DiagLoc);
1548
8
    } else {
1549
8
      PP.Diag(Tok, diag::warn_pragma_exec_charset_spec_invalid);
1550
8
      return;
1551
8
    }
1552
1553
14
    if (Tok.isNot(tok::r_paren)) {
1554
6
      PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << ")";
1555
6
      return;
1556
6
    }
1557
1558
8
    PP.Lex(Tok);
1559
8
    if (Tok.isNot(tok::eod))
1560
0
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma execution_character_set";
1561
8
  }
1562
};
1563
1564
/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1565
struct PragmaIncludeAliasHandler : public PragmaHandler {
1566
10.7k
  PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1567
1568
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1569
22
                    Token &IncludeAliasTok) override {
1570
22
    PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1571
22
  }
1572
};
1573
1574
/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1575
/// extension.  The syntax is:
1576
/// \code
1577
///   #pragma message(string)
1578
/// \endcode
1579
/// OR, in GCC mode:
1580
/// \code
1581
///   #pragma message string
1582
/// \endcode
1583
/// string is a string, which is fully macro expanded, and permits string
1584
/// concatenation, embedded escape characters, etc... See MSDN for more details.
1585
/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1586
/// form as \#pragma message.
1587
struct PragmaMessageHandler : public PragmaHandler {
1588
private:
1589
  const PPCallbacks::PragmaMessageKind Kind;
1590
  const StringRef Namespace;
1591
1592
  static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1593
295k
                                bool PragmaNameOnly = false) {
1594
295k
    switch (Kind) {
1595
98.4k
      case PPCallbacks::PMK_Message:
1596
98.4k
        return PragmaNameOnly ? 
"message"98.4k
:
"pragma message"12
;
1597
98.4k
      case PPCallbacks::PMK_Warning:
1598
98.4k
        return PragmaNameOnly ? 
"warning"98.4k
:
"pragma warning"7
;
1599
98.4k
      case PPCallbacks::PMK_Error:
1600
98.4k
        return PragmaNameOnly ? 
"error"98.4k
:
"pragma error"6
;
1601
295k
    }
1602
0
    llvm_unreachable("Unknown PragmaMessageKind!");
1603
0
  }
1604
1605
public:
1606
  PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1607
                       StringRef Namespace = StringRef())
1608
      : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
1609
295k
        Namespace(Namespace) {}
1610
1611
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1612
26
                    Token &Tok) override {
1613
26
    SourceLocation MessageLoc = Tok.getLocation();
1614
26
    PP.Lex(Tok);
1615
26
    bool ExpectClosingParen = false;
1616
26
    switch (Tok.getKind()) {
1617
11
    case tok::l_paren:
1618
      // We have a MSVC style pragma message.
1619
11
      ExpectClosingParen = true;
1620
      // Read the string.
1621
11
      PP.Lex(Tok);
1622
11
      break;
1623
14
    case tok::string_literal:
1624
      // We have a GCC style pragma message, and we just read the string.
1625
14
      break;
1626
1
    default:
1627
1
      PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1628
1
      return;
1629
26
    }
1630
1631
25
    std::string MessageString;
1632
25
    if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1633
25
                                   /*AllowMacroExpansion=*/true))
1634
2
      return;
1635
1636
23
    if (ExpectClosingParen) {
1637
9
      if (Tok.isNot(tok::r_paren)) {
1638
1
        PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1639
1
        return;
1640
1
      }
1641
8
      PP.Lex(Tok);  // eat the r_paren.
1642
8
    }
1643
1644
22
    if (Tok.isNot(tok::eod)) {
1645
0
      PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1646
0
      return;
1647
0
    }
1648
1649
    // Output the message.
1650
22
    PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1651
22
                          ? 
diag::err_pragma_message5
1652
22
                          : 
diag::warn_pragma_message17
) << MessageString;
1653
1654
    // If the pragma is lexically sound, notify any interested PPCallbacks.
1655
22
    if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1656
22
      Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1657
22
  }
1658
};
1659
1660
/// Handle the clang \#pragma module import extension. The syntax is:
1661
/// \code
1662
///   #pragma clang module import some.module.name
1663
/// \endcode
1664
struct PragmaModuleImportHandler : public PragmaHandler {
1665
98.4k
  PragmaModuleImportHandler() : PragmaHandler("import") {}
1666
1667
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1668
121
                    Token &Tok) override {
1669
121
    SourceLocation ImportLoc = Tok.getLocation();
1670
1671
    // Read the module name.
1672
121
    llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1673
121
        ModuleName;
1674
121
    if (LexModuleName(PP, Tok, ModuleName))
1675
6
      return;
1676
1677
115
    if (Tok.isNot(tok::eod))
1678
2
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1679
1680
    // If we have a non-empty module path, load the named module.
1681
115
    Module *Imported =
1682
115
        PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1683
115
                                      /*IsInclusionDirective=*/false);
1684
115
    if (!Imported)
1685
0
      return;
1686
1687
115
    PP.makeModuleVisible(Imported, ImportLoc);
1688
115
    PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1689
115
                            tok::annot_module_include, Imported);
1690
115
    if (auto *CB = PP.getPPCallbacks())
1691
115
      CB->moduleImport(ImportLoc, ModuleName, Imported);
1692
115
  }
1693
};
1694
1695
/// Handle the clang \#pragma module begin extension. The syntax is:
1696
/// \code
1697
///   #pragma clang module begin some.module.name
1698
///   ...
1699
///   #pragma clang module end
1700
/// \endcode
1701
struct PragmaModuleBeginHandler : public PragmaHandler {
1702
98.4k
  PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1703
1704
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1705
146
                    Token &Tok) override {
1706
146
    SourceLocation BeginLoc = Tok.getLocation();
1707
1708
    // Read the module name.
1709
146
    llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1710
146
        ModuleName;
1711
146
    if (LexModuleName(PP, Tok, ModuleName))
1712
2
      return;
1713
1714
144
    if (Tok.isNot(tok::eod))
1715
2
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1716
1717
    // We can only enter submodules of the current module.
1718
144
    StringRef Current = PP.getLangOpts().CurrentModule;
1719
144
    if (ModuleName.front().first->getName() != Current) {
1720
0
      PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1721
0
        << ModuleName.front().first << (ModuleName.size() > 1)
1722
0
        << Current.empty() << Current;
1723
0
      return;
1724
0
    }
1725
1726
    // Find the module we're entering. We require that a module map for it
1727
    // be loaded or implicitly loadable.
1728
144
    auto &HSI = PP.getHeaderSearchInfo();
1729
144
    Module *M = HSI.lookupModule(Current);
1730
144
    if (!M) {
1731
0
      PP.Diag(ModuleName.front().second,
1732
0
              diag::err_pp_module_begin_no_module_map) << Current;
1733
0
      return;
1734
0
    }
1735
192
    
for (unsigned I = 1; 144
I != ModuleName.size();
++I48
) {
1736
48
      auto *NewM = M->findOrInferSubmodule(ModuleName[I].first->getName());
1737
48
      if (!NewM) {
1738
0
        PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1739
0
          << M->getFullModuleName() << ModuleName[I].first;
1740
0
        return;
1741
0
      }
1742
48
      M = NewM;
1743
48
    }
1744
1745
    // If the module isn't available, it doesn't make sense to enter it.
1746
144
    if (Preprocessor::checkModuleIsAvailable(
1747
144
            PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
1748
1
      PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1749
1
        << M->getTopLevelModuleName();
1750
1
      return;
1751
1
    }
1752
1753
    // Enter the scope of the submodule.
1754
143
    PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1755
143
    PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1756
143
                            tok::annot_module_begin, M);
1757
143
  }
1758
};
1759
1760
/// Handle the clang \#pragma module end extension.
1761
struct PragmaModuleEndHandler : public PragmaHandler {
1762
98.4k
  PragmaModuleEndHandler() : PragmaHandler("end") {}
1763
1764
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1765
144
                    Token &Tok) override {
1766
144
    SourceLocation Loc = Tok.getLocation();
1767
1768
144
    PP.LexUnexpandedToken(Tok);
1769
144
    if (Tok.isNot(tok::eod))
1770
2
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1771
1772
144
    Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1773
144
    if (M)
1774
141
      PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1775
3
    else
1776
3
      PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
1777
144
  }
1778
};
1779
1780
/// Handle the clang \#pragma module build extension.
1781
struct PragmaModuleBuildHandler : public PragmaHandler {
1782
98.4k
  PragmaModuleBuildHandler() : PragmaHandler("build") {}
1783
1784
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1785
77
                    Token &Tok) override {
1786
77
    PP.HandlePragmaModuleBuild(Tok);
1787
77
  }
1788
};
1789
1790
/// Handle the clang \#pragma module load extension.
1791
struct PragmaModuleLoadHandler : public PragmaHandler {
1792
98.4k
  PragmaModuleLoadHandler() : PragmaHandler("load") {}
1793
1794
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1795
6
                    Token &Tok) override {
1796
6
    SourceLocation Loc = Tok.getLocation();
1797
1798
    // Read the module name.
1799
6
    llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1800
6
        ModuleName;
1801
6
    if (LexModuleName(PP, Tok, ModuleName))
1802
0
      return;
1803
1804
6
    if (Tok.isNot(tok::eod))
1805
0
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1806
1807
    // Load the module, don't make it visible.
1808
6
    PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1809
6
                                    /*IsInclusionDirective=*/false);
1810
6
  }
1811
};
1812
1813
/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1814
/// macro on the top of the stack.
1815
struct PragmaPushMacroHandler : public PragmaHandler {
1816
98.4k
  PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1817
1818
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1819
17.8k
                    Token &PushMacroTok) override {
1820
17.8k
    PP.HandlePragmaPushMacro(PushMacroTok);
1821
17.8k
  }
1822
};
1823
1824
/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1825
/// macro to the value on the top of the stack.
1826
struct PragmaPopMacroHandler : public PragmaHandler {
1827
98.4k
  PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1828
1829
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1830
17.8k
                    Token &PopMacroTok) override {
1831
17.8k
    PP.HandlePragmaPopMacro(PopMacroTok);
1832
17.8k
  }
1833
};
1834
1835
/// PragmaARCCFCodeAuditedHandler -
1836
///   \#pragma clang arc_cf_code_audited begin/end
1837
struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1838
98.4k
  PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1839
1840
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1841
63.6k
                    Token &NameTok) override {
1842
63.6k
    SourceLocation Loc = NameTok.getLocation();
1843
63.6k
    bool IsBegin;
1844
1845
63.6k
    Token Tok;
1846
1847
    // Lex the 'begin' or 'end'.
1848
63.6k
    PP.LexUnexpandedToken(Tok);
1849
63.6k
    const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1850
63.6k
    if (BeginEnd && BeginEnd->isStr("begin")) {
1851
31.8k
      IsBegin = true;
1852
31.8k
    } else 
if (31.8k
BeginEnd31.8k
&&
BeginEnd->isStr("end")31.8k
) {
1853
31.8k
      IsBegin = false;
1854
31.8k
    } else {
1855
1
      PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1856
1
      return;
1857
1
    }
1858
1859
    // Verify that this is followed by EOD.
1860
63.6k
    PP.LexUnexpandedToken(Tok);
1861
63.6k
    if (Tok.isNot(tok::eod))
1862
1
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1863
1864
    // The start location of the active audit.
1865
63.6k
    SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedInfo().second;
1866
1867
    // The start location we want after processing this.
1868
63.6k
    SourceLocation NewLoc;
1869
1870
63.6k
    if (IsBegin) {
1871
      // Complain about attempts to re-enter an audit.
1872
31.8k
      if (BeginLoc.isValid()) {
1873
1
        PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1874
1
        PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1875
1
      }
1876
31.8k
      NewLoc = Loc;
1877
31.8k
    } else {
1878
      // Complain about attempts to leave an audit that doesn't exist.
1879
31.8k
      if (!BeginLoc.isValid()) {
1880
1
        PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1881
1
        return;
1882
1
      }
1883
31.8k
      NewLoc = SourceLocation();
1884
31.8k
    }
1885
1886
63.6k
    PP.setPragmaARCCFCodeAuditedInfo(NameTok.getIdentifierInfo(), NewLoc);
1887
63.6k
  }
1888
};
1889
1890
/// PragmaAssumeNonNullHandler -
1891
///   \#pragma clang assume_nonnull begin/end
1892
struct PragmaAssumeNonNullHandler : public PragmaHandler {
1893
98.4k
  PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1894
1895
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1896
143k
                    Token &NameTok) override {
1897
143k
    SourceLocation Loc = NameTok.getLocation();
1898
143k
    bool IsBegin;
1899
1900
143k
    Token Tok;
1901
1902
    // Lex the 'begin' or 'end'.
1903
143k
    PP.LexUnexpandedToken(Tok);
1904
143k
    const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1905
143k
    if (BeginEnd && BeginEnd->isStr("begin")) {
1906
71.9k
      IsBegin = true;
1907
71.9k
    } else 
if (71.9k
BeginEnd71.9k
&&
BeginEnd->isStr("end")71.9k
) {
1908
71.9k
      IsBegin = false;
1909
71.9k
    } else {
1910
1
      PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1911
1
      return;
1912
1
    }
1913
1914
    // Verify that this is followed by EOD.
1915
143k
    PP.LexUnexpandedToken(Tok);
1916
143k
    if (Tok.isNot(tok::eod))
1917
0
      PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1918
1919
    // The start location of the active audit.
1920
143k
    SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1921
1922
    // The start location we want after processing this.
1923
143k
    SourceLocation NewLoc;
1924
143k
    PPCallbacks *Callbacks = PP.getPPCallbacks();
1925
1926
143k
    if (IsBegin) {
1927
      // Complain about attempts to re-enter an audit.
1928
71.9k
      if (BeginLoc.isValid()) {
1929
1
        PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1930
1
        PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1931
1
      }
1932
71.9k
      NewLoc = Loc;
1933
71.9k
      if (Callbacks)
1934
71.9k
        Callbacks->PragmaAssumeNonNullBegin(NewLoc);
1935
71.9k
    } else {
1936
      // Complain about attempts to leave an audit that doesn't exist.
1937
71.9k
      if (!BeginLoc.isValid()) {
1938
0
        PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1939
0
        return;
1940
0
      }
1941
71.9k
      NewLoc = SourceLocation();
1942
71.9k
      if (Callbacks)
1943
71.9k
        Callbacks->PragmaAssumeNonNullEnd(NewLoc);
1944
71.9k
    }
1945
1946
143k
    PP.setPragmaAssumeNonNullLoc(NewLoc);
1947
143k
  }
1948
};
1949
1950
/// Handle "\#pragma region [...]"
1951
///
1952
/// The syntax is
1953
/// \code
1954
///   #pragma region [optional name]
1955
///   #pragma endregion [optional comment]
1956
/// \endcode
1957
///
1958
/// \note This is
1959
/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1960
/// pragma, just skipped by compiler.
1961
struct PragmaRegionHandler : public PragmaHandler {
1962
196k
  PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
1963
1964
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1965
11
                    Token &NameTok) override {
1966
    // #pragma region: endregion matches can be verified
1967
    // __pragma(region): no sense, but ignored by msvc
1968
    // _Pragma is not valid for MSVC, but there isn't any point
1969
    // to handle a _Pragma differently.
1970
11
  }
1971
};
1972
1973
/// This handles parsing pragmas that take a macro name and optional message
1974
static IdentifierInfo *HandleMacroAnnotationPragma(Preprocessor &PP, Token &Tok,
1975
                                                   const char *Pragma,
1976
20
                                                   std::string &MessageString) {
1977
20
  std::string Macro;
1978
1979
20
  PP.Lex(Tok);
1980
20
  if (Tok.isNot(tok::l_paren)) {
1981
2
    PP.Diag(Tok, diag::err_expected) << "(";
1982
2
    return nullptr;
1983
2
  }
1984
1985
18
  PP.LexUnexpandedToken(Tok);
1986
18
  if (!Tok.is(tok::identifier)) {
1987
2
    PP.Diag(Tok, diag::err_expected) << tok::identifier;
1988
2
    return nullptr;
1989
2
  }
1990
16
  IdentifierInfo *II = Tok.getIdentifierInfo();
1991
1992
16
  if (!II->hasMacroDefinition()) {
1993
3
    PP.Diag(Tok, diag::err_pp_visibility_non_macro) << II->getName();
1994
3
    return nullptr;
1995
3
  }
1996
1997
13
  PP.Lex(Tok);
1998
13
  if (Tok.is(tok::comma)) {
1999
8
    PP.Lex(Tok);
2000
8
    if (!PP.FinishLexStringLiteral(Tok, MessageString, Pragma,
2001
8
                                   /*AllowMacroExpansion=*/true))
2002
0
      return nullptr;
2003
8
  }
2004
2005
13
  if (Tok.isNot(tok::r_paren)) {
2006
2
    PP.Diag(Tok, diag::err_expected) << ")";
2007
2
    return nullptr;
2008
2
  }
2009
11
  return II;
2010
13
}
2011
2012
/// "\#pragma clang deprecated(...)"
2013
///
2014
/// The syntax is
2015
/// \code
2016
///   #pragma clang deprecate(MACRO_NAME [, Message])
2017
/// \endcode
2018
struct PragmaDeprecatedHandler : public PragmaHandler {
2019
98.4k
  PragmaDeprecatedHandler() : PragmaHandler("deprecated") {}
2020
2021
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2022
12
                    Token &Tok) override {
2023
12
    std::string MessageString;
2024
2025
12
    if (IdentifierInfo *II = HandleMacroAnnotationPragma(
2026
12
            PP, Tok, "#pragma clang deprecated", MessageString)) {
2027
6
      II->setIsDeprecatedMacro(true);
2028
6
      if (!MessageString.empty())
2029
4
        PP.addMacroDeprecationMsg(II, std::move(MessageString));
2030
6
    }
2031
12
  }
2032
};
2033
2034
/// "\#pragma clang restrict_expansion(...)"
2035
///
2036
/// The syntax is
2037
/// \code
2038
///   #pragma clang restrict_expansion(MACRO_NAME [, Message])
2039
/// \endcode
2040
struct PragmaRestrictExpansionHandler : public PragmaHandler {
2041
98.4k
  PragmaRestrictExpansionHandler() : PragmaHandler("restrict_expansion") {}
2042
2043
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2044
8
                    Token &Tok) override {
2045
8
    std::string MessageString;
2046
2047
8
    if (IdentifierInfo *II = HandleMacroAnnotationPragma(
2048
8
            PP, Tok, "#pragma clang restrict_expansion", MessageString)) {
2049
5
      II->setIsRestrictExpansion(true);
2050
5
      PP.addRestrictExpansionMsg(II, std::move(MessageString),
2051
5
                                 Tok.getLocation());
2052
5
    }
2053
8
  }
2054
};
2055
2056
} // namespace
2057
2058
/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
2059
/// \#pragma GCC poison/system_header/dependency and \#pragma once.
2060
98.4k
void Preprocessor::RegisterBuiltinPragmas() {
2061
98.4k
  AddPragmaHandler(new PragmaOnceHandler());
2062
98.4k
  AddPragmaHandler(new PragmaMarkHandler());
2063
98.4k
  AddPragmaHandler(new PragmaPushMacroHandler());
2064
98.4k
  AddPragmaHandler(new PragmaPopMacroHandler());
2065
98.4k
  AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
2066
2067
  // #pragma GCC ...
2068
98.4k
  AddPragmaHandler("GCC", new PragmaPoisonHandler());
2069
98.4k
  AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
2070
98.4k
  AddPragmaHandler("GCC", new PragmaDependencyHandler());
2071
98.4k
  AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
2072
98.4k
  AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
2073
98.4k
                                                   "GCC"));
2074
98.4k
  AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
2075
98.4k
                                                   "GCC"));
2076
  // #pragma clang ...
2077
98.4k
  AddPragmaHandler("clang", new PragmaPoisonHandler());
2078
98.4k
  AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
2079
98.4k
  AddPragmaHandler("clang", new PragmaIncludeInsteadHandler());
2080
98.4k
  AddPragmaHandler("clang", new PragmaDebugHandler());
2081
98.4k
  AddPragmaHandler("clang", new PragmaDependencyHandler());
2082
98.4k
  AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
2083
98.4k
  AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
2084
98.4k
  AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
2085
98.4k
  AddPragmaHandler("clang", new PragmaDeprecatedHandler());
2086
98.4k
  AddPragmaHandler("clang", new PragmaRestrictExpansionHandler());
2087
2088
  // #pragma clang module ...
2089
98.4k
  auto *ModuleHandler = new PragmaNamespace("module");
2090
98.4k
  AddPragmaHandler("clang", ModuleHandler);
2091
98.4k
  ModuleHandler->AddPragma(new PragmaModuleImportHandler());
2092
98.4k
  ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
2093
98.4k
  ModuleHandler->AddPragma(new PragmaModuleEndHandler());
2094
98.4k
  ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
2095
98.4k
  ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
2096
2097
  // Add region pragmas.
2098
98.4k
  AddPragmaHandler(new PragmaRegionHandler("region"));
2099
98.4k
  AddPragmaHandler(new PragmaRegionHandler("endregion"));
2100
2101
  // MS extensions.
2102
98.4k
  if (LangOpts.MicrosoftExt) {
2103
10.7k
    AddPragmaHandler(new PragmaWarningHandler());
2104
10.7k
    AddPragmaHandler(new PragmaExecCharsetHandler());
2105
10.7k
    AddPragmaHandler(new PragmaIncludeAliasHandler());
2106
10.7k
    AddPragmaHandler(new PragmaHdrstopHandler());
2107
10.7k
    AddPragmaHandler(new PragmaSystemHeaderHandler());
2108
10.7k
  }
2109
2110
  // Pragmas added by plugins
2111
98.4k
  for (const PragmaHandlerRegistry::entry &handler :
2112
98.4k
       PragmaHandlerRegistry::entries()) {
2113
0
    AddPragmaHandler(handler.instantiate().release());
2114
0
  }
2115
98.4k
}
2116
2117
/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
2118
/// warn about those pragmas being unknown.
2119
1.81k
void Preprocessor::IgnorePragmas() {
2120
1.81k
  AddPragmaHandler(new EmptyPragmaHandler());
2121
  // Also ignore all pragmas in all namespaces created
2122
  // in Preprocessor::RegisterBuiltinPragmas().
2123
1.81k
  AddPragmaHandler("GCC", new EmptyPragmaHandler());
2124
1.81k
  AddPragmaHandler("clang", new EmptyPragmaHandler());
2125
1.81k
}