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