blob: 8aff163d798b1d5e2b8f35ba9e3a459e8910dc29 [file] [log] [blame]
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001//===- Pragma.cpp - Pragma registration and handling ----------------------===//
Chris Lattnerb8761832006-06-24 21:31:03 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattnerb8761832006-06-24 21:31:03 +00006//
7//===----------------------------------------------------------------------===//
8//
Chris Lattnerb694ba72006-07-02 22:41:36 +00009// This file implements the PragmaHandler/PragmaTable interfaces and implements
10// pragma related methods of the Preprocessor class.
Chris Lattnerb8761832006-06-24 21:31:03 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Pragma.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000015#include "clang/Basic/Diagnostic.h"
Chris Lattnerb694ba72006-07-02 22:41:36 +000016#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000017#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000018#include "clang/Basic/LLVM.h"
19#include "clang/Basic/LangOptions.h"
20#include "clang/Basic/Module.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000021#include "clang/Basic/SourceLocation.h"
Chris Lattnerb694ba72006-07-02 22:41:36 +000022#include "clang/Basic/SourceManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000023#include "clang/Basic/TokenKinds.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Lex/HeaderSearch.h"
25#include "clang/Lex/LexDiagnostic.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000026#include "clang/Lex/Lexer.h"
Richard Smith9565c75b2017-06-19 23:09:36 +000027#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Lex/MacroInfo.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000029#include "clang/Lex/ModuleLoader.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000030#include "clang/Lex/PPCallbacks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Lex/Preprocessor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000032#include "clang/Lex/PreprocessorLexer.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000033#include "clang/Lex/Token.h"
34#include "clang/Lex/TokenLexer.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/DenseMap.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000037#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000038#include "llvm/ADT/SmallString.h"
39#include "llvm/ADT/SmallVector.h"
Andrew V. Tischenkoc88deb12018-04-10 10:34:13 +000040#include "llvm/ADT/StringSwitch.h"
Nico Weberade321e2018-04-10 18:53:28 +000041#include "llvm/ADT/StringRef.h"
Andrew V. Tischenkoc88deb12018-04-10 10:34:13 +000042#include "llvm/Support/CrashRecoveryContext.h"
Nico Weberade321e2018-04-10 18:53:28 +000043#include "llvm/Support/Compiler.h"
Daniel Dunbarf2cf3292010-08-17 22:32:48 +000044#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000045#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000046#include <cassert>
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000047#include <cstddef>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000048#include <cstdint>
49#include <limits>
50#include <string>
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000051#include <utility>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000052#include <vector>
53
Chris Lattnerb8761832006-06-24 21:31:03 +000054using namespace clang;
55
56// Out-of-line destructor to provide a home for the class.
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000057PragmaHandler::~PragmaHandler() = default;
Chris Lattnerb8761832006-06-24 21:31:03 +000058
Chris Lattner2e155302006-07-03 05:34:41 +000059//===----------------------------------------------------------------------===//
Daniel Dunbard839e772010-06-11 20:10:12 +000060// EmptyPragmaHandler Implementation.
61//===----------------------------------------------------------------------===//
62
Hans Wennborg7357bbc2015-10-12 20:47:58 +000063EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000064
Fangrui Song6907ce22018-07-30 19:24:48 +000065void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
Douglas Gregorc7d65762010-09-09 22:45:38 +000066 PragmaIntroducerKind Introducer,
67 Token &FirstToken) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000068
69//===----------------------------------------------------------------------===//
Chris Lattner2e155302006-07-03 05:34:41 +000070// PragmaNamespace Implementation.
71//===----------------------------------------------------------------------===//
72
Chris Lattner2e155302006-07-03 05:34:41 +000073PragmaNamespace::~PragmaNamespace() {
Reid Kleckner588c9372014-02-19 23:44:52 +000074 llvm::DeleteContainerSeconds(Handlers);
Chris Lattner2e155302006-07-03 05:34:41 +000075}
76
77/// FindHandler - Check to see if there is already a handler for the
78/// specified name. If not, return the handler for the null identifier if it
79/// exists, otherwise return null. If IgnoreNull is true (the default) then
80/// the null handler isn't returned on failure to match.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000081PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
Chris Lattner2e155302006-07-03 05:34:41 +000082 bool IgnoreNull) const {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000083 if (PragmaHandler *Handler = Handlers.lookup(Name))
84 return Handler;
Craig Topperd2d442c2014-05-17 23:10:59 +000085 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000086}
Mike Stump11289f42009-09-09 15:08:12 +000087
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000088void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
89 assert(!Handlers.lookup(Handler->getName()) &&
90 "A handler with this name is already registered in this namespace");
David Blaikie13156b62014-11-19 03:06:06 +000091 Handlers[Handler->getName()] = Handler;
Chris Lattner2e155302006-07-03 05:34:41 +000092}
93
Daniel Dunbar40596532008-10-04 19:17:46 +000094void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000095 assert(Handlers.lookup(Handler->getName()) &&
96 "Handler not registered in this namespace");
97 Handlers.erase(Handler->getName());
Daniel Dunbar40596532008-10-04 19:17:46 +000098}
99
Fangrui Song6907ce22018-07-30 19:24:48 +0000100void PragmaNamespace::HandlePragma(Preprocessor &PP,
Douglas Gregorc7d65762010-09-09 22:45:38 +0000101 PragmaIntroducerKind Introducer,
102 Token &Tok) {
Chris Lattnerb8761832006-06-24 21:31:03 +0000103 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
104 // expand it, the user can have a STDC #define, that should not affect this.
105 PP.LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000106
Chris Lattnerb8761832006-06-24 21:31:03 +0000107 // Get the handler for this token. If there is no handler, ignore the pragma.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000108 PragmaHandler *Handler
109 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000110 : StringRef(),
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000111 /*IgnoreNull=*/false);
Craig Topperd2d442c2014-05-17 23:10:59 +0000112 if (!Handler) {
Chris Lattner21656f22009-04-19 21:10:26 +0000113 PP.Diag(Tok, diag::warn_pragma_ignored);
114 return;
115 }
Mike Stump11289f42009-09-09 15:08:12 +0000116
Chris Lattnerb8761832006-06-24 21:31:03 +0000117 // Otherwise, pass it down.
Douglas Gregorc7d65762010-09-09 22:45:38 +0000118 Handler->HandlePragma(PP, Introducer, Tok);
Chris Lattnerb8761832006-06-24 21:31:03 +0000119}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000120
Chris Lattnerb694ba72006-07-02 22:41:36 +0000121//===----------------------------------------------------------------------===//
122// Preprocessor Pragma Directive Handling.
123//===----------------------------------------------------------------------===//
124
James Dennett18a6d792012-06-17 03:26:26 +0000125/// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
Chris Lattnerb694ba72006-07-02 22:41:36 +0000126/// rest of the pragma, passing it to the registered pragma handlers.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000127void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
128 PragmaIntroducerKind Introducer) {
129 if (Callbacks)
130 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
131
Jordan Rosede1a2922012-06-08 18:06:21 +0000132 if (!PragmasEnabled)
133 return;
134
Chris Lattnerb694ba72006-07-02 22:41:36 +0000135 ++NumPragma;
Mike Stump11289f42009-09-09 15:08:12 +0000136
Chris Lattnerb694ba72006-07-02 22:41:36 +0000137 // Invoke the first level of pragma handlers which reads the namespace id.
Chris Lattner146762e2007-07-20 16:59:19 +0000138 Token Tok;
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000139 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000140
Chris Lattnerb694ba72006-07-02 22:41:36 +0000141 // If the pragma handler didn't read the rest of the line, consume it now.
Fangrui Song6907ce22018-07-30 19:24:48 +0000142 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000143 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000144 DiscardUntilEndOfDirective();
145}
146
147/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
148/// return the first token after the directive. The _Pragma token has just
149/// been read into 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +0000150void Preprocessor::Handle_Pragma(Token &Tok) {
Richard Smith75f96812019-04-11 21:18:22 +0000151 // C11 6.10.3.4/3:
152 // all pragma unary operator expressions within [a completely
153 // macro-replaced preprocessing token sequence] are [...] processed [after
154 // rescanning is complete]
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000155 //
Richard Smith75f96812019-04-11 21:18:22 +0000156 // This means that we execute _Pragma operators in two cases:
157 //
158 // 1) on token sequences that would otherwise be produced as the output of
159 // phase 4 of preprocessing, and
160 // 2) on token sequences formed as the macro-replaced token sequence of a
161 // macro argument
162 //
163 // Case #2 appears to be a wording bug: only _Pragmas that would survive to
164 // the end of phase 4 should actually be executed. Discussion on the WG14
165 // mailing list suggests that a _Pragma operator is notionally checked early,
166 // but only pragmas that survive to the end of phase 4 should be executed.
167 //
168 // In Case #2, we check the syntax now, but then put the tokens back into the
169 // token stream for later consumption.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000170
Richard Smith75f96812019-04-11 21:18:22 +0000171 struct TokenCollector {
172 Preprocessor &Self;
173 bool Collect;
174 SmallVector<Token, 3> Tokens;
175 Token &Tok;
176
177 void lex() {
178 if (Collect)
179 Tokens.push_back(Tok);
180 Self.Lex(Tok);
181 }
182
183 void revert() {
184 assert(Collect && "did not collect tokens");
185 assert(!Tokens.empty() && "collected unexpected number of tokens");
186
187 // Push the ( "string" ) tokens into the token stream.
188 auto Toks = llvm::make_unique<Token[]>(Tokens.size());
189 std::copy(Tokens.begin() + 1, Tokens.end(), Toks.get());
190 Toks[Tokens.size() - 1] = Tok;
191 Self.EnterTokenStream(std::move(Toks), Tokens.size(),
192 /*DisableMacroExpansion*/ true);
193
194 // ... and return the _Pragma token unchanged.
195 Tok = *Tokens.begin();
196 }
197 };
198
199 TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000200
Chris Lattnerb694ba72006-07-02 22:41:36 +0000201 // Remember the pragma token location.
202 SourceLocation PragmaLoc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000203
Chris Lattnerb694ba72006-07-02 22:41:36 +0000204 // Read the '('.
Richard Smith75f96812019-04-11 21:18:22 +0000205 Toks.lex();
Chris Lattner907dfe92008-11-18 07:59:24 +0000206 if (Tok.isNot(tok::l_paren)) {
207 Diag(PragmaLoc, diag::err__Pragma_malformed);
Richard Smith75f96812019-04-11 21:18:22 +0000208 return;
Chris Lattner907dfe92008-11-18 07:59:24 +0000209 }
Chris Lattnerb694ba72006-07-02 22:41:36 +0000210
211 // Read the '"..."'.
Richard Smith75f96812019-04-11 21:18:22 +0000212 Toks.lex();
Richard Smithc98bb4e2013-03-09 23:30:15 +0000213 if (!tok::isStringLiteral(Tok.getKind())) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000214 Diag(PragmaLoc, diag::err__Pragma_malformed);
Hubert Tong0deb6942015-07-30 21:30:00 +0000215 // Skip bad tokens, and the ')', if present.
Reid Kleckner53e6a5d2014-08-14 19:47:06 +0000216 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
Richard Smithd67aea22012-03-06 03:21:47 +0000217 Lex(Tok);
Hubert Tong0deb6942015-07-30 21:30:00 +0000218 while (Tok.isNot(tok::r_paren) &&
219 !Tok.isAtStartOfLine() &&
220 Tok.isNot(tok::eof))
221 Lex(Tok);
Richard Smithd67aea22012-03-06 03:21:47 +0000222 if (Tok.is(tok::r_paren))
223 Lex(Tok);
Richard Smith75f96812019-04-11 21:18:22 +0000224 return;
Richard Smithd67aea22012-03-06 03:21:47 +0000225 }
226
227 if (Tok.hasUDSuffix()) {
228 Diag(Tok, diag::err_invalid_string_udl);
229 // Skip this token, and the ')', if present.
230 Lex(Tok);
231 if (Tok.is(tok::r_paren))
232 Lex(Tok);
Richard Smith75f96812019-04-11 21:18:22 +0000233 return;
Chris Lattner907dfe92008-11-18 07:59:24 +0000234 }
Mike Stump11289f42009-09-09 15:08:12 +0000235
Chris Lattnerb694ba72006-07-02 22:41:36 +0000236 // Remember the string.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000237 Token StrTok = Tok;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000238
239 // Read the ')'.
Richard Smith75f96812019-04-11 21:18:22 +0000240 Toks.lex();
Chris Lattner907dfe92008-11-18 07:59:24 +0000241 if (Tok.isNot(tok::r_paren)) {
242 Diag(PragmaLoc, diag::err__Pragma_malformed);
Richard Smith75f96812019-04-11 21:18:22 +0000243 return;
Chris Lattner907dfe92008-11-18 07:59:24 +0000244 }
Mike Stump11289f42009-09-09 15:08:12 +0000245
Richard Smith75f96812019-04-11 21:18:22 +0000246 // If we're expanding a macro argument, put the tokens back.
247 if (InMacroArgPreExpansion) {
248 Toks.revert();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000249 return;
Richard Smith75f96812019-04-11 21:18:22 +0000250 }
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000251
Chris Lattner9dc9c202009-02-15 20:52:18 +0000252 SourceLocation RParenLoc = Tok.getLocation();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000253 std::string StrVal = getSpelling(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000254
Richard Smithc98bb4e2013-03-09 23:30:15 +0000255 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
256 // "The string literal is destringized by deleting any encoding prefix,
Chris Lattner262d4e32009-01-16 18:59:23 +0000257 // deleting the leading and trailing double-quotes, replacing each escape
258 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
259 // single backslash."
Richard Smithc98bb4e2013-03-09 23:30:15 +0000260 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
261 (StrVal[0] == 'u' && StrVal[1] != '8'))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000262 StrVal.erase(StrVal.begin());
Richard Smithc98bb4e2013-03-09 23:30:15 +0000263 else if (StrVal[0] == 'u')
264 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
265
266 if (StrVal[0] == 'R') {
267 // FIXME: C++11 does not specify how to handle raw-string-literals here.
268 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
269 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
270 "Invalid raw string token!");
271
272 // Measure the length of the d-char-sequence.
273 unsigned NumDChars = 0;
274 while (StrVal[2 + NumDChars] != '(') {
275 assert(NumDChars < (StrVal.size() - 5) / 2 &&
276 "Invalid raw string token!");
277 ++NumDChars;
278 }
279 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
280
281 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
282 // parens below.
283 StrVal.erase(0, 2 + NumDChars);
284 StrVal.erase(StrVal.size() - 1 - NumDChars);
285 } else {
286 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
287 "Invalid string token!");
288
289 // Remove escaped quotes and escapes.
Benjamin Kramerc2f5f292013-05-04 10:37:20 +0000290 unsigned ResultPos = 1;
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000291 for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
Reid Kleckner95e036c2013-09-25 16:42:48 +0000292 // Skip escapes. \\ -> '\' and \" -> '"'.
293 if (StrVal[i] == '\\' && i + 1 < e &&
294 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
295 ++i;
296 StrVal[ResultPos++] = StrVal[i];
Richard Smithc98bb4e2013-03-09 23:30:15 +0000297 }
Reid Kleckner95e036c2013-09-25 16:42:48 +0000298 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000299 }
Mike Stump11289f42009-09-09 15:08:12 +0000300
Chris Lattnerb694ba72006-07-02 22:41:36 +0000301 // Remove the front quote, replacing it with a space, so that the pragma
302 // contents appear to have a space before them.
303 StrVal[0] = ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000304
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000305 // Replace the terminating quote with a \n.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000306 StrVal[StrVal.size()-1] = '\n';
Mike Stump11289f42009-09-09 15:08:12 +0000307
Peter Collingbournef29ce972011-02-22 13:49:06 +0000308 // Plop the string (including the newline and trailing null) into a buffer
309 // where we can lex it.
310 Token TmpTok;
311 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000312 CreateString(StrVal, TmpTok);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000313 SourceLocation TokLoc = TmpTok.getLocation();
314
315 // Make and enter a lexer object so that we lex and expand the tokens just
316 // like any others.
317 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
318 StrVal.size(), *this);
319
Craig Topperd2d442c2014-05-17 23:10:59 +0000320 EnterSourceFileWithLexer(TL, nullptr);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000321
322 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000323 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
John McCall89e925d2010-08-28 22:34:47 +0000324
325 // Finally, return whatever came after the pragma directive.
326 return Lex(Tok);
327}
328
329/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
330/// is not enclosed within a string literal.
331void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
332 // Remember the pragma token location.
333 SourceLocation PragmaLoc = Tok.getLocation();
334
335 // Read the '('.
336 Lex(Tok);
337 if (Tok.isNot(tok::l_paren)) {
338 Diag(PragmaLoc, diag::err__Pragma_malformed);
339 return;
340 }
341
Peter Collingbournef29ce972011-02-22 13:49:06 +0000342 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000343 SmallVector<Token, 32> PragmaToks;
John McCall89e925d2010-08-28 22:34:47 +0000344 int NumParens = 0;
345 Lex(Tok);
346 while (Tok.isNot(tok::eof)) {
Peter Collingbournef29ce972011-02-22 13:49:06 +0000347 PragmaToks.push_back(Tok);
John McCall89e925d2010-08-28 22:34:47 +0000348 if (Tok.is(tok::l_paren))
349 NumParens++;
350 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
351 break;
John McCall89e925d2010-08-28 22:34:47 +0000352 Lex(Tok);
353 }
354
John McCall49039d42010-08-29 01:09:54 +0000355 if (Tok.is(tok::eof)) {
356 Diag(PragmaLoc, diag::err_unterminated___pragma);
357 return;
358 }
359
Peter Collingbournef29ce972011-02-22 13:49:06 +0000360 PragmaToks.front().setFlag(Token::LeadingSpace);
John McCall89e925d2010-08-28 22:34:47 +0000361
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000362 // Replace the ')' with an EOD to mark the end of the pragma.
363 PragmaToks.back().setKind(tok::eod);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000364
365 Token *TokArray = new Token[PragmaToks.size()];
366 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
367
368 // Push the tokens onto the stack.
369 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
370
371 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000372 HandlePragmaDirective(PragmaLoc, PIK___pragma);
John McCall89e925d2010-08-28 22:34:47 +0000373
374 // Finally, return whatever came after the pragma directive.
375 return Lex(Tok);
376}
377
James Dennett18a6d792012-06-17 03:26:26 +0000378/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
Chris Lattner146762e2007-07-20 16:59:19 +0000379void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
Sunil Srivastavafe583272016-07-25 17:17:06 +0000380 // Don't honor the 'once' when handling the primary source file, unless
Erik Verbruggene0bde752016-10-27 14:17:10 +0000381 // this is a prefix to a TU, which indicates we're generating a PCH file, or
382 // when the main file is a header (e.g. when -xc-header is provided on the
383 // commandline).
384 if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000385 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
386 return;
387 }
Mike Stump11289f42009-09-09 15:08:12 +0000388
Chris Lattnerb694ba72006-07-02 22:41:36 +0000389 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000390 // Mark the file as a once-only file now.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000391 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
Chris Lattnerb694ba72006-07-02 22:41:36 +0000392}
393
Chris Lattnerc2383312007-12-19 19:38:36 +0000394void Preprocessor::HandlePragmaMark() {
Ted Kremenek76c34412008-11-19 22:21:33 +0000395 assert(CurPPLexer && "No current lexer?");
Erich Keane0a6b5b62018-12-04 14:34:09 +0000396 CurLexer->ReadToEndOfLine();
Chris Lattnerc2383312007-12-19 19:38:36 +0000397}
398
James Dennett18a6d792012-06-17 03:26:26 +0000399/// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
Erik Verbruggen851ce0e2016-10-26 11:46:10 +0000400void Preprocessor::HandlePragmaPoison() {
Chris Lattner146762e2007-07-20 16:59:19 +0000401 Token Tok;
Chris Lattner538d7f32006-07-20 04:31:52 +0000402
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000403 while (true) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000404 // Read the next token to poison. While doing this, pretend that we are
405 // skipping while reading the identifier to poison.
406 // This avoids errors on code like:
407 // #pragma GCC poison X
408 // #pragma GCC poison X
Ted Kremenek551c82a2008-11-18 01:12:54 +0000409 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000410 LexUnexpandedToken(Tok);
Ted Kremenek551c82a2008-11-18 01:12:54 +0000411 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000412
Chris Lattnerb694ba72006-07-02 22:41:36 +0000413 // If we reached the end of line, we're done.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000414 if (Tok.is(tok::eod)) return;
Mike Stump11289f42009-09-09 15:08:12 +0000415
Chris Lattnerb694ba72006-07-02 22:41:36 +0000416 // Can only poison identifiers.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000417 if (Tok.isNot(tok::raw_identifier)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000418 Diag(Tok, diag::err_pp_invalid_poison);
419 return;
420 }
Mike Stump11289f42009-09-09 15:08:12 +0000421
Chris Lattnercefc7682006-07-08 08:28:12 +0000422 // Look up the identifier info for the token. We disabled identifier lookup
423 // by saying we're skipping contents, so we need to do this manually.
424 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000425
Chris Lattnerb694ba72006-07-02 22:41:36 +0000426 // Already poisoned.
427 if (II->isPoisoned()) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000428
Chris Lattnerb694ba72006-07-02 22:41:36 +0000429 // If this is a macro identifier, emit a warning.
Richard Smith20e883e2015-04-29 23:20:19 +0000430 if (isMacroDefined(II))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000431 Diag(Tok, diag::pp_poisoning_existing_macro);
Mike Stump11289f42009-09-09 15:08:12 +0000432
Chris Lattnerb694ba72006-07-02 22:41:36 +0000433 // Finally, poison it!
434 II->setIsPoisoned();
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000435 if (II->isFromAST())
436 II->setChangedSinceDeserialization();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000437 }
438}
439
James Dennett18a6d792012-06-17 03:26:26 +0000440/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
Chris Lattnerb694ba72006-07-02 22:41:36 +0000441/// that the whole directive has been parsed.
Chris Lattner146762e2007-07-20 16:59:19 +0000442void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000443 if (isInPrimaryFile()) {
444 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
445 return;
446 }
Mike Stump11289f42009-09-09 15:08:12 +0000447
Chris Lattnerb694ba72006-07-02 22:41:36 +0000448 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Ted Kremenek300590b2008-11-20 01:45:11 +0000449 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump11289f42009-09-09 15:08:12 +0000450
Chris Lattnerb694ba72006-07-02 22:41:36 +0000451 // Mark the file as a system header.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000452 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
Mike Stump11289f42009-09-09 15:08:12 +0000453
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000454 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000455 if (PLoc.isInvalid())
456 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000457
Jay Foad9a6b0982011-06-21 15:13:30 +0000458 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
Mike Stump11289f42009-09-09 15:08:12 +0000459
Chris Lattner3bdc7672011-05-22 22:10:16 +0000460 // Notify the client, if desired, that we are in a new source file.
461 if (Callbacks)
462 Callbacks->FileChanged(SysHeaderTok.getLocation(),
463 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
464
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000465 // Emit a line marker. This will change any source locations from this point
466 // forward to realize they are in a system header.
467 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +0000468 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
Jordan Rose111c4a62013-04-17 19:09:18 +0000469 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
Reid Klecknereb00ee02017-05-22 21:42:58 +0000470 SrcMgr::C_System);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000471}
472
James Dennett18a6d792012-06-17 03:26:26 +0000473/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
Chris Lattner146762e2007-07-20 16:59:19 +0000474void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
475 Token FilenameTok;
Richard Smithb9b05102019-03-19 01:51:19 +0000476 if (LexHeaderName(FilenameTok, /*AllowConcatenation*/false))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000477 return;
Mike Stump11289f42009-09-09 15:08:12 +0000478
Richard Smithb9b05102019-03-19 01:51:19 +0000479 // If the next token wasn't a header-name, diagnose the error.
Richard Smith91e150d2019-03-19 22:09:55 +0000480 if (FilenameTok.isNot(tok::header_name)) {
Richard Smithb9b05102019-03-19 01:51:19 +0000481 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
482 return;
483 }
484
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000485 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000486 SmallString<128> FilenameBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +0000487 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000488 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +0000489 if (Invalid)
490 return;
Mike Stump11289f42009-09-09 15:08:12 +0000491
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000492 bool isAngled =
493 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000494 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
495 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000496 if (Filename.empty())
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000497 return;
Mike Stump11289f42009-09-09 15:08:12 +0000498
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000499 // Search include directories for this file.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000500 const DirectoryLookup *CurDir;
Richard Smith25d50752014-10-20 00:15:49 +0000501 const FileEntry *File =
502 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000503 nullptr, CurDir, nullptr, nullptr, nullptr, nullptr, nullptr);
Craig Topperd2d442c2014-05-17 23:10:59 +0000504 if (!File) {
Eli Friedman3781a362011-08-30 23:07:51 +0000505 if (!SuppressIncludeNotFoundError)
506 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +0000507 return;
508 }
Mike Stump11289f42009-09-09 15:08:12 +0000509
Chris Lattnerd32480d2009-01-17 06:22:33 +0000510 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000511
512 // If this file is older than the file it depends on, emit a diagnostic.
513 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
514 // Lex tokens at the end of the message and include them in the message.
515 std::string Message;
516 Lex(DependencyTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000517 while (DependencyTok.isNot(tok::eod)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000518 Message += getSpelling(DependencyTok) + " ";
519 Lex(DependencyTok);
520 }
Mike Stump11289f42009-09-09 15:08:12 +0000521
Chris Lattnerf0b04972010-09-05 23:16:09 +0000522 // Remove the trailing ' ' if present.
523 if (!Message.empty())
524 Message.erase(Message.end()-1);
Chris Lattner97b8e842008-11-18 08:02:48 +0000525 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000526 }
527}
528
Reid Kleckner002562a2013-05-06 21:02:12 +0000529/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000530/// Return the IdentifierInfo* associated with the macro to push or pop.
531IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
532 // Remember the pragma token location.
533 Token PragmaTok = Tok;
534
535 // Read the '('.
536 Lex(Tok);
537 if (Tok.isNot(tok::l_paren)) {
538 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
539 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000540 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000541 }
542
543 // Read the macro name string.
544 Lex(Tok);
545 if (Tok.isNot(tok::string_literal)) {
546 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
547 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000548 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000549 }
550
Richard Smithd67aea22012-03-06 03:21:47 +0000551 if (Tok.hasUDSuffix()) {
552 Diag(Tok, diag::err_invalid_string_udl);
Craig Topperd2d442c2014-05-17 23:10:59 +0000553 return nullptr;
Richard Smithd67aea22012-03-06 03:21:47 +0000554 }
555
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000556 // Remember the macro string.
557 std::string StrVal = getSpelling(Tok);
558
559 // Read the ')'.
560 Lex(Tok);
561 if (Tok.isNot(tok::r_paren)) {
562 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
563 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000564 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000565 }
566
567 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
568 "Invalid string token!");
569
570 // Create a Token from the string.
571 Token MacroTok;
572 MacroTok.startToken();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000573 MacroTok.setKind(tok::raw_identifier);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000574 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000575
576 // Get the IdentifierInfo of MacroToPushTok.
577 return LookUpIdentifierInfo(MacroTok);
578}
579
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000580/// Handle \#pragma push_macro.
James Dennett18a6d792012-06-17 03:26:26 +0000581///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000582/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000583/// \code
Dmitri Gribenko9ebd1612012-11-30 20:04:39 +0000584/// #pragma push_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000585/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000586void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
587 // Parse the pragma directive and get the macro IdentifierInfo*.
588 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
589 if (!IdentInfo) return;
590
591 // Get the MacroInfo associated with IdentInfo.
592 MacroInfo *MI = getMacroInfo(IdentInfo);
Fangrui Song6907ce22018-07-30 19:24:48 +0000593
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000594 if (MI) {
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000595 // Allow the original MacroInfo to be redefined later.
596 MI->setIsAllowRedefinitionsWithoutWarning(true);
597 }
598
599 // Push the cloned MacroInfo so we can retrieve it later.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +0000600 PragmaPushMacroInfo[IdentInfo].push_back(MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000601}
602
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000603/// Handle \#pragma pop_macro.
James Dennett18a6d792012-06-17 03:26:26 +0000604///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000605/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000606/// \code
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000607/// #pragma pop_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000608/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000609void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
610 SourceLocation MessageLoc = PopMacroTok.getLocation();
611
612 // Parse the pragma directive and get the macro IdentifierInfo*.
613 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
614 if (!IdentInfo) return;
615
616 // Find the vector<MacroInfo*> associated with the macro.
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000617 llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter =
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000618 PragmaPushMacroInfo.find(IdentInfo);
619 if (iter != PragmaPushMacroInfo.end()) {
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000620 // Forget the MacroInfo currently associated with IdentInfo.
Richard Smith20e883e2015-04-29 23:20:19 +0000621 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000622 if (MI->isWarnIfUnused())
623 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
624 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000625 }
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000626
627 // Get the MacroInfo we want to reinstall.
628 MacroInfo *MacroToReInstall = iter->second.back();
629
Richard Smith713369b2015-04-23 20:40:50 +0000630 if (MacroToReInstall)
Alexander Kornienkoc0b49282012-08-29 16:56:24 +0000631 // Reinstall the previously pushed macro.
Richard Smith713369b2015-04-23 20:40:50 +0000632 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000633
634 // Pop PragmaPushMacroInfo stack.
635 iter->second.pop_back();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000636 if (iter->second.empty())
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000637 PragmaPushMacroInfo.erase(iter);
638 } else {
639 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
640 << IdentInfo->getName();
641 }
642}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000643
Aaron Ballman611306e2012-03-02 22:51:54 +0000644void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000645 // We will either get a quoted filename or a bracketed filename, and we
Aaron Ballman611306e2012-03-02 22:51:54 +0000646 // have to track which we got. The first filename is the source name,
647 // and the second name is the mapped filename. If the first is quoted,
648 // the second must be as well (cannot mix and match quotes and brackets).
Aaron Ballman611306e2012-03-02 22:51:54 +0000649
650 // Get the open paren
651 Lex(Tok);
652 if (Tok.isNot(tok::l_paren)) {
653 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
654 return;
655 }
656
657 // We expect either a quoted string literal, or a bracketed name
658 Token SourceFilenameTok;
Richard Smithb9b05102019-03-19 01:51:19 +0000659 if (LexHeaderName(SourceFilenameTok))
Aaron Ballman611306e2012-03-02 22:51:54 +0000660 return;
Aaron Ballman611306e2012-03-02 22:51:54 +0000661
662 StringRef SourceFileName;
663 SmallString<128> FileNameBuffer;
Richard Smith91e150d2019-03-19 22:09:55 +0000664 if (SourceFilenameTok.is(tok::header_name)) {
Aaron Ballman611306e2012-03-02 22:51:54 +0000665 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
Aaron Ballman611306e2012-03-02 22:51:54 +0000666 } else {
667 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
668 return;
669 }
670 FileNameBuffer.clear();
671
672 // Now we expect a comma, followed by another include name
673 Lex(Tok);
674 if (Tok.isNot(tok::comma)) {
675 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
676 return;
677 }
678
679 Token ReplaceFilenameTok;
Richard Smithb9b05102019-03-19 01:51:19 +0000680 if (LexHeaderName(ReplaceFilenameTok))
Aaron Ballman611306e2012-03-02 22:51:54 +0000681 return;
Aaron Ballman611306e2012-03-02 22:51:54 +0000682
683 StringRef ReplaceFileName;
Richard Smith91e150d2019-03-19 22:09:55 +0000684 if (ReplaceFilenameTok.is(tok::header_name)) {
Aaron Ballman611306e2012-03-02 22:51:54 +0000685 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
Aaron Ballman611306e2012-03-02 22:51:54 +0000686 } else {
687 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
688 return;
689 }
690
691 // Finally, we expect the closing paren
692 Lex(Tok);
693 if (Tok.isNot(tok::r_paren)) {
694 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
695 return;
696 }
697
698 // Now that we have the source and target filenames, we need to make sure
699 // they're both of the same type (angled vs non-angled)
700 StringRef OriginalSource = SourceFileName;
701
Fangrui Song6907ce22018-07-30 19:24:48 +0000702 bool SourceIsAngled =
703 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
Aaron Ballman611306e2012-03-02 22:51:54 +0000704 SourceFileName);
705 bool ReplaceIsAngled =
706 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
707 ReplaceFileName);
708 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
709 (SourceIsAngled != ReplaceIsAngled)) {
710 unsigned int DiagID;
711 if (SourceIsAngled)
712 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
713 else
714 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
715
716 Diag(SourceFilenameTok.getLocation(), DiagID)
Fangrui Song6907ce22018-07-30 19:24:48 +0000717 << SourceFileName
Aaron Ballman611306e2012-03-02 22:51:54 +0000718 << ReplaceFileName;
719
720 return;
721 }
722
723 // Now we can let the include handler know about this mapping
724 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
725}
726
Richard Smith9565c75b2017-06-19 23:09:36 +0000727// Lex a component of a module name: either an identifier or a string literal;
728// for components that can be expressed both ways, the two forms are equivalent.
729static bool LexModuleNameComponent(
730 Preprocessor &PP, Token &Tok,
731 std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent,
732 bool First) {
733 PP.LexUnexpandedToken(Tok);
734 if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
735 StringLiteralParser Literal(Tok, PP);
736 if (Literal.hadError)
737 return true;
738 ModuleNameComponent = std::make_pair(
739 PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation());
740 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
741 ModuleNameComponent =
742 std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
743 } else {
744 PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
745 return true;
746 }
747 return false;
748}
749
750static bool LexModuleName(
751 Preprocessor &PP, Token &Tok,
752 llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
753 &ModuleName) {
754 while (true) {
755 std::pair<IdentifierInfo*, SourceLocation> NameComponent;
756 if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
757 return true;
758 ModuleName.push_back(NameComponent);
759
760 PP.LexUnexpandedToken(Tok);
761 if (Tok.isNot(tok::period))
762 return false;
763 }
764}
765
Richard Smith5d2ed482017-06-09 19:22:32 +0000766void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
767 SourceLocation Loc = Tok.getLocation();
768
Richard Smith9565c75b2017-06-19 23:09:36 +0000769 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
770 if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
Richard Smith5d2ed482017-06-09 19:22:32 +0000771 return;
Richard Smith9565c75b2017-06-19 23:09:36 +0000772 IdentifierInfo *ModuleName = ModuleNameLoc.first;
Richard Smith5d2ed482017-06-09 19:22:32 +0000773
774 LexUnexpandedToken(Tok);
775 if (Tok.isNot(tok::eod)) {
776 Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
777 DiscardUntilEndOfDirective();
778 }
779
Richard Smith5d2ed482017-06-09 19:22:32 +0000780 CurLexer->LexingRawMode = true;
781
782 auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
783 if (Tok.getKind() != tok::raw_identifier ||
784 Tok.getRawIdentifier() != Ident)
785 return false;
786 CurLexer->Lex(Tok);
787 return true;
788 };
789
790 // Scan forward looking for the end of the module.
791 const char *Start = CurLexer->getBufferLocation();
792 const char *End = nullptr;
793 unsigned NestingLevel = 1;
794 while (true) {
795 End = CurLexer->getBufferLocation();
796 CurLexer->Lex(Tok);
797
798 if (Tok.is(tok::eof)) {
799 Diag(Loc, diag::err_pp_module_build_missing_end);
800 break;
801 }
802
803 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
804 // Token was part of module; keep going.
805 continue;
806 }
807
808 // We hit something directive-shaped; check to see if this is the end
809 // of the module build.
810 CurLexer->ParsingPreprocessorDirective = true;
811 CurLexer->Lex(Tok);
812 if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
813 TryConsumeIdentifier("module")) {
814 if (TryConsumeIdentifier("build"))
815 // #pragma clang module build -> entering a nested module build.
816 ++NestingLevel;
817 else if (TryConsumeIdentifier("endbuild")) {
818 // #pragma clang module endbuild -> leaving a module build.
819 if (--NestingLevel == 0)
820 break;
821 }
822 // We should either be looking at the EOD or more of the current directive
823 // preceding the EOD. Either way we can ignore this token and keep going.
824 assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
825 }
826 }
827
828 CurLexer->LexingRawMode = false;
829
830 // Load the extracted text as a preprocessed module.
831 assert(CurLexer->getBuffer().begin() <= Start &&
832 Start <= CurLexer->getBuffer().end() &&
833 CurLexer->getBuffer().begin() <= End &&
834 End <= CurLexer->getBuffer().end() &&
835 "module source range not contained within same file buffer");
836 TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(),
837 StringRef(Start, End - Start));
838}
839
Mike Rice58df1af2018-09-11 17:10:44 +0000840void Preprocessor::HandlePragmaHdrstop(Token &Tok) {
841 Lex(Tok);
842 if (Tok.is(tok::l_paren)) {
843 Diag(Tok.getLocation(), diag::warn_pp_hdrstop_filename_ignored);
844
845 std::string FileName;
846 if (!LexStringLiteral(Tok, FileName, "pragma hdrstop", false))
847 return;
848
849 if (Tok.isNot(tok::r_paren)) {
850 Diag(Tok, diag::err_expected) << tok::r_paren;
851 return;
852 }
853 Lex(Tok);
854 }
855 if (Tok.isNot(tok::eod))
856 Diag(Tok.getLocation(), diag::ext_pp_extra_tokens_at_eol)
857 << "pragma hdrstop";
858
859 if (creatingPCHWithPragmaHdrStop() &&
860 SourceMgr.isInMainFile(Tok.getLocation())) {
861 assert(CurLexer && "no lexer for #pragma hdrstop processing");
862 Token &Result = Tok;
863 Result.startToken();
864 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
865 CurLexer->cutOffLexing();
866 }
867 if (usingPCHWithPragmaHdrStop())
868 SkippingUntilPragmaHdrStop = false;
869}
870
Chris Lattnerb694ba72006-07-02 22:41:36 +0000871/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
872/// If 'Namespace' is non-null, then it is a token required to exist on the
873/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000874void Preprocessor::AddPragmaHandler(StringRef Namespace,
Chris Lattnerb694ba72006-07-02 22:41:36 +0000875 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000876 PragmaNamespace *InsertNS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000877
Chris Lattnerb694ba72006-07-02 22:41:36 +0000878 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000879 if (!Namespace.empty()) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000880 // If there is already a pragma handler with the name of this namespace,
881 // we either have an error (directive with the same name as a namespace) or
882 // we already have the namespace to insert into.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000883 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000884 InsertNS = Existing->getIfNamespace();
Craig Topperd2d442c2014-05-17 23:10:59 +0000885 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
Chris Lattnerb694ba72006-07-02 22:41:36 +0000886 " handler with the same name!");
887 } else {
888 // Otherwise, this namespace doesn't exist yet, create and insert the
889 // handler for it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000890 InsertNS = new PragmaNamespace(Namespace);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000891 PragmaHandlers->AddPragma(InsertNS);
892 }
893 }
Mike Stump11289f42009-09-09 15:08:12 +0000894
Chris Lattnerb694ba72006-07-02 22:41:36 +0000895 // Check to make sure we don't already have a pragma for this identifier.
896 assert(!InsertNS->FindHandler(Handler->getName()) &&
897 "Pragma handler already exists for this identifier!");
898 InsertNS->AddPragma(Handler);
899}
900
Daniel Dunbar40596532008-10-04 19:17:46 +0000901/// RemovePragmaHandler - Remove the specific pragma handler from the
902/// preprocessor. If \arg Namespace is non-null, then it should be the
903/// namespace that \arg Handler was added to. It is an error to remove
904/// a handler that has not been registered.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000905void Preprocessor::RemovePragmaHandler(StringRef Namespace,
Daniel Dunbar40596532008-10-04 19:17:46 +0000906 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000907 PragmaNamespace *NS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000908
Daniel Dunbar40596532008-10-04 19:17:46 +0000909 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000910 if (!Namespace.empty()) {
911 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
Daniel Dunbar40596532008-10-04 19:17:46 +0000912 assert(Existing && "Namespace containing handler does not exist!");
913
914 NS = Existing->getIfNamespace();
915 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
916 }
917
918 NS->RemovePragmaHandler(Handler);
Mike Stump11289f42009-09-09 15:08:12 +0000919
Craig Topperbe250302014-09-12 05:19:24 +0000920 // If this is a non-default namespace and it is now empty, remove it.
921 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
Daniel Dunbar40596532008-10-04 19:17:46 +0000922 PragmaHandlers->RemovePragmaHandler(NS);
Argyrios Kyrtzidis7ce75262012-01-06 00:22:09 +0000923 delete NS;
924 }
Daniel Dunbar40596532008-10-04 19:17:46 +0000925}
926
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000927bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
928 Token Tok;
929 LexUnexpandedToken(Tok);
930
931 if (Tok.isNot(tok::identifier)) {
932 Diag(Tok, diag::ext_on_off_switch_syntax);
933 return true;
934 }
935 IdentifierInfo *II = Tok.getIdentifierInfo();
936 if (II->isStr("ON"))
937 Result = tok::OOS_ON;
938 else if (II->isStr("OFF"))
939 Result = tok::OOS_OFF;
940 else if (II->isStr("DEFAULT"))
941 Result = tok::OOS_DEFAULT;
942 else {
943 Diag(Tok, diag::ext_on_off_switch_syntax);
944 return true;
945 }
946
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000947 // Verify that this is followed by EOD.
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000948 LexUnexpandedToken(Tok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000949 if (Tok.isNot(tok::eod))
950 Diag(Tok, diag::ext_pragma_syntax_eod);
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000951 return false;
952}
953
Chris Lattnerb694ba72006-07-02 22:41:36 +0000954namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000955
James Dennett18a6d792012-06-17 03:26:26 +0000956/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000957struct PragmaOnceHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000958 PragmaOnceHandler() : PragmaHandler("once") {}
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000959
Craig Topper9140dd22014-03-11 06:50:42 +0000960 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
961 Token &OnceTok) override {
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000962 PP.CheckEndOfDirective("pragma once");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000963 PP.HandlePragmaOnce(OnceTok);
964 }
965};
966
James Dennett18a6d792012-06-17 03:26:26 +0000967/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
Chris Lattnerc2383312007-12-19 19:38:36 +0000968/// rest of the line is not lexed.
969struct PragmaMarkHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000970 PragmaMarkHandler() : PragmaHandler("mark") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000971
Craig Topper9140dd22014-03-11 06:50:42 +0000972 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
973 Token &MarkTok) override {
Chris Lattnerc2383312007-12-19 19:38:36 +0000974 PP.HandlePragmaMark();
975 }
976};
977
James Dennett18a6d792012-06-17 03:26:26 +0000978/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000979struct PragmaPoisonHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000980 PragmaPoisonHandler() : PragmaHandler("poison") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000981
Craig Topper9140dd22014-03-11 06:50:42 +0000982 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
983 Token &PoisonTok) override {
Erik Verbruggen851ce0e2016-10-26 11:46:10 +0000984 PP.HandlePragmaPoison();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000985 }
986};
987
James Dennett18a6d792012-06-17 03:26:26 +0000988/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
Chris Lattnerc2383312007-12-19 19:38:36 +0000989/// as a system header, which silences warnings in it.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000990struct PragmaSystemHeaderHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000991 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000992
Craig Topper9140dd22014-03-11 06:50:42 +0000993 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
994 Token &SHToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000995 PP.HandlePragmaSystemHeader(SHToken);
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000996 PP.CheckEndOfDirective("pragma");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000997 }
998};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000999
Chris Lattnerb694ba72006-07-02 22:41:36 +00001000struct PragmaDependencyHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001001 PragmaDependencyHandler() : PragmaHandler("dependency") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001002
Craig Topper9140dd22014-03-11 06:50:42 +00001003 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1004 Token &DepToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +00001005 PP.HandlePragmaDependency(DepToken);
1006 }
1007};
Mike Stump11289f42009-09-09 15:08:12 +00001008
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001009struct PragmaDebugHandler : public PragmaHandler {
1010 PragmaDebugHandler() : PragmaHandler("__debug") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001011
Craig Topper9140dd22014-03-11 06:50:42 +00001012 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
Richard Smith77e53cbe2019-04-18 00:57:01 +00001013 Token &DebugToken) override {
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001014 Token Tok;
1015 PP.LexUnexpandedToken(Tok);
1016 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001017 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001018 return;
1019 }
1020 IdentifierInfo *II = Tok.getIdentifierInfo();
1021
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001022 if (II->isStr("assert")) {
David Blaikie83d382b2011-09-23 05:06:16 +00001023 llvm_unreachable("This is an assertion!");
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001024 } else if (II->isStr("crash")) {
David Blaikie5bd4c2a2012-08-21 18:56:49 +00001025 LLVM_BUILTIN_TRAP;
David Blaikie5d577a22012-06-29 22:03:56 +00001026 } else if (II->isStr("parser_crash")) {
1027 Token Crasher;
Benjamin Kramer3162f292015-03-08 19:28:24 +00001028 Crasher.startToken();
David Blaikie5d577a22012-06-29 22:03:56 +00001029 Crasher.setKind(tok::annot_pragma_parser_crash);
Benjamin Kramer3162f292015-03-08 19:28:24 +00001030 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
David Blaikie5d577a22012-06-29 22:03:56 +00001031 PP.EnterToken(Crasher);
Richard Smithba3a4f92016-01-12 21:59:26 +00001032 } else if (II->isStr("dump")) {
1033 Token Identifier;
1034 PP.LexUnexpandedToken(Identifier);
1035 if (auto *DumpII = Identifier.getIdentifierInfo()) {
1036 Token DumpAnnot;
1037 DumpAnnot.startToken();
1038 DumpAnnot.setKind(tok::annot_pragma_dump);
1039 DumpAnnot.setAnnotationRange(
1040 SourceRange(Tok.getLocation(), Identifier.getLocation()));
1041 DumpAnnot.setAnnotationValue(DumpII);
1042 PP.DiscardUntilEndOfDirective();
1043 PP.EnterToken(DumpAnnot);
1044 } else {
1045 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
1046 << II->getName();
1047 }
Richard Smith6c2b5a82018-02-09 01:15:13 +00001048 } else if (II->isStr("diag_mapping")) {
1049 Token DiagName;
1050 PP.LexUnexpandedToken(DiagName);
1051 if (DiagName.is(tok::eod))
1052 PP.getDiagnostics().dump();
1053 else if (DiagName.is(tok::string_literal) && !DiagName.hasUDSuffix()) {
1054 StringLiteralParser Literal(DiagName, PP);
1055 if (Literal.hadError)
1056 return;
1057 PP.getDiagnostics().dump(Literal.GetString());
1058 } else {
1059 PP.Diag(DiagName, diag::warn_pragma_debug_missing_argument)
1060 << II->getName();
1061 }
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001062 } else if (II->isStr("llvm_fatal_error")) {
1063 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1064 } else if (II->isStr("llvm_unreachable")) {
1065 llvm_unreachable("#pragma clang __debug llvm_unreachable");
Richard Smith3ffa61d2015-04-30 23:10:40 +00001066 } else if (II->isStr("macro")) {
1067 Token MacroName;
1068 PP.LexUnexpandedToken(MacroName);
1069 auto *MacroII = MacroName.getIdentifierInfo();
1070 if (MacroII)
1071 PP.dumpMacroInfo(MacroII);
1072 else
Richard Smithba3a4f92016-01-12 21:59:26 +00001073 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1074 << II->getName();
Richard Smith77e53cbe2019-04-18 00:57:01 +00001075 } else if (II->isStr("module_map")) {
1076 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1077 ModuleName;
1078 if (LexModuleName(PP, Tok, ModuleName))
1079 return;
1080 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
1081 Module *M = nullptr;
1082 for (auto IIAndLoc : ModuleName) {
1083 M = MM.lookupModuleQualified(IIAndLoc.first->getName(), M);
1084 if (!M) {
1085 PP.Diag(IIAndLoc.second, diag::warn_pragma_debug_unknown_module)
1086 << IIAndLoc.first;
1087 return;
1088 }
1089 }
1090 M->dump();
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001091 } else if (II->isStr("overflow_stack")) {
1092 DebugOverflowStack();
Daniel Dunbar211a7872010-08-18 23:09:23 +00001093 } else if (II->isStr("handle_crash")) {
1094 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
1095 if (CRC)
1096 CRC->HandleCrash();
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001097 } else if (II->isStr("captured")) {
1098 HandleCaptured(PP);
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001099 } else {
1100 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1101 << II->getName();
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001102 }
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001103
1104 PPCallbacks *Callbacks = PP.getPPCallbacks();
1105 if (Callbacks)
1106 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1107 }
1108
1109 void HandleCaptured(Preprocessor &PP) {
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001110 Token Tok;
1111 PP.LexUnexpandedToken(Tok);
1112
1113 if (Tok.isNot(tok::eod)) {
1114 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1115 << "pragma clang __debug captured";
1116 return;
1117 }
1118
1119 SourceLocation NameLoc = Tok.getLocation();
David Blaikie2eabcc92016-02-09 18:52:09 +00001120 MutableArrayRef<Token> Toks(
1121 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1122 Toks[0].startToken();
1123 Toks[0].setKind(tok::annot_pragma_captured);
1124 Toks[0].setLocation(NameLoc);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001125
David Blaikie2eabcc92016-02-09 18:52:09 +00001126 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001127 }
1128
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001129// Disable MSVC warning about runtime stack overflow.
1130#ifdef _MSC_VER
1131 #pragma warning(disable : 4717)
1132#endif
Matthias Braun285f88d2017-04-24 18:41:00 +00001133 static void DebugOverflowStack(void (*P)() = nullptr) {
1134 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1135 Self(reinterpret_cast<void(*)()>(Self));
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001136 }
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001137#ifdef _MSC_VER
1138 #pragma warning(default : 4717)
1139#endif
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001140};
1141
James Dennett18a6d792012-06-17 03:26:26 +00001142/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
Chris Lattner504af112009-04-19 23:16:58 +00001143struct PragmaDiagnosticHandler : public PragmaHandler {
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001144private:
1145 const char *Namespace;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001146
Chris Lattnerfb42a182009-07-12 21:18:45 +00001147public:
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001148 explicit PragmaDiagnosticHandler(const char *NS)
1149 : PragmaHandler("diagnostic"), Namespace(NS) {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001150
Craig Topper9140dd22014-03-11 06:50:42 +00001151 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1152 Token &DiagToken) override {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001153 SourceLocation DiagLoc = DiagToken.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001154 Token Tok;
1155 PP.LexUnexpandedToken(Tok);
1156 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001157 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001158 return;
1159 }
1160 IdentifierInfo *II = Tok.getIdentifierInfo();
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001161 PPCallbacks *Callbacks = PP.getPPCallbacks();
Mike Stump11289f42009-09-09 15:08:12 +00001162
Alp Toker46df1c02014-06-12 10:15:20 +00001163 if (II->isStr("pop")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001164 if (!PP.getDiagnostics().popMappings(DiagLoc))
Douglas Gregor3cc26482010-08-30 15:15:34 +00001165 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001166 else if (Callbacks)
1167 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
Douglas Gregor3cc26482010-08-30 15:15:34 +00001168 return;
1169 } else if (II->isStr("push")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001170 PP.getDiagnostics().pushMappings(DiagLoc);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001171 if (Callbacks)
1172 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
Chris Lattnerfb42a182009-07-12 21:18:45 +00001173 return;
Alp Toker46df1c02014-06-12 10:15:20 +00001174 }
1175
1176 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1177 .Case("ignored", diag::Severity::Ignored)
1178 .Case("warning", diag::Severity::Warning)
1179 .Case("error", diag::Severity::Error)
1180 .Case("fatal", diag::Severity::Fatal)
1181 .Default(diag::Severity());
1182
1183 if (SV == diag::Severity()) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001184 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001185 return;
1186 }
Mike Stump11289f42009-09-09 15:08:12 +00001187
Chris Lattner504af112009-04-19 23:16:58 +00001188 PP.LexUnexpandedToken(Tok);
Andy Gibbs58905d22012-11-17 19:15:38 +00001189 SourceLocation StringLoc = Tok.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001190
Andy Gibbs58905d22012-11-17 19:15:38 +00001191 std::string WarningName;
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001192 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1193 /*MacroExpansion=*/false))
Chris Lattner504af112009-04-19 23:16:58 +00001194 return;
Mike Stump11289f42009-09-09 15:08:12 +00001195
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001196 if (Tok.isNot(tok::eod)) {
Chris Lattner504af112009-04-19 23:16:58 +00001197 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1198 return;
1199 }
Mike Stump11289f42009-09-09 15:08:12 +00001200
Chris Lattner504af112009-04-19 23:16:58 +00001201 if (WarningName.size() < 3 || WarningName[0] != '-' ||
Richard Smith3be1cb22014-08-07 00:24:21 +00001202 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001203 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
Chris Lattner504af112009-04-19 23:16:58 +00001204 return;
1205 }
Mike Stump11289f42009-09-09 15:08:12 +00001206
Sunil Srivastava5239de72016-02-13 01:44:05 +00001207 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1208 : diag::Flavor::Remark;
Benjamin Kramer2193e232016-02-13 13:42:41 +00001209 StringRef Group = StringRef(WarningName).substr(2);
Sunil Srivastava5239de72016-02-13 01:44:05 +00001210 bool unknownDiag = false;
1211 if (Group == "everything") {
1212 // Special handling for pragma clang diagnostic ... "-Weverything".
1213 // There is no formal group named "everything", so there has to be a
1214 // special case for it.
1215 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1216 } else
1217 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1218 DiagLoc);
1219 if (unknownDiag)
Andy Gibbs58905d22012-11-17 19:15:38 +00001220 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1221 << WarningName;
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001222 else if (Callbacks)
Alp Toker46df1c02014-06-12 10:15:20 +00001223 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
Chris Lattner504af112009-04-19 23:16:58 +00001224 }
1225};
Mike Stump11289f42009-09-09 15:08:12 +00001226
Mike Rice58df1af2018-09-11 17:10:44 +00001227/// "\#pragma hdrstop [<header-name-string>]"
1228struct PragmaHdrstopHandler : public PragmaHandler {
1229 PragmaHdrstopHandler() : PragmaHandler("hdrstop") {}
1230 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1231 Token &DepToken) override {
1232 PP.HandlePragmaHdrstop(DepToken);
1233 }
1234};
1235
Reid Kleckner881dff32013-09-13 22:00:30 +00001236/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1237/// diagnostics, so we don't really implement this pragma. We parse it and
1238/// ignore it to avoid -Wunknown-pragma warnings.
1239struct PragmaWarningHandler : public PragmaHandler {
1240 PragmaWarningHandler() : PragmaHandler("warning") {}
1241
Craig Topper9140dd22014-03-11 06:50:42 +00001242 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1243 Token &Tok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001244 // Parse things like:
1245 // warning(push, 1)
1246 // warning(pop)
John Thompson4762b232013-11-16 00:16:03 +00001247 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
Reid Kleckner881dff32013-09-13 22:00:30 +00001248 SourceLocation DiagLoc = Tok.getLocation();
1249 PPCallbacks *Callbacks = PP.getPPCallbacks();
1250
1251 PP.Lex(Tok);
1252 if (Tok.isNot(tok::l_paren)) {
1253 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1254 return;
1255 }
1256
1257 PP.Lex(Tok);
1258 IdentifierInfo *II = Tok.getIdentifierInfo();
Reid Kleckner881dff32013-09-13 22:00:30 +00001259
Alexander Musman6b080fc2015-05-25 11:21:20 +00001260 if (II && II->isStr("push")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001261 // #pragma warning( push[ ,n ] )
Reid Kleckner4d185102013-10-02 15:19:23 +00001262 int Level = -1;
Reid Kleckner881dff32013-09-13 22:00:30 +00001263 PP.Lex(Tok);
1264 if (Tok.is(tok::comma)) {
1265 PP.Lex(Tok);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001266 uint64_t Value;
1267 if (Tok.is(tok::numeric_constant) &&
1268 PP.parseSimpleIntegerLiteral(Tok, Value))
1269 Level = int(Value);
Reid Kleckner4d185102013-10-02 15:19:23 +00001270 if (Level < 0 || Level > 4) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001271 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1272 return;
1273 }
1274 }
1275 if (Callbacks)
1276 Callbacks->PragmaWarningPush(DiagLoc, Level);
Alexander Musman6b080fc2015-05-25 11:21:20 +00001277 } else if (II && II->isStr("pop")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001278 // #pragma warning( pop )
1279 PP.Lex(Tok);
1280 if (Callbacks)
1281 Callbacks->PragmaWarningPop(DiagLoc);
1282 } else {
1283 // #pragma warning( warning-specifier : warning-number-list
1284 // [; warning-specifier : warning-number-list...] )
1285 while (true) {
1286 II = Tok.getIdentifierInfo();
Alexander Musman6b080fc2015-05-25 11:21:20 +00001287 if (!II && !Tok.is(tok::numeric_constant)) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001288 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1289 return;
1290 }
1291
1292 // Figure out which warning specifier this is.
Alexander Musman6b080fc2015-05-25 11:21:20 +00001293 bool SpecifierValid;
1294 StringRef Specifier;
1295 llvm::SmallString<1> SpecifierBuf;
1296 if (II) {
1297 Specifier = II->getName();
1298 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1299 .Cases("default", "disable", "error", "once",
1300 "suppress", true)
1301 .Default(false);
1302 // If we read a correct specifier, snatch next token (that should be
1303 // ":", checked later).
1304 if (SpecifierValid)
1305 PP.Lex(Tok);
1306 } else {
1307 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1308 uint64_t Value;
1309 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1310 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1311 SpecifierValid = (Value >= 1) && (Value <= 4);
1312 } else
1313 SpecifierValid = false;
1314 // Next token already snatched by parseSimpleIntegerLiteral.
1315 }
1316
Reid Kleckner881dff32013-09-13 22:00:30 +00001317 if (!SpecifierValid) {
1318 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1319 return;
1320 }
Reid Kleckner881dff32013-09-13 22:00:30 +00001321 if (Tok.isNot(tok::colon)) {
1322 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1323 return;
1324 }
1325
1326 // Collect the warning ids.
1327 SmallVector<int, 4> Ids;
1328 PP.Lex(Tok);
1329 while (Tok.is(tok::numeric_constant)) {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001330 uint64_t Value;
1331 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001332 Value > std::numeric_limits<int>::max()) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001333 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1334 return;
1335 }
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001336 Ids.push_back(int(Value));
Reid Kleckner881dff32013-09-13 22:00:30 +00001337 }
1338 if (Callbacks)
1339 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1340
1341 // Parse the next specifier if there is a semicolon.
1342 if (Tok.isNot(tok::semi))
1343 break;
1344 PP.Lex(Tok);
1345 }
1346 }
1347
1348 if (Tok.isNot(tok::r_paren)) {
1349 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1350 return;
1351 }
1352
1353 PP.Lex(Tok);
1354 if (Tok.isNot(tok::eod))
1355 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1356 }
1357};
1358
Reid Kleckner0f56b222019-03-14 18:12:17 +00001359/// "\#pragma execution_character_set(...)". MSVC supports this pragma only
1360/// for "UTF-8". We parse it and ignore it if UTF-8 is provided and warn
1361/// otherwise to avoid -Wunknown-pragma warnings.
1362struct PragmaExecCharsetHandler : public PragmaHandler {
1363 PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {}
1364
1365 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1366 Token &Tok) override {
1367 // Parse things like:
1368 // execution_character_set(push, "UTF-8")
1369 // execution_character_set(pop)
1370 SourceLocation DiagLoc = Tok.getLocation();
1371 PPCallbacks *Callbacks = PP.getPPCallbacks();
1372
1373 PP.Lex(Tok);
1374 if (Tok.isNot(tok::l_paren)) {
1375 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << "(";
1376 return;
1377 }
1378
1379 PP.Lex(Tok);
1380 IdentifierInfo *II = Tok.getIdentifierInfo();
1381
1382 if (II && II->isStr("push")) {
1383 // #pragma execution_character_set( push[ , string ] )
1384 PP.Lex(Tok);
1385 if (Tok.is(tok::comma)) {
1386 PP.Lex(Tok);
1387
1388 std::string ExecCharset;
1389 if (!PP.FinishLexStringLiteral(Tok, ExecCharset,
1390 "pragma execution_character_set",
1391 /*MacroExpansion=*/false))
1392 return;
1393
1394 // MSVC supports either of these, but nothing else.
1395 if (ExecCharset != "UTF-8" && ExecCharset != "utf-8") {
1396 PP.Diag(Tok, diag::warn_pragma_exec_charset_push_invalid) << ExecCharset;
1397 return;
1398 }
1399 }
1400 if (Callbacks)
1401 Callbacks->PragmaExecCharsetPush(DiagLoc, "UTF-8");
1402 } else if (II && II->isStr("pop")) {
1403 // #pragma execution_character_set( pop )
1404 PP.Lex(Tok);
1405 if (Callbacks)
1406 Callbacks->PragmaExecCharsetPop(DiagLoc);
1407 } else {
1408 PP.Diag(Tok, diag::warn_pragma_exec_charset_spec_invalid);
1409 return;
1410 }
1411
1412 if (Tok.isNot(tok::r_paren)) {
1413 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << ")";
1414 return;
1415 }
1416
1417 PP.Lex(Tok);
1418 if (Tok.isNot(tok::eod))
1419 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma execution_character_set";
1420 }
1421};
1422
James Dennett18a6d792012-06-17 03:26:26 +00001423/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
Aaron Ballman611306e2012-03-02 22:51:54 +00001424struct PragmaIncludeAliasHandler : public PragmaHandler {
1425 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001426
Craig Topper9140dd22014-03-11 06:50:42 +00001427 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1428 Token &IncludeAliasTok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001429 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
Aaron Ballman611306e2012-03-02 22:51:54 +00001430 }
1431};
1432
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001433/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1434/// extension. The syntax is:
1435/// \code
1436/// #pragma message(string)
1437/// \endcode
1438/// OR, in GCC mode:
1439/// \code
1440/// #pragma message string
1441/// \endcode
1442/// string is a string, which is fully macro expanded, and permits string
1443/// concatenation, embedded escape characters, etc... See MSDN for more details.
1444/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1445/// form as \#pragma message.
Chris Lattner30c924b2010-06-26 17:11:39 +00001446struct PragmaMessageHandler : public PragmaHandler {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001447private:
1448 const PPCallbacks::PragmaMessageKind Kind;
1449 const StringRef Namespace;
1450
1451 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1452 bool PragmaNameOnly = false) {
1453 switch (Kind) {
1454 case PPCallbacks::PMK_Message:
1455 return PragmaNameOnly ? "message" : "pragma message";
1456 case PPCallbacks::PMK_Warning:
1457 return PragmaNameOnly ? "warning" : "pragma warning";
1458 case PPCallbacks::PMK_Error:
1459 return PragmaNameOnly ? "error" : "pragma error";
1460 }
1461 llvm_unreachable("Unknown PragmaMessageKind!");
1462 }
1463
1464public:
1465 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1466 StringRef Namespace = StringRef())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001467 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
1468 Namespace(Namespace) {}
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001469
Craig Topper9140dd22014-03-11 06:50:42 +00001470 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1471 Token &Tok) override {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001472 SourceLocation MessageLoc = Tok.getLocation();
1473 PP.Lex(Tok);
1474 bool ExpectClosingParen = false;
1475 switch (Tok.getKind()) {
1476 case tok::l_paren:
1477 // We have a MSVC style pragma message.
1478 ExpectClosingParen = true;
1479 // Read the string.
1480 PP.Lex(Tok);
1481 break;
1482 case tok::string_literal:
1483 // We have a GCC style pragma message, and we just read the string.
1484 break;
1485 default:
1486 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1487 return;
1488 }
1489
1490 std::string MessageString;
1491 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1492 /*MacroExpansion=*/true))
1493 return;
1494
1495 if (ExpectClosingParen) {
1496 if (Tok.isNot(tok::r_paren)) {
1497 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1498 return;
1499 }
1500 PP.Lex(Tok); // eat the r_paren.
1501 }
1502
1503 if (Tok.isNot(tok::eod)) {
1504 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1505 return;
1506 }
1507
1508 // Output the message.
1509 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1510 ? diag::err_pragma_message
1511 : diag::warn_pragma_message) << MessageString;
1512
1513 // If the pragma is lexically sound, notify any interested PPCallbacks.
1514 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1515 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
Chris Lattner30c924b2010-06-26 17:11:39 +00001516 }
1517};
1518
Richard Smithc51c38b2017-04-29 00:34:47 +00001519/// Handle the clang \#pragma module import extension. The syntax is:
1520/// \code
1521/// #pragma clang module import some.module.name
1522/// \endcode
1523struct PragmaModuleImportHandler : public PragmaHandler {
1524 PragmaModuleImportHandler() : PragmaHandler("import") {}
1525
1526 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
Richard Smithd1386302017-05-04 00:29:54 +00001527 Token &Tok) override {
1528 SourceLocation ImportLoc = Tok.getLocation();
1529
1530 // Read the module name.
1531 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1532 ModuleName;
1533 if (LexModuleName(PP, Tok, ModuleName))
1534 return;
1535
1536 if (Tok.isNot(tok::eod))
1537 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1538
1539 // If we have a non-empty module path, load the named module.
1540 Module *Imported =
1541 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1542 /*IsIncludeDirective=*/false);
1543 if (!Imported)
1544 return;
1545
1546 PP.makeModuleVisible(Imported, ImportLoc);
1547 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1548 tok::annot_module_include, Imported);
1549 if (auto *CB = PP.getPPCallbacks())
1550 CB->moduleImport(ImportLoc, ModuleName, Imported);
1551 }
1552};
1553
1554/// Handle the clang \#pragma module begin extension. The syntax is:
1555/// \code
1556/// #pragma clang module begin some.module.name
1557/// ...
1558/// #pragma clang module end
1559/// \endcode
1560struct PragmaModuleBeginHandler : public PragmaHandler {
1561 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1562
1563 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1564 Token &Tok) override {
1565 SourceLocation BeginLoc = Tok.getLocation();
1566
1567 // Read the module name.
1568 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1569 ModuleName;
1570 if (LexModuleName(PP, Tok, ModuleName))
1571 return;
1572
1573 if (Tok.isNot(tok::eod))
1574 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1575
1576 // We can only enter submodules of the current module.
1577 StringRef Current = PP.getLangOpts().CurrentModule;
1578 if (ModuleName.front().first->getName() != Current) {
1579 PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1580 << ModuleName.front().first << (ModuleName.size() > 1)
1581 << Current.empty() << Current;
1582 return;
1583 }
1584
1585 // Find the module we're entering. We require that a module map for it
1586 // be loaded or implicitly loadable.
David Blaikie89e58dd2019-05-07 21:38:51 +00001587 auto &HSI = PP.getHeaderSearchInfo();
1588 Module *M = HSI.lookupModule(Current);
Richard Smithd1386302017-05-04 00:29:54 +00001589 if (!M) {
1590 PP.Diag(ModuleName.front().second,
1591 diag::err_pp_module_begin_no_module_map) << Current;
1592 return;
1593 }
1594 for (unsigned I = 1; I != ModuleName.size(); ++I) {
David Blaikie89e58dd2019-05-07 21:38:51 +00001595 auto *NewM = M->findOrInferSubmodule(ModuleName[I].first->getName());
Richard Smithd1386302017-05-04 00:29:54 +00001596 if (!NewM) {
1597 PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1598 << M->getFullModuleName() << ModuleName[I].first;
1599 return;
1600 }
1601 M = NewM;
1602 }
1603
Richard Smith51d09c52017-05-30 05:22:59 +00001604 // If the module isn't available, it doesn't make sense to enter it.
Richard Smith27e5aa02017-06-05 18:57:56 +00001605 if (Preprocessor::checkModuleIsAvailable(
1606 PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
Richard Smith51d09c52017-05-30 05:22:59 +00001607 PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1608 << M->getTopLevelModuleName();
1609 return;
1610 }
1611
Richard Smithd1386302017-05-04 00:29:54 +00001612 // Enter the scope of the submodule.
1613 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1614 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1615 tok::annot_module_begin, M);
1616 }
1617};
1618
1619/// Handle the clang \#pragma module end extension.
1620struct PragmaModuleEndHandler : public PragmaHandler {
1621 PragmaModuleEndHandler() : PragmaHandler("end") {}
1622
1623 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1624 Token &Tok) override {
1625 SourceLocation Loc = Tok.getLocation();
1626
1627 PP.LexUnexpandedToken(Tok);
1628 if (Tok.isNot(tok::eod))
1629 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1630
1631 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1632 if (M)
1633 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1634 else
1635 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
Richard Smithc51c38b2017-04-29 00:34:47 +00001636 }
1637};
1638
Richard Smith5d2ed482017-06-09 19:22:32 +00001639/// Handle the clang \#pragma module build extension.
1640struct PragmaModuleBuildHandler : public PragmaHandler {
1641 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1642
1643 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1644 Token &Tok) override {
1645 PP.HandlePragmaModuleBuild(Tok);
1646 }
1647};
1648
1649/// Handle the clang \#pragma module load extension.
1650struct PragmaModuleLoadHandler : public PragmaHandler {
1651 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1652
1653 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1654 Token &Tok) override {
1655 SourceLocation Loc = Tok.getLocation();
1656
1657 // Read the module name.
1658 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1659 ModuleName;
1660 if (LexModuleName(PP, Tok, ModuleName))
1661 return;
1662
1663 if (Tok.isNot(tok::eod))
1664 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1665
1666 // Load the module, don't make it visible.
1667 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1668 /*IsIncludeDirective=*/false);
1669 }
1670};
1671
James Dennett18a6d792012-06-17 03:26:26 +00001672/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001673/// macro on the top of the stack.
1674struct PragmaPushMacroHandler : public PragmaHandler {
1675 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001676
Craig Topper9140dd22014-03-11 06:50:42 +00001677 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1678 Token &PushMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001679 PP.HandlePragmaPushMacro(PushMacroTok);
1680 }
1681};
1682
James Dennett18a6d792012-06-17 03:26:26 +00001683/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001684/// macro to the value on the top of the stack.
1685struct PragmaPopMacroHandler : public PragmaHandler {
1686 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001687
Craig Topper9140dd22014-03-11 06:50:42 +00001688 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1689 Token &PopMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001690 PP.HandlePragmaPopMacro(PopMacroTok);
1691 }
1692};
1693
Fangrui Song6907ce22018-07-30 19:24:48 +00001694/// PragmaARCCFCodeAuditedHandler -
James Dennett18a6d792012-06-17 03:26:26 +00001695/// \#pragma clang arc_cf_code_audited begin/end
John McCall32f5fe12011-09-30 05:12:12 +00001696struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1697 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001698
Craig Topper9140dd22014-03-11 06:50:42 +00001699 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1700 Token &NameTok) override {
John McCall32f5fe12011-09-30 05:12:12 +00001701 SourceLocation Loc = NameTok.getLocation();
1702 bool IsBegin;
1703
1704 Token Tok;
1705
1706 // Lex the 'begin' or 'end'.
1707 PP.LexUnexpandedToken(Tok);
1708 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1709 if (BeginEnd && BeginEnd->isStr("begin")) {
1710 IsBegin = true;
1711 } else if (BeginEnd && BeginEnd->isStr("end")) {
1712 IsBegin = false;
1713 } else {
1714 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1715 return;
1716 }
1717
1718 // Verify that this is followed by EOD.
1719 PP.LexUnexpandedToken(Tok);
1720 if (Tok.isNot(tok::eod))
1721 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1722
1723 // The start location of the active audit.
1724 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1725
1726 // The start location we want after processing this.
1727 SourceLocation NewLoc;
1728
1729 if (IsBegin) {
1730 // Complain about attempts to re-enter an audit.
1731 if (BeginLoc.isValid()) {
1732 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1733 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1734 }
1735 NewLoc = Loc;
1736 } else {
1737 // Complain about attempts to leave an audit that doesn't exist.
1738 if (!BeginLoc.isValid()) {
1739 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1740 return;
1741 }
1742 NewLoc = SourceLocation();
1743 }
1744
1745 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1746 }
1747};
1748
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001749/// PragmaAssumeNonNullHandler -
1750/// \#pragma clang assume_nonnull begin/end
1751struct PragmaAssumeNonNullHandler : public PragmaHandler {
1752 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001753
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001754 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1755 Token &NameTok) override {
1756 SourceLocation Loc = NameTok.getLocation();
1757 bool IsBegin;
1758
1759 Token Tok;
1760
1761 // Lex the 'begin' or 'end'.
1762 PP.LexUnexpandedToken(Tok);
1763 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1764 if (BeginEnd && BeginEnd->isStr("begin")) {
1765 IsBegin = true;
1766 } else if (BeginEnd && BeginEnd->isStr("end")) {
1767 IsBegin = false;
1768 } else {
1769 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1770 return;
1771 }
1772
1773 // Verify that this is followed by EOD.
1774 PP.LexUnexpandedToken(Tok);
1775 if (Tok.isNot(tok::eod))
1776 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1777
1778 // The start location of the active audit.
1779 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1780
1781 // The start location we want after processing this.
1782 SourceLocation NewLoc;
Eli Friedman16fee082017-09-27 23:29:37 +00001783 PPCallbacks *Callbacks = PP.getPPCallbacks();
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001784
1785 if (IsBegin) {
1786 // Complain about attempts to re-enter an audit.
1787 if (BeginLoc.isValid()) {
1788 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1789 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1790 }
1791 NewLoc = Loc;
Eli Friedman16fee082017-09-27 23:29:37 +00001792 if (Callbacks)
1793 Callbacks->PragmaAssumeNonNullBegin(NewLoc);
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001794 } else {
1795 // Complain about attempts to leave an audit that doesn't exist.
1796 if (!BeginLoc.isValid()) {
1797 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1798 return;
1799 }
1800 NewLoc = SourceLocation();
Eli Friedman16fee082017-09-27 23:29:37 +00001801 if (Callbacks)
1802 Callbacks->PragmaAssumeNonNullEnd(NewLoc);
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001803 }
1804
1805 PP.setPragmaAssumeNonNullLoc(NewLoc);
1806 }
1807};
1808
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001809/// Handle "\#pragma region [...]"
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001810///
1811/// The syntax is
1812/// \code
1813/// #pragma region [optional name]
1814/// #pragma endregion [optional comment]
1815/// \endcode
1816///
1817/// \note This is
1818/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1819/// pragma, just skipped by compiler.
1820struct PragmaRegionHandler : public PragmaHandler {
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001821 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
Aaron Ballman406ea512012-11-30 19:52:30 +00001822
Craig Topper9140dd22014-03-11 06:50:42 +00001823 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1824 Token &NameTok) override {
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001825 // #pragma region: endregion matches can be verified
1826 // __pragma(region): no sense, but ignored by msvc
1827 // _Pragma is not valid for MSVC, but there isn't any point
1828 // to handle a _Pragma differently.
1829 }
1830};
Aaron Ballman406ea512012-11-30 19:52:30 +00001831
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001832} // namespace
Chris Lattnerb694ba72006-07-02 22:41:36 +00001833
1834/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
James Dennett18a6d792012-06-17 03:26:26 +00001835/// \#pragma GCC poison/system_header/dependency and \#pragma once.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001836void Preprocessor::RegisterBuiltinPragmas() {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001837 AddPragmaHandler(new PragmaOnceHandler());
1838 AddPragmaHandler(new PragmaMarkHandler());
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001839 AddPragmaHandler(new PragmaPushMacroHandler());
1840 AddPragmaHandler(new PragmaPopMacroHandler());
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001841 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
Mike Stump11289f42009-09-09 15:08:12 +00001842
Chris Lattnerb61448d2009-05-12 18:21:11 +00001843 // #pragma GCC ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001844 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1845 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1846 AddPragmaHandler("GCC", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001847 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001848 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1849 "GCC"));
1850 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1851 "GCC"));
Chris Lattnerb61448d2009-05-12 18:21:11 +00001852 // #pragma clang ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001853 AddPragmaHandler("clang", new PragmaPoisonHandler());
1854 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001855 AddPragmaHandler("clang", new PragmaDebugHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001856 AddPragmaHandler("clang", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001857 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
John McCall32f5fe12011-09-30 05:12:12 +00001858 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001859 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
Chris Lattnerb61448d2009-05-12 18:21:11 +00001860
Richard Smithc51c38b2017-04-29 00:34:47 +00001861 // #pragma clang module ...
1862 auto *ModuleHandler = new PragmaNamespace("module");
1863 AddPragmaHandler("clang", ModuleHandler);
1864 ModuleHandler->AddPragma(new PragmaModuleImportHandler());
Richard Smithd1386302017-05-04 00:29:54 +00001865 ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
1866 ModuleHandler->AddPragma(new PragmaModuleEndHandler());
Richard Smith5d2ed482017-06-09 19:22:32 +00001867 ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
1868 ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
Fangrui Song6907ce22018-07-30 19:24:48 +00001869
Matt Davis1edb9052018-01-27 00:25:29 +00001870 // Add region pragmas.
1871 AddPragmaHandler(new PragmaRegionHandler("region"));
1872 AddPragmaHandler(new PragmaRegionHandler("endregion"));
Richard Smithc51c38b2017-04-29 00:34:47 +00001873
Chris Lattner2ff698d2009-01-16 08:21:25 +00001874 // MS extensions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001875 if (LangOpts.MicrosoftExt) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001876 AddPragmaHandler(new PragmaWarningHandler());
Reid Kleckner0f56b222019-03-14 18:12:17 +00001877 AddPragmaHandler(new PragmaExecCharsetHandler());
Aaron Ballman611306e2012-03-02 22:51:54 +00001878 AddPragmaHandler(new PragmaIncludeAliasHandler());
Mike Rice58df1af2018-09-11 17:10:44 +00001879 AddPragmaHandler(new PragmaHdrstopHandler());
Chris Lattner30c924b2010-06-26 17:11:39 +00001880 }
John Brawn8e62db32016-04-04 14:22:58 +00001881
1882 // Pragmas added by plugins
1883 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1884 ie = PragmaHandlerRegistry::end();
1885 it != ie; ++it) {
1886 AddPragmaHandler(it->instantiate().release());
1887 }
Chris Lattnerb694ba72006-07-02 22:41:36 +00001888}
Lubos Lunak576a0412014-05-01 12:54:03 +00001889
1890/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1891/// warn about those pragmas being unknown.
1892void Preprocessor::IgnorePragmas() {
1893 AddPragmaHandler(new EmptyPragmaHandler());
1894 // Also ignore all pragmas in all namespaces created
1895 // in Preprocessor::RegisterBuiltinPragmas().
1896 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1897 AddPragmaHandler("clang", new EmptyPragmaHandler());
Lubos Lunak576a0412014-05-01 12:54:03 +00001898}