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 = Token::createAnnotation(Kind: tok::annot_pragma_parser_crash,
1119 Range: Tok.getLocation());
1120 PP.EnterToken(Tok: Crasher, /*IsReinject*/ false);
1121 }
1122 } else if (II->isStr(Str: "sleep")) {
1123 std::this_thread::sleep_for(rtime: std::chrono::milliseconds(100));
1124 } else if (II->isStr(Str: "dump")) {
1125 Token DumpAnnot =
1126 Token::createAnnotation(Kind: tok::annot_pragma_dump, Range: Tok.getLocation());
1127 PP.EnterToken(Tok: DumpAnnot, /*IsReinject*/false);
1128 } else if (II->isStr(Str: "diag_mapping")) {
1129 Token DiagName;
1130 PP.LexUnexpandedToken(Result&: DiagName);
1131 if (DiagName.is(K: tok::eod))
1132 PP.getDiagnostics().dump();
1133 else if (DiagName.is(K: tok::string_literal) && !DiagName.hasUDSuffix()) {
1134 StringLiteralParser Literal(DiagName, PP,
1135 StringLiteralEvalMethod::Unevaluated);
1136 if (Literal.hadError)
1137 return;
1138 PP.getDiagnostics().dump(DiagName: Literal.GetString());
1139 } else {
1140 PP.Diag(Tok: DiagName, DiagID: diag::warn_pragma_debug_missing_argument)
1141 << II->getName();
1142 }
1143 } else if (II->isStr(Str: "llvm_fatal_error")) {
1144 if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1145 llvm::report_fatal_error(reason: "#pragma clang __debug llvm_fatal_error");
1146 } else if (II->isStr(Str: "llvm_unreachable")) {
1147 if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1148 llvm_unreachable("#pragma clang __debug llvm_unreachable");
1149 } else if (II->isStr(Str: "macro")) {
1150 Token MacroName;
1151 PP.LexUnexpandedToken(Result&: MacroName);
1152 auto *MacroII = MacroName.getIdentifierInfo();
1153 if (MacroII)
1154 PP.dumpMacroInfo(II: MacroII);
1155 else
1156 PP.Diag(Tok: MacroName, DiagID: diag::warn_pragma_debug_missing_argument)
1157 << II->getName();
1158 } else if (II->isStr(Str: "module_map")) {
1159 llvm::SmallVector<IdentifierLoc, 8> ModuleName;
1160 if (LexModuleName(PP, Tok, ModuleName))
1161 return;
1162 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
1163 Module *M = nullptr;
1164 for (auto IIAndLoc : ModuleName) {
1165 M = MM.lookupModuleQualified(Name: IIAndLoc.getIdentifierInfo()->getName(),
1166 Context: M);
1167 if (!M) {
1168 PP.Diag(Loc: IIAndLoc.getLoc(), DiagID: diag::warn_pragma_debug_unknown_module)
1169 << IIAndLoc.getIdentifierInfo()->getName();
1170 return;
1171 }
1172 }
1173 M->dump();
1174 } else if (II->isStr(Str: "module_lookup")) {
1175 Token MName;
1176 PP.LexUnexpandedToken(Result&: MName);
1177 auto *MNameII = MName.getIdentifierInfo();
1178 if (!MNameII) {
1179 PP.Diag(Tok: MName, DiagID: diag::warn_pragma_debug_missing_argument)
1180 << II->getName();
1181 return;
1182 }
1183 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName: MNameII->getName());
1184 if (!M) {
1185 PP.Diag(Tok: MName, DiagID: diag::warn_pragma_debug_unable_to_find_module)
1186 << MNameII->getName();
1187 return;
1188 }
1189 M->dump();
1190 } else if (II->isStr(Str: "overflow_stack")) {
1191 if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1192 DebugOverflowStack();
1193 } else if (II->isStr(Str: "captured")) {
1194 HandleCaptured(PP);
1195 } else if (II->isStr(Str: "modules")) {
1196 struct ModuleVisitor {
1197 Preprocessor &PP;
1198 void visit(Module *M, bool VisibleOnly) {
1199 SourceLocation ImportLoc = PP.getModuleImportLoc(M);
1200 if (!VisibleOnly || ImportLoc.isValid()) {
1201 llvm::errs() << M->getFullModuleName() << " ";
1202 if (ImportLoc.isValid()) {
1203 llvm::errs() << M << " visible ";
1204 ImportLoc.print(OS&: llvm::errs(), SM: PP.getSourceManager());
1205 }
1206 llvm::errs() << "\n";
1207 }
1208 for (Module *Sub : M->submodules()) {
1209 if (!VisibleOnly || ImportLoc.isInvalid() || Sub->IsExplicit)
1210 visit(M: Sub, VisibleOnly);
1211 }
1212 }
1213 void visitAll(bool VisibleOnly) {
1214 for (auto &NameAndMod :
1215 PP.getHeaderSearchInfo().getModuleMap().modules())
1216 visit(M: NameAndMod.second, VisibleOnly);
1217 }
1218 } Visitor{.PP: PP};
1219
1220 Token Kind;
1221 PP.LexUnexpandedToken(Result&: Kind);
1222 auto *DumpII = Kind.getIdentifierInfo();
1223 if (!DumpII) {
1224 PP.Diag(Tok: Kind, DiagID: diag::warn_pragma_debug_missing_argument)
1225 << II->getName();
1226 } else if (DumpII->isStr(Str: "all")) {
1227 Visitor.visitAll(VisibleOnly: false);
1228 } else if (DumpII->isStr(Str: "visible")) {
1229 Visitor.visitAll(VisibleOnly: true);
1230 } else if (DumpII->isStr(Str: "building")) {
1231 for (auto &Building : PP.getBuildingSubmodules()) {
1232 llvm::errs() << "in " << Building.M->getFullModuleName();
1233 if (Building.ImportLoc.isValid()) {
1234 llvm::errs() << " imported ";
1235 if (Building.IsPragma)
1236 llvm::errs() << "via pragma ";
1237 llvm::errs() << "at ";
1238 Building.ImportLoc.print(OS&: llvm::errs(), SM: PP.getSourceManager());
1239 llvm::errs() << "\n";
1240 }
1241 }
1242 } else {
1243 PP.Diag(Tok, DiagID: diag::warn_pragma_debug_unexpected_command)
1244 << DumpII->getName();
1245 }
1246 } else if (II->isStr(Str: "sloc_usage")) {
1247 // An optional integer literal argument specifies the number of files to
1248 // specifically report information about.
1249 std::optional<unsigned> MaxNotes;
1250 Token ArgToken;
1251 PP.Lex(Result&: ArgToken);
1252 uint64_t Value;
1253 if (ArgToken.is(K: tok::numeric_constant) &&
1254 PP.parseSimpleIntegerLiteral(Tok&: ArgToken, Value)) {
1255 MaxNotes = Value;
1256 } else if (ArgToken.isNot(K: tok::eod)) {
1257 PP.Diag(Tok: ArgToken, DiagID: diag::warn_pragma_debug_unexpected_argument);
1258 }
1259
1260 PP.Diag(Tok, DiagID: diag::remark_sloc_usage);
1261 PP.getSourceManager().noteSLocAddressSpaceUsage(Diag&: PP.getDiagnostics(),
1262 MaxNotes);
1263 } else {
1264 PP.Diag(Tok, DiagID: diag::warn_pragma_debug_unexpected_command)
1265 << II->getName();
1266 }
1267
1268 PPCallbacks *Callbacks = PP.getPPCallbacks();
1269 if (Callbacks)
1270 Callbacks->PragmaDebug(Loc: Tok.getLocation(), DebugType: II->getName());
1271 }
1272
1273 void HandleCaptured(Preprocessor &PP) {
1274 Token Tok;
1275 PP.LexUnexpandedToken(Result&: Tok);
1276
1277 if (Tok.isNot(K: tok::eod)) {
1278 PP.Diag(Tok, DiagID: diag::ext_pp_extra_tokens_at_eol)
1279 << "pragma clang __debug captured";
1280 return;
1281 }
1282
1283 SourceLocation NameLoc = Tok.getLocation();
1284 MutableArrayRef<Token> Toks(
1285 PP.getPreprocessorAllocator().Allocate<Token>(Num: 1), 1);
1286 Toks[0] = Token::createAnnotation(Kind: tok::annot_pragma_captured, Range: NameLoc);
1287
1288 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
1289 /*IsReinject=*/false);
1290 }
1291
1292// Disable MSVC warning about runtime stack overflow.
1293#ifdef _MSC_VER
1294 #pragma warning(disable : 4717)
1295#endif
1296 static void DebugOverflowStack(void (*P)() = nullptr) {
1297 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1298 Self(reinterpret_cast<void(*)()>(Self));
1299 }
1300#ifdef _MSC_VER
1301 #pragma warning(default : 4717)
1302#endif
1303};
1304
1305struct PragmaUnsafeBufferUsageHandler : public PragmaHandler {
1306 PragmaUnsafeBufferUsageHandler() : PragmaHandler("unsafe_buffer_usage") {}
1307 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1308 Token &FirstToken) override {
1309 Token Tok;
1310
1311 PP.LexUnexpandedToken(Result&: Tok);
1312 if (Tok.isNot(K: tok::identifier)) {
1313 PP.Diag(Tok, DiagID: diag::err_pp_pragma_unsafe_buffer_usage_syntax);
1314 return;
1315 }
1316
1317 IdentifierInfo *II = Tok.getIdentifierInfo();
1318 SourceLocation Loc = Tok.getLocation();
1319
1320 if (II->isStr(Str: "begin")) {
1321 if (PP.enterOrExitSafeBufferOptOutRegion(isEnter: true, Loc))
1322 PP.Diag(Loc, DiagID: diag::err_pp_double_begin_pragma_unsafe_buffer_usage);
1323 } else if (II->isStr(Str: "end")) {
1324 if (PP.enterOrExitSafeBufferOptOutRegion(isEnter: false, Loc))
1325 PP.Diag(Loc, DiagID: diag::err_pp_unmatched_end_begin_pragma_unsafe_buffer_usage);
1326 } else
1327 PP.Diag(Tok, DiagID: diag::err_pp_pragma_unsafe_buffer_usage_syntax);
1328 }
1329};
1330
1331/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
1332struct PragmaDiagnosticHandler : public PragmaHandler {
1333private:
1334 const char *Namespace;
1335
1336public:
1337 explicit PragmaDiagnosticHandler(const char *NS)
1338 : PragmaHandler("diagnostic"), Namespace(NS) {}
1339
1340 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1341 Token &DiagToken) override {
1342 SourceLocation DiagLoc = DiagToken.getLocation();
1343 Token Tok;
1344 PP.LexUnexpandedToken(Result&: Tok);
1345 if (Tok.isNot(K: tok::identifier)) {
1346 PP.Diag(Tok, DiagID: diag::warn_pragma_diagnostic_invalid);
1347 return;
1348 }
1349 IdentifierInfo *II = Tok.getIdentifierInfo();
1350 PPCallbacks *Callbacks = PP.getPPCallbacks();
1351
1352 // Get the next token, which is either an EOD or a string literal. We lex
1353 // it now so that we can early return if the previous token was push or pop.
1354 PP.LexUnexpandedToken(Result&: Tok);
1355
1356 if (II->isStr(Str: "pop")) {
1357 if (!PP.getDiagnostics().popMappings(Loc: DiagLoc))
1358 PP.Diag(Tok, DiagID: diag::warn_pragma_diagnostic_cannot_pop);
1359 else if (Callbacks)
1360 Callbacks->PragmaDiagnosticPop(Loc: DiagLoc, Namespace);
1361
1362 if (Tok.isNot(K: tok::eod))
1363 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::warn_pragma_diagnostic_invalid_token);
1364 return;
1365 } else if (II->isStr(Str: "push")) {
1366 PP.getDiagnostics().pushMappings(Loc: DiagLoc);
1367 if (Callbacks)
1368 Callbacks->PragmaDiagnosticPush(Loc: DiagLoc, Namespace);
1369
1370 if (Tok.isNot(K: tok::eod))
1371 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::warn_pragma_diagnostic_invalid_token);
1372 return;
1373 }
1374
1375 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1376 .Case(S: "ignored", Value: diag::Severity::Ignored)
1377 .Case(S: "warning", Value: diag::Severity::Warning)
1378 .Case(S: "error", Value: diag::Severity::Error)
1379 .Case(S: "fatal", Value: diag::Severity::Fatal)
1380 .Default(Value: diag::Severity());
1381
1382 if (SV == diag::Severity()) {
1383 PP.Diag(Tok, DiagID: diag::warn_pragma_diagnostic_invalid);
1384 return;
1385 }
1386
1387 // At this point, we expect a string literal.
1388 SourceLocation StringLoc = Tok.getLocation();
1389 std::string WarningName;
1390 if (!PP.FinishLexStringLiteral(Result&: Tok, String&: WarningName, DiagnosticTag: "pragma diagnostic",
1391 /*AllowMacroExpansion=*/false))
1392 return;
1393
1394 if (Tok.isNot(K: tok::eod)) {
1395 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::warn_pragma_diagnostic_invalid_token);
1396 return;
1397 }
1398
1399 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1400 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
1401 PP.Diag(Loc: StringLoc, DiagID: diag::warn_pragma_diagnostic_invalid_option);
1402 return;
1403 }
1404
1405 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1406 : diag::Flavor::Remark;
1407 StringRef Group = StringRef(WarningName).substr(Start: 2);
1408 bool unknownDiag = false;
1409 if (Group == "everything") {
1410 // Special handling for pragma clang diagnostic ... "-Weverything".
1411 // There is no formal group named "everything", so there has to be a
1412 // special case for it.
1413 PP.getDiagnostics().setSeverityForAll(Flavor, Map: SV, Loc: DiagLoc);
1414 } else
1415 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, Map: SV,
1416 Loc: DiagLoc);
1417 if (unknownDiag)
1418 PP.Diag(Loc: StringLoc, DiagID: diag::warn_pragma_diagnostic_unknown_warning)
1419 << WarningName;
1420 else if (Callbacks)
1421 Callbacks->PragmaDiagnostic(Loc: DiagLoc, Namespace, mapping: SV, Str: WarningName);
1422 }
1423};
1424
1425/// "\#pragma hdrstop [<header-name-string>]"
1426struct PragmaHdrstopHandler : public PragmaHandler {
1427 PragmaHdrstopHandler() : PragmaHandler("hdrstop") {}
1428 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1429 Token &DepToken) override {
1430 PP.HandlePragmaHdrstop(Tok&: DepToken);
1431 }
1432};
1433
1434/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1435/// diagnostics, so we don't really implement this pragma. We parse it and
1436/// ignore it to avoid -Wunknown-pragma warnings.
1437struct PragmaWarningHandler : public PragmaHandler {
1438 PragmaWarningHandler() : PragmaHandler("warning") {}
1439
1440 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1441 Token &Tok) override {
1442 // Parse things like:
1443 // warning(push, 1)
1444 // warning(pop)
1445 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1446 SourceLocation DiagLoc = Tok.getLocation();
1447 PPCallbacks *Callbacks = PP.getPPCallbacks();
1448
1449 PP.Lex(Result&: Tok);
1450 if (Tok.isNot(K: tok::l_paren)) {
1451 PP.Diag(Tok, DiagID: diag::warn_pragma_warning_expected) << "(";
1452 return;
1453 }
1454
1455 PP.Lex(Result&: Tok);
1456 IdentifierInfo *II = Tok.getIdentifierInfo();
1457
1458 if (II && II->isStr(Str: "push")) {
1459 // #pragma warning( push[ ,n ] )
1460 int Level = -1;
1461 PP.Lex(Result&: Tok);
1462 if (Tok.is(K: tok::comma)) {
1463 PP.Lex(Result&: Tok);
1464 uint64_t Value;
1465 if (Tok.is(K: tok::numeric_constant) &&
1466 PP.parseSimpleIntegerLiteral(Tok, Value))
1467 Level = int(Value);
1468 if (Level < 0 || Level > 4) {
1469 PP.Diag(Tok, DiagID: diag::warn_pragma_warning_push_level);
1470 return;
1471 }
1472 }
1473 PP.getDiagnostics().pushMappings(Loc: DiagLoc);
1474 if (Callbacks)
1475 Callbacks->PragmaWarningPush(Loc: DiagLoc, Level);
1476 } else if (II && II->isStr(Str: "pop")) {
1477 // #pragma warning( pop )
1478 PP.Lex(Result&: Tok);
1479 if (!PP.getDiagnostics().popMappings(Loc: DiagLoc))
1480 PP.Diag(Tok, DiagID: diag::warn_pragma_diagnostic_cannot_pop);
1481 else if (Callbacks)
1482 Callbacks->PragmaWarningPop(Loc: DiagLoc);
1483 } else {
1484 // #pragma warning( warning-specifier : warning-number-list
1485 // [; warning-specifier : warning-number-list...] )
1486 while (true) {
1487 II = Tok.getIdentifierInfo();
1488 if (!II && !Tok.is(K: tok::numeric_constant)) {
1489 PP.Diag(Tok, DiagID: diag::warn_pragma_warning_spec_invalid);
1490 return;
1491 }
1492
1493 // Figure out which warning specifier this is.
1494 bool SpecifierValid;
1495 PPCallbacks::PragmaWarningSpecifier Specifier;
1496 if (II) {
1497 int SpecifierInt = llvm::StringSwitch<int>(II->getName())
1498 .Case(S: "default", Value: PPCallbacks::PWS_Default)
1499 .Case(S: "disable", Value: PPCallbacks::PWS_Disable)
1500 .Case(S: "error", Value: PPCallbacks::PWS_Error)
1501 .Case(S: "once", Value: PPCallbacks::PWS_Once)
1502 .Case(S: "suppress", Value: PPCallbacks::PWS_Suppress)
1503 .Default(Value: -1);
1504 SpecifierValid = SpecifierInt != -1;
1505 if (SpecifierValid)
1506 Specifier =
1507 static_cast<PPCallbacks::PragmaWarningSpecifier>(SpecifierInt);
1508
1509 // If we read a correct specifier, snatch next token (that should be
1510 // ":", checked later).
1511 if (SpecifierValid)
1512 PP.Lex(Result&: Tok);
1513 } else {
1514 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1515 uint64_t Value;
1516 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1517 if ((SpecifierValid = (Value >= 1) && (Value <= 4)))
1518 Specifier = static_cast<PPCallbacks::PragmaWarningSpecifier>(
1519 PPCallbacks::PWS_Level1 + Value - 1);
1520 } else
1521 SpecifierValid = false;
1522 // Next token already snatched by parseSimpleIntegerLiteral.
1523 }
1524
1525 if (!SpecifierValid) {
1526 PP.Diag(Tok, DiagID: diag::warn_pragma_warning_spec_invalid);
1527 return;
1528 }
1529 if (Tok.isNot(K: tok::colon)) {
1530 PP.Diag(Tok, DiagID: diag::warn_pragma_warning_expected) << ":";
1531 return;
1532 }
1533
1534 // Collect the warning ids.
1535 SmallVector<int, 4> Ids;
1536 PP.Lex(Result&: Tok);
1537 while (Tok.is(K: tok::numeric_constant)) {
1538 uint64_t Value;
1539 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1540 Value > INT_MAX) {
1541 PP.Diag(Tok, DiagID: diag::warn_pragma_warning_expected_number);
1542 return;
1543 }
1544 Ids.push_back(Elt: int(Value));
1545 }
1546
1547 // Only act on disable for now.
1548 diag::Severity SV = diag::Severity();
1549 if (Specifier == PPCallbacks::PWS_Disable)
1550 SV = diag::Severity::Ignored;
1551 if (SV != diag::Severity())
1552 for (int Id : Ids) {
1553 if (auto Group = diagGroupFromCLWarningID(Id)) {
1554 bool unknownDiag = PP.getDiagnostics().setSeverityForGroup(
1555 Flavor: diag::Flavor::WarningOrError, Group: *Group, Map: SV, Loc: DiagLoc);
1556 assert(!unknownDiag &&
1557 "wd table should only contain known diags");
1558 (void)unknownDiag;
1559 }
1560 }
1561
1562 if (Callbacks)
1563 Callbacks->PragmaWarning(Loc: DiagLoc, WarningSpec: Specifier, Ids);
1564
1565 // Parse the next specifier if there is a semicolon.
1566 if (Tok.isNot(K: tok::semi))
1567 break;
1568 PP.Lex(Result&: Tok);
1569 }
1570 }
1571
1572 if (Tok.isNot(K: tok::r_paren)) {
1573 PP.Diag(Tok, DiagID: diag::warn_pragma_warning_expected) << ")";
1574 return;
1575 }
1576
1577 PP.Lex(Result&: Tok);
1578 if (Tok.isNot(K: tok::eod))
1579 PP.Diag(Tok, DiagID: diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1580 }
1581};
1582
1583/// "\#pragma execution_character_set(...)". MSVC supports this pragma only
1584/// for "UTF-8". We parse it and ignore it if UTF-8 is provided and warn
1585/// otherwise to avoid -Wunknown-pragma warnings.
1586struct PragmaExecCharsetHandler : public PragmaHandler {
1587 PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {}
1588
1589 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1590 Token &Tok) override {
1591 // Parse things like:
1592 // execution_character_set(push, "UTF-8")
1593 // execution_character_set(pop)
1594 SourceLocation DiagLoc = Tok.getLocation();
1595 PPCallbacks *Callbacks = PP.getPPCallbacks();
1596
1597 PP.Lex(Result&: Tok);
1598 if (Tok.isNot(K: tok::l_paren)) {
1599 PP.Diag(Tok, DiagID: diag::warn_pragma_exec_charset_expected) << "(";
1600 return;
1601 }
1602
1603 PP.Lex(Result&: Tok);
1604 IdentifierInfo *II = Tok.getIdentifierInfo();
1605
1606 if (II && II->isStr(Str: "push")) {
1607 // #pragma execution_character_set( push[ , string ] )
1608 PP.Lex(Result&: Tok);
1609 if (Tok.is(K: tok::comma)) {
1610 PP.Lex(Result&: Tok);
1611
1612 std::string ExecCharset;
1613 if (!PP.FinishLexStringLiteral(Result&: Tok, String&: ExecCharset,
1614 DiagnosticTag: "pragma execution_character_set",
1615 /*AllowMacroExpansion=*/false))
1616 return;
1617
1618 // MSVC supports either of these, but nothing else.
1619 if (ExecCharset != "UTF-8" && ExecCharset != "utf-8") {
1620 PP.Diag(Tok, DiagID: diag::warn_pragma_exec_charset_push_invalid) << ExecCharset;
1621 return;
1622 }
1623 }
1624 if (Callbacks)
1625 Callbacks->PragmaExecCharsetPush(Loc: DiagLoc, Str: "UTF-8");
1626 } else if (II && II->isStr(Str: "pop")) {
1627 // #pragma execution_character_set( pop )
1628 PP.Lex(Result&: Tok);
1629 if (Callbacks)
1630 Callbacks->PragmaExecCharsetPop(Loc: DiagLoc);
1631 } else {
1632 PP.Diag(Tok, DiagID: diag::warn_pragma_exec_charset_spec_invalid);
1633 return;
1634 }
1635
1636 if (Tok.isNot(K: tok::r_paren)) {
1637 PP.Diag(Tok, DiagID: diag::warn_pragma_exec_charset_expected) << ")";
1638 return;
1639 }
1640
1641 PP.Lex(Result&: Tok);
1642 if (Tok.isNot(K: tok::eod))
1643 PP.Diag(Tok, DiagID: diag::ext_pp_extra_tokens_at_eol) << "pragma execution_character_set";
1644 }
1645};
1646
1647/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1648struct PragmaIncludeAliasHandler : public PragmaHandler {
1649 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1650
1651 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1652 Token &IncludeAliasTok) override {
1653 PP.HandlePragmaIncludeAlias(Tok&: IncludeAliasTok);
1654 }
1655};
1656
1657/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1658/// extension. The syntax is:
1659/// \code
1660/// #pragma message(string)
1661/// \endcode
1662/// OR, in GCC mode:
1663/// \code
1664/// #pragma message string
1665/// \endcode
1666/// string is a string, which is fully macro expanded, and permits string
1667/// concatenation, embedded escape characters, etc... See MSDN for more details.
1668/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1669/// form as \#pragma message.
1670struct PragmaMessageHandler : public PragmaHandler {
1671private:
1672 const PPCallbacks::PragmaMessageKind Kind;
1673 const StringRef Namespace;
1674
1675 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1676 bool PragmaNameOnly = false) {
1677 switch (Kind) {
1678 case PPCallbacks::PMK_Message:
1679 return PragmaNameOnly ? "message" : "pragma message";
1680 case PPCallbacks::PMK_Warning:
1681 return PragmaNameOnly ? "warning" : "pragma warning";
1682 case PPCallbacks::PMK_Error:
1683 return PragmaNameOnly ? "error" : "pragma error";
1684 }
1685 llvm_unreachable("Unknown PragmaMessageKind!");
1686 }
1687
1688public:
1689 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1690 StringRef Namespace = StringRef())
1691 : PragmaHandler(PragmaKind(Kind, PragmaNameOnly: true)), Kind(Kind),
1692 Namespace(Namespace) {}
1693
1694 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1695 Token &Tok) override {
1696 SourceLocation MessageLoc = Tok.getLocation();
1697 PP.Lex(Result&: Tok);
1698 bool ExpectClosingParen = false;
1699 switch (Tok.getKind()) {
1700 case tok::l_paren:
1701 // We have a MSVC style pragma message.
1702 ExpectClosingParen = true;
1703 // Read the string.
1704 PP.Lex(Result&: Tok);
1705 break;
1706 case tok::string_literal:
1707 // We have a GCC style pragma message, and we just read the string.
1708 break;
1709 default:
1710 PP.Diag(Loc: MessageLoc, DiagID: diag::err_pragma_message_malformed) << Kind;
1711 return;
1712 }
1713
1714 std::string MessageString;
1715 if (!PP.FinishLexStringLiteral(Result&: Tok, String&: MessageString, DiagnosticTag: PragmaKind(Kind),
1716 /*AllowMacroExpansion=*/true))
1717 return;
1718
1719 if (ExpectClosingParen) {
1720 if (Tok.isNot(K: tok::r_paren)) {
1721 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_pragma_message_malformed) << Kind;
1722 return;
1723 }
1724 PP.Lex(Result&: Tok); // eat the r_paren.
1725 }
1726
1727 if (Tok.isNot(K: tok::eod)) {
1728 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_pragma_message_malformed) << Kind;
1729 return;
1730 }
1731
1732 // Output the message.
1733 PP.Diag(Loc: MessageLoc, DiagID: (Kind == PPCallbacks::PMK_Error)
1734 ? diag::err_pragma_message
1735 : diag::warn_pragma_message) << MessageString;
1736
1737 // If the pragma is lexically sound, notify any interested PPCallbacks.
1738 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1739 Callbacks->PragmaMessage(Loc: MessageLoc, Namespace, Kind, Str: MessageString);
1740 }
1741};
1742
1743/// Handle the clang \#pragma module import extension. The syntax is:
1744/// \code
1745/// #pragma clang module import some.module.name
1746/// \endcode
1747struct PragmaModuleImportHandler : public PragmaHandler {
1748 PragmaModuleImportHandler() : PragmaHandler("import") {}
1749
1750 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1751 Token &Tok) override {
1752 SourceLocation ImportLoc = Tok.getLocation();
1753
1754 // Read the module name.
1755 llvm::SmallVector<IdentifierLoc, 8> ModuleName;
1756 if (LexModuleName(PP, Tok, ModuleName))
1757 return;
1758
1759 if (Tok.isNot(K: tok::eod))
1760 PP.Diag(Tok, DiagID: diag::ext_pp_extra_tokens_at_eol) << "pragma";
1761
1762 // If we have a non-empty module path, load the named module.
1763 Module *Imported =
1764 PP.getModuleLoader().loadModule(ImportLoc, Path: ModuleName, Visibility: Module::Hidden,
1765 /*IsInclusionDirective=*/false);
1766 if (!Imported)
1767 return;
1768
1769 PP.makeModuleVisible(M: Imported, Loc: ImportLoc);
1770 PP.EnterAnnotationToken(Range: SourceRange(ImportLoc, ModuleName.back().getLoc()),
1771 Kind: tok::annot_module_include, AnnotationVal: Imported);
1772 if (auto *CB = PP.getPPCallbacks())
1773 CB->moduleImport(ImportLoc, Path: ModuleName, Imported);
1774 }
1775};
1776
1777/// Handle the clang \#pragma module begin extension. The syntax is:
1778/// \code
1779/// #pragma clang module begin some.module.name
1780/// ...
1781/// #pragma clang module end
1782/// \endcode
1783struct PragmaModuleBeginHandler : public PragmaHandler {
1784 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1785
1786 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1787 Token &Tok) override {
1788 SourceLocation BeginLoc = Tok.getLocation();
1789
1790 // Read the module name.
1791 llvm::SmallVector<IdentifierLoc, 8> ModuleName;
1792 if (LexModuleName(PP, Tok, ModuleName))
1793 return;
1794
1795 if (Tok.isNot(K: tok::eod))
1796 PP.Diag(Tok, DiagID: diag::ext_pp_extra_tokens_at_eol) << "pragma";
1797
1798 // We can only enter submodules of the current module.
1799 StringRef Current = PP.getLangOpts().CurrentModule;
1800 if (ModuleName.front().getIdentifierInfo()->getName() != Current) {
1801 PP.Diag(Loc: ModuleName.front().getLoc(),
1802 DiagID: diag::err_pp_module_begin_wrong_module)
1803 << ModuleName.front().getIdentifierInfo() << (ModuleName.size() > 1)
1804 << Current.empty() << Current;
1805 return;
1806 }
1807
1808 // Find the module we're entering. We require that a module map for it
1809 // be loaded or implicitly loadable.
1810 auto &HSI = PP.getHeaderSearchInfo();
1811 auto &MM = HSI.getModuleMap();
1812 Module *M = HSI.lookupModule(ModuleName: Current, ImportLoc: ModuleName.front().getLoc());
1813 if (!M) {
1814 PP.Diag(Loc: ModuleName.front().getLoc(),
1815 DiagID: diag::err_pp_module_begin_no_module_map)
1816 << Current;
1817 return;
1818 }
1819 for (unsigned I = 1; I != ModuleName.size(); ++I) {
1820 auto *NewM = MM.findOrInferSubmodule(
1821 Parent: M, Name: ModuleName[I].getIdentifierInfo()->getName());
1822 if (!NewM) {
1823 PP.Diag(Loc: ModuleName[I].getLoc(), DiagID: diag::err_pp_module_begin_no_submodule)
1824 << M->getFullModuleName() << ModuleName[I].getIdentifierInfo();
1825 return;
1826 }
1827 M = NewM;
1828 }
1829
1830 // If the module isn't available, it doesn't make sense to enter it.
1831 if (Preprocessor::checkModuleIsAvailable(
1832 LangOpts: PP.getLangOpts(), TargetInfo: PP.getTargetInfo(), M: *M, Diags&: PP.getDiagnostics())) {
1833 PP.Diag(Loc: BeginLoc, DiagID: diag::note_pp_module_begin_here)
1834 << M->getTopLevelModuleName();
1835 return;
1836 }
1837
1838 // Enter the scope of the submodule.
1839 PP.EnterSubmodule(M, ImportLoc: BeginLoc, /*ForPragma*/true);
1840 PP.EnterAnnotationToken(Range: SourceRange(BeginLoc, ModuleName.back().getLoc()),
1841 Kind: tok::annot_module_begin, AnnotationVal: M);
1842 }
1843};
1844
1845/// Handle the clang \#pragma module end extension.
1846struct PragmaModuleEndHandler : public PragmaHandler {
1847 PragmaModuleEndHandler() : PragmaHandler("end") {}
1848
1849 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1850 Token &Tok) override {
1851 SourceLocation Loc = Tok.getLocation();
1852
1853 PP.LexUnexpandedToken(Result&: Tok);
1854 if (Tok.isNot(K: tok::eod))
1855 PP.Diag(Tok, DiagID: diag::ext_pp_extra_tokens_at_eol) << "pragma";
1856
1857 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1858 if (M)
1859 PP.EnterAnnotationToken(Range: SourceRange(Loc), Kind: tok::annot_module_end, AnnotationVal: M);
1860 else
1861 PP.Diag(Loc, DiagID: diag::err_pp_module_end_without_module_begin);
1862 }
1863};
1864
1865/// Handle the clang \#pragma module build extension.
1866struct PragmaModuleBuildHandler : public PragmaHandler {
1867 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1868
1869 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1870 Token &Tok) override {
1871 PP.HandlePragmaModuleBuild(Tok);
1872 }
1873};
1874
1875/// Handle the clang \#pragma module load extension.
1876struct PragmaModuleLoadHandler : public PragmaHandler {
1877 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1878
1879 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1880 Token &Tok) override {
1881 SourceLocation Loc = Tok.getLocation();
1882
1883 // Read the module name.
1884 llvm::SmallVector<IdentifierLoc, 8> ModuleName;
1885 if (LexModuleName(PP, Tok, ModuleName))
1886 return;
1887
1888 if (Tok.isNot(K: tok::eod))
1889 PP.Diag(Tok, DiagID: diag::ext_pp_extra_tokens_at_eol) << "pragma";
1890
1891 // Load the module, don't make it visible.
1892 PP.getModuleLoader().loadModule(ImportLoc: Loc, Path: ModuleName, Visibility: Module::Hidden,
1893 /*IsInclusionDirective=*/false);
1894 }
1895};
1896
1897/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1898/// macro on the top of the stack.
1899struct PragmaPushMacroHandler : public PragmaHandler {
1900 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1901
1902 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1903 Token &PushMacroTok) override {
1904 PP.HandlePragmaPushMacro(PushMacroTok);
1905 }
1906};
1907
1908/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1909/// macro to the value on the top of the stack.
1910struct PragmaPopMacroHandler : public PragmaHandler {
1911 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1912
1913 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1914 Token &PopMacroTok) override {
1915 PP.HandlePragmaPopMacro(PopMacroTok);
1916 }
1917};
1918
1919/// PragmaARCCFCodeAuditedHandler -
1920/// \#pragma clang arc_cf_code_audited begin/end
1921struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1922 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1923
1924 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1925 Token &NameTok) override {
1926 SourceLocation Loc = NameTok.getLocation();
1927 bool IsBegin;
1928
1929 Token Tok;
1930
1931 // Lex the 'begin' or 'end'.
1932 PP.LexUnexpandedToken(Result&: Tok);
1933 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1934 if (BeginEnd && BeginEnd->isStr(Str: "begin")) {
1935 IsBegin = true;
1936 } else if (BeginEnd && BeginEnd->isStr(Str: "end")) {
1937 IsBegin = false;
1938 } else {
1939 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_pp_arc_cf_code_audited_syntax);
1940 return;
1941 }
1942
1943 // Verify that this is followed by EOD.
1944 PP.LexUnexpandedToken(Result&: Tok);
1945 if (Tok.isNot(K: tok::eod))
1946 PP.Diag(Tok, DiagID: diag::ext_pp_extra_tokens_at_eol) << "pragma";
1947
1948 // The start location of the active audit.
1949 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedInfo().getLoc();
1950
1951 // The start location we want after processing this.
1952 SourceLocation NewLoc;
1953
1954 if (IsBegin) {
1955 // Complain about attempts to re-enter an audit.
1956 if (BeginLoc.isValid()) {
1957 PP.Diag(Loc, DiagID: diag::err_pp_double_begin_of_arc_cf_code_audited);
1958 PP.Diag(Loc: BeginLoc, DiagID: diag::note_pragma_entered_here);
1959 }
1960 NewLoc = Loc;
1961 } else {
1962 // Complain about attempts to leave an audit that doesn't exist.
1963 if (!BeginLoc.isValid()) {
1964 PP.Diag(Loc, DiagID: diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1965 return;
1966 }
1967 NewLoc = SourceLocation();
1968 }
1969
1970 PP.setPragmaARCCFCodeAuditedInfo(Ident: NameTok.getIdentifierInfo(), Loc: NewLoc);
1971 }
1972};
1973
1974/// PragmaAssumeNonNullHandler -
1975/// \#pragma clang assume_nonnull begin/end
1976struct PragmaAssumeNonNullHandler : public PragmaHandler {
1977 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1978
1979 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1980 Token &NameTok) override {
1981 SourceLocation Loc = NameTok.getLocation();
1982 bool IsBegin;
1983
1984 Token Tok;
1985
1986 // Lex the 'begin' or 'end'.
1987 PP.LexUnexpandedToken(Result&: Tok);
1988 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1989 if (BeginEnd && BeginEnd->isStr(Str: "begin")) {
1990 IsBegin = true;
1991 } else if (BeginEnd && BeginEnd->isStr(Str: "end")) {
1992 IsBegin = false;
1993 } else {
1994 PP.Diag(Loc: Tok.getLocation(), DiagID: diag::err_pp_assume_nonnull_syntax);
1995 return;
1996 }
1997
1998 // Verify that this is followed by EOD.
1999 PP.LexUnexpandedToken(Result&: Tok);
2000 if (Tok.isNot(K: tok::eod))
2001 PP.Diag(Tok, DiagID: diag::ext_pp_extra_tokens_at_eol) << "pragma";
2002
2003 // The start location of the active audit.
2004 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
2005
2006 // The start location we want after processing this.
2007 SourceLocation NewLoc;
2008 PPCallbacks *Callbacks = PP.getPPCallbacks();
2009
2010 if (IsBegin) {
2011 // Complain about attempts to re-enter an audit.
2012 if (BeginLoc.isValid()) {
2013 PP.Diag(Loc, DiagID: diag::err_pp_double_begin_of_assume_nonnull);
2014 PP.Diag(Loc: BeginLoc, DiagID: diag::note_pragma_entered_here);
2015 }
2016 NewLoc = Loc;
2017 if (Callbacks)
2018 Callbacks->PragmaAssumeNonNullBegin(Loc: NewLoc);
2019 } else {
2020 // Complain about attempts to leave an audit that doesn't exist.
2021 if (!BeginLoc.isValid()) {
2022 PP.Diag(Loc, DiagID: diag::err_pp_unmatched_end_of_assume_nonnull);
2023 return;
2024 }
2025 NewLoc = SourceLocation();
2026 if (Callbacks)
2027 Callbacks->PragmaAssumeNonNullEnd(Loc: NewLoc);
2028 }
2029
2030 PP.setPragmaAssumeNonNullLoc(NewLoc);
2031 }
2032};
2033
2034/// Handle "\#pragma region [...]"
2035///
2036/// The syntax is
2037/// \code
2038/// #pragma region [optional name]
2039/// #pragma endregion [optional comment]
2040/// \endcode
2041///
2042/// \note This is
2043/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
2044/// pragma, just skipped by compiler.
2045struct PragmaRegionHandler : public PragmaHandler {
2046 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
2047
2048 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2049 Token &NameTok) override {
2050 // #pragma region: endregion matches can be verified
2051 // __pragma(region): no sense, but ignored by msvc
2052 // _Pragma is not valid for MSVC, but there isn't any point
2053 // to handle a _Pragma differently.
2054 }
2055};
2056
2057/// "\#pragma managed"
2058/// "\#pragma managed(...)"
2059/// "\#pragma unmanaged"
2060/// MSVC ignores this pragma when not compiling using /clr, which clang doesn't
2061/// support. We parse it and ignore it to avoid -Wunknown-pragma warnings.
2062struct PragmaManagedHandler : public EmptyPragmaHandler {
2063 PragmaManagedHandler(const char *pragma) : EmptyPragmaHandler(pragma) {}
2064};
2065
2066/// This handles parsing pragmas that take a macro name and optional message
2067static IdentifierInfo *HandleMacroAnnotationPragma(Preprocessor &PP, Token &Tok,
2068 const char *Pragma,
2069 std::string &MessageString) {
2070 PP.Lex(Result&: Tok);
2071 if (Tok.isNot(K: tok::l_paren)) {
2072 PP.Diag(Tok, DiagID: diag::err_expected) << "(";
2073 return nullptr;
2074 }
2075
2076 PP.LexUnexpandedToken(Result&: Tok);
2077 if (!Tok.is(K: tok::identifier)) {
2078 PP.Diag(Tok, DiagID: diag::err_expected) << tok::identifier;
2079 return nullptr;
2080 }
2081 IdentifierInfo *II = Tok.getIdentifierInfo();
2082
2083 if (!II->hasMacroDefinition()) {
2084 PP.Diag(Tok, DiagID: diag::err_pp_visibility_non_macro) << II;
2085 return nullptr;
2086 }
2087
2088 PP.Lex(Result&: Tok);
2089 if (Tok.is(K: tok::comma)) {
2090 PP.Lex(Result&: Tok);
2091 if (!PP.FinishLexStringLiteral(Result&: Tok, String&: MessageString, DiagnosticTag: Pragma,
2092 /*AllowMacroExpansion=*/true))
2093 return nullptr;
2094 }
2095
2096 if (Tok.isNot(K: tok::r_paren)) {
2097 PP.Diag(Tok, DiagID: diag::err_expected) << ")";
2098 return nullptr;
2099 }
2100 return II;
2101}
2102
2103/// "\#pragma clang deprecated(...)"
2104///
2105/// The syntax is
2106/// \code
2107/// #pragma clang deprecate(MACRO_NAME [, Message])
2108/// \endcode
2109struct PragmaDeprecatedHandler : public PragmaHandler {
2110 PragmaDeprecatedHandler() : PragmaHandler("deprecated") {}
2111
2112 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2113 Token &Tok) override {
2114 std::string MessageString;
2115
2116 if (IdentifierInfo *II = HandleMacroAnnotationPragma(
2117 PP, Tok, Pragma: "#pragma clang deprecated", MessageString)) {
2118 II->setIsDeprecatedMacro(true);
2119 PP.addMacroDeprecationMsg(II, Msg: std::move(MessageString),
2120 AnnotationLoc: Tok.getLocation());
2121 }
2122 }
2123};
2124
2125/// "\#pragma clang restrict_expansion(...)"
2126///
2127/// The syntax is
2128/// \code
2129/// #pragma clang restrict_expansion(MACRO_NAME [, Message])
2130/// \endcode
2131struct PragmaRestrictExpansionHandler : public PragmaHandler {
2132 PragmaRestrictExpansionHandler() : PragmaHandler("restrict_expansion") {}
2133
2134 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2135 Token &Tok) override {
2136 std::string MessageString;
2137
2138 if (IdentifierInfo *II = HandleMacroAnnotationPragma(
2139 PP, Tok, Pragma: "#pragma clang restrict_expansion", MessageString)) {
2140 II->setIsRestrictExpansion(true);
2141 PP.addRestrictExpansionMsg(II, Msg: std::move(MessageString),
2142 AnnotationLoc: Tok.getLocation());
2143 }
2144 }
2145};
2146
2147/// "\#pragma clang final(...)"
2148///
2149/// The syntax is
2150/// \code
2151/// #pragma clang final(MACRO_NAME)
2152/// \endcode
2153struct PragmaFinalHandler : public PragmaHandler {
2154 PragmaFinalHandler() : PragmaHandler("final") {}
2155
2156 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2157 Token &Tok) override {
2158 PP.Lex(Result&: Tok);
2159 if (Tok.isNot(K: tok::l_paren)) {
2160 PP.Diag(Tok, DiagID: diag::err_expected) << "(";
2161 return;
2162 }
2163
2164 PP.LexUnexpandedToken(Result&: Tok);
2165 if (!Tok.is(K: tok::identifier)) {
2166 PP.Diag(Tok, DiagID: diag::err_expected) << tok::identifier;
2167 return;
2168 }
2169 IdentifierInfo *II = Tok.getIdentifierInfo();
2170
2171 if (!II->hasMacroDefinition()) {
2172 PP.Diag(Tok, DiagID: diag::err_pp_visibility_non_macro) << II;
2173 return;
2174 }
2175
2176 PP.Lex(Result&: Tok);
2177 if (Tok.isNot(K: tok::r_paren)) {
2178 PP.Diag(Tok, DiagID: diag::err_expected) << ")";
2179 return;
2180 }
2181 II->setIsFinal(true);
2182 PP.addFinalLoc(II, AnnotationLoc: Tok.getLocation());
2183 }
2184};
2185
2186/// "\#pragma clang __set_pp_state ..."
2187///
2188/// This pragma takes an identifier+value pair and sets some internal state in
2189/// the compiler; it is intended primarily to preserve preprocessor state that
2190/// is required for compilation to function properly across preprocessor runs
2191/// if '-E' is used. This is an internal pragma that should not be used by
2192/// users.
2193///
2194/// The syntax is
2195/// \code
2196/// #pragma clang __set_pp_state glibcxx_version INTEGER
2197/// \endcode
2198struct PragmaSetPPStateHandler : PragmaHandler {
2199 PragmaSetPPStateHandler() : PragmaHandler("__set_pp_state") {}
2200 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2201 Token &Tok) override {
2202 PP.HandlePragmaSetPPState(Introducer, Tok);
2203 }
2204};
2205} // namespace
2206
2207/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
2208/// \#pragma GCC poison/system_header/dependency and \#pragma once.
2209void Preprocessor::RegisterBuiltinPragmas() {
2210 AddPragmaHandler(Handler: new PragmaOnceHandler());
2211 AddPragmaHandler(Handler: new PragmaMarkHandler());
2212 AddPragmaHandler(Handler: new PragmaPushMacroHandler());
2213 AddPragmaHandler(Handler: new PragmaPopMacroHandler());
2214 AddPragmaHandler(Handler: new PragmaMessageHandler(PPCallbacks::PMK_Message));
2215
2216 // #pragma GCC ...
2217 AddPragmaHandler(Namespace: "GCC", Handler: new PragmaPoisonHandler());
2218 AddPragmaHandler(Namespace: "GCC", Handler: new PragmaSystemHeaderHandler());
2219 AddPragmaHandler(Namespace: "GCC", Handler: new PragmaDependencyHandler());
2220 AddPragmaHandler(Namespace: "GCC", Handler: new PragmaDiagnosticHandler("GCC"));
2221 AddPragmaHandler(Namespace: "GCC", Handler: new PragmaMessageHandler(PPCallbacks::PMK_Warning,
2222 "GCC"));
2223 AddPragmaHandler(Namespace: "GCC", Handler: new PragmaMessageHandler(PPCallbacks::PMK_Error,
2224 "GCC"));
2225 // #pragma clang ...
2226 AddPragmaHandler(Namespace: "clang", Handler: new PragmaPoisonHandler());
2227 AddPragmaHandler(Namespace: "clang", Handler: new PragmaSystemHeaderHandler());
2228 AddPragmaHandler(Namespace: "clang", Handler: new PragmaDebugHandler());
2229 AddPragmaHandler(Namespace: "clang", Handler: new PragmaDependencyHandler());
2230 AddPragmaHandler(Namespace: "clang", Handler: new PragmaDiagnosticHandler("clang"));
2231 AddPragmaHandler(Namespace: "clang", Handler: new PragmaARCCFCodeAuditedHandler());
2232 AddPragmaHandler(Namespace: "clang", Handler: new PragmaAssumeNonNullHandler());
2233 AddPragmaHandler(Namespace: "clang", Handler: new PragmaDeprecatedHandler());
2234 AddPragmaHandler(Namespace: "clang", Handler: new PragmaRestrictExpansionHandler());
2235 AddPragmaHandler(Namespace: "clang", Handler: new PragmaFinalHandler());
2236 AddPragmaHandler(Namespace: "clang", Handler: new PragmaSetPPStateHandler());
2237
2238 // #pragma clang module ...
2239 auto *ModuleHandler = new PragmaNamespace("module");
2240 AddPragmaHandler(Namespace: "clang", Handler: ModuleHandler);
2241 ModuleHandler->AddPragma(Handler: new PragmaModuleImportHandler());
2242 ModuleHandler->AddPragma(Handler: new PragmaModuleBeginHandler());
2243 ModuleHandler->AddPragma(Handler: new PragmaModuleEndHandler());
2244 ModuleHandler->AddPragma(Handler: new PragmaModuleBuildHandler());
2245 ModuleHandler->AddPragma(Handler: new PragmaModuleLoadHandler());
2246
2247 // Safe Buffers pragmas
2248 AddPragmaHandler(Namespace: "clang", Handler: new PragmaUnsafeBufferUsageHandler);
2249
2250 // Add region pragmas.
2251 AddPragmaHandler(Handler: new PragmaRegionHandler("region"));
2252 AddPragmaHandler(Handler: new PragmaRegionHandler("endregion"));
2253
2254 // MS extensions.
2255 if (LangOpts.MicrosoftExt) {
2256 AddPragmaHandler(Handler: new PragmaWarningHandler());
2257 AddPragmaHandler(Handler: new PragmaExecCharsetHandler());
2258 AddPragmaHandler(Handler: new PragmaIncludeAliasHandler());
2259 AddPragmaHandler(Handler: new PragmaHdrstopHandler());
2260 AddPragmaHandler(Handler: new PragmaSystemHeaderHandler());
2261 AddPragmaHandler(Handler: new PragmaManagedHandler("managed"));
2262 AddPragmaHandler(Handler: new PragmaManagedHandler("unmanaged"));
2263 }
2264
2265 // Pragmas added by plugins
2266 for (const PragmaHandlerRegistry::entry &handler :
2267 PragmaHandlerRegistry::entries()) {
2268 AddPragmaHandler(Handler: handler.instantiate().release());
2269 }
2270}
2271
2272/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
2273/// warn about those pragmas being unknown.
2274void Preprocessor::IgnorePragmas() {
2275 AddPragmaHandler(Handler: new EmptyPragmaHandler());
2276 // Also ignore all pragmas in all namespaces created
2277 // in Preprocessor::RegisterBuiltinPragmas().
2278 AddPragmaHandler(Namespace: "GCC", Handler: new EmptyPragmaHandler());
2279 AddPragmaHandler(Namespace: "clang", Handler: new EmptyPragmaHandler());
2280}
2281