blob: b9be03f4f20d98d9d9fa5d8bd4efb05964987ccc [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//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb8761832006-06-24 21:31:03 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerb694ba72006-07-02 22:41:36 +000010// This file implements the PragmaHandler/PragmaTable interfaces and implements
11// pragma related methods of the Preprocessor class.
Chris Lattnerb8761832006-06-24 21:31:03 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Pragma.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000016#include "clang/Basic/Diagnostic.h"
Chris Lattnerb694ba72006-07-02 22:41:36 +000017#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000018#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000019#include "clang/Basic/LLVM.h"
20#include "clang/Basic/LangOptions.h"
21#include "clang/Basic/Module.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000022#include "clang/Basic/SourceLocation.h"
Chris Lattnerb694ba72006-07-02 22:41:36 +000023#include "clang/Basic/SourceManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000024#include "clang/Basic/TokenKinds.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Lex/HeaderSearch.h"
26#include "clang/Lex/LexDiagnostic.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000027#include "clang/Lex/Lexer.h"
Richard Smith9565c75b2017-06-19 23:09:36 +000028#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Lex/MacroInfo.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000030#include "clang/Lex/ModuleLoader.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000031#include "clang/Lex/PPCallbacks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Lex/Preprocessor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000033#include "clang/Lex/PreprocessorLexer.h"
34#include "clang/Lex/PTHLexer.h"
35#include "clang/Lex/Token.h"
36#include "clang/Lex/TokenLexer.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/DenseMap.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000039#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000040#include "llvm/ADT/SmallString.h"
41#include "llvm/ADT/SmallVector.h"
Reid Kleckner881dff32013-09-13 22:00:30 +000042#include "llvm/ADT/StringSwitch.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000043#include "llvm/ADT/StringRef.h"
Daniel Dunbar211a7872010-08-18 23:09:23 +000044#include "llvm/Support/CrashRecoveryContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000045#include "llvm/Support/Compiler.h"
Daniel Dunbarf2cf3292010-08-17 22:32:48 +000046#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000047#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000048#include <cassert>
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000049#include <cstddef>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000050#include <cstdint>
51#include <limits>
52#include <string>
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000053#include <utility>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000054#include <vector>
55
Chris Lattnerb8761832006-06-24 21:31:03 +000056using namespace clang;
57
58// Out-of-line destructor to provide a home for the class.
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000059PragmaHandler::~PragmaHandler() = default;
Chris Lattnerb8761832006-06-24 21:31:03 +000060
Chris Lattner2e155302006-07-03 05:34:41 +000061//===----------------------------------------------------------------------===//
Daniel Dunbard839e772010-06-11 20:10:12 +000062// EmptyPragmaHandler Implementation.
63//===----------------------------------------------------------------------===//
64
Hans Wennborg7357bbc2015-10-12 20:47:58 +000065EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000066
Douglas Gregorc7d65762010-09-09 22:45:38 +000067void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
68 PragmaIntroducerKind Introducer,
69 Token &FirstToken) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000070
71//===----------------------------------------------------------------------===//
Chris Lattner2e155302006-07-03 05:34:41 +000072// PragmaNamespace Implementation.
73//===----------------------------------------------------------------------===//
74
Chris Lattner2e155302006-07-03 05:34:41 +000075PragmaNamespace::~PragmaNamespace() {
Reid Kleckner588c9372014-02-19 23:44:52 +000076 llvm::DeleteContainerSeconds(Handlers);
Chris Lattner2e155302006-07-03 05:34:41 +000077}
78
79/// FindHandler - Check to see if there is already a handler for the
80/// specified name. If not, return the handler for the null identifier if it
81/// exists, otherwise return null. If IgnoreNull is true (the default) then
82/// the null handler isn't returned on failure to match.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000083PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
Chris Lattner2e155302006-07-03 05:34:41 +000084 bool IgnoreNull) const {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000085 if (PragmaHandler *Handler = Handlers.lookup(Name))
86 return Handler;
Craig Topperd2d442c2014-05-17 23:10:59 +000087 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000088}
Mike Stump11289f42009-09-09 15:08:12 +000089
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000090void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
91 assert(!Handlers.lookup(Handler->getName()) &&
92 "A handler with this name is already registered in this namespace");
David Blaikie13156b62014-11-19 03:06:06 +000093 Handlers[Handler->getName()] = Handler;
Chris Lattner2e155302006-07-03 05:34:41 +000094}
95
Daniel Dunbar40596532008-10-04 19:17:46 +000096void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000097 assert(Handlers.lookup(Handler->getName()) &&
98 "Handler not registered in this namespace");
99 Handlers.erase(Handler->getName());
Daniel Dunbar40596532008-10-04 19:17:46 +0000100}
101
Douglas Gregorc7d65762010-09-09 22:45:38 +0000102void PragmaNamespace::HandlePragma(Preprocessor &PP,
103 PragmaIntroducerKind Introducer,
104 Token &Tok) {
Chris Lattnerb8761832006-06-24 21:31:03 +0000105 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
106 // expand it, the user can have a STDC #define, that should not affect this.
107 PP.LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000108
Chris Lattnerb8761832006-06-24 21:31:03 +0000109 // Get the handler for this token. If there is no handler, ignore the pragma.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000110 PragmaHandler *Handler
111 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000112 : StringRef(),
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000113 /*IgnoreNull=*/false);
Craig Topperd2d442c2014-05-17 23:10:59 +0000114 if (!Handler) {
Chris Lattner21656f22009-04-19 21:10:26 +0000115 PP.Diag(Tok, diag::warn_pragma_ignored);
116 return;
117 }
Mike Stump11289f42009-09-09 15:08:12 +0000118
Chris Lattnerb8761832006-06-24 21:31:03 +0000119 // Otherwise, pass it down.
Douglas Gregorc7d65762010-09-09 22:45:38 +0000120 Handler->HandlePragma(PP, Introducer, Tok);
Chris Lattnerb8761832006-06-24 21:31:03 +0000121}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000122
Chris Lattnerb694ba72006-07-02 22:41:36 +0000123//===----------------------------------------------------------------------===//
124// Preprocessor Pragma Directive Handling.
125//===----------------------------------------------------------------------===//
126
James Dennett18a6d792012-06-17 03:26:26 +0000127/// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
Chris Lattnerb694ba72006-07-02 22:41:36 +0000128/// rest of the pragma, passing it to the registered pragma handlers.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000129void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
130 PragmaIntroducerKind Introducer) {
131 if (Callbacks)
132 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
133
Jordan Rosede1a2922012-06-08 18:06:21 +0000134 if (!PragmasEnabled)
135 return;
136
Chris Lattnerb694ba72006-07-02 22:41:36 +0000137 ++NumPragma;
Mike Stump11289f42009-09-09 15:08:12 +0000138
Chris Lattnerb694ba72006-07-02 22:41:36 +0000139 // Invoke the first level of pragma handlers which reads the namespace id.
Chris Lattner146762e2007-07-20 16:59:19 +0000140 Token Tok;
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000141 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000142
Chris Lattnerb694ba72006-07-02 22:41:36 +0000143 // If the pragma handler didn't read the rest of the line, consume it now.
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000144 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
145 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000146 DiscardUntilEndOfDirective();
147}
148
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000149namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000150
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000151/// \brief Helper class for \see Preprocessor::Handle_Pragma.
152class LexingFor_PragmaRAII {
153 Preprocessor &PP;
154 bool InMacroArgPreExpansion;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000155 bool Failed = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000156 Token &OutTok;
157 Token PragmaTok;
158
159public:
160 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
161 Token &Tok)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000162 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion), OutTok(Tok) {
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000163 if (InMacroArgPreExpansion) {
164 PragmaTok = OutTok;
165 PP.EnableBacktrackAtThisPos();
166 }
167 }
168
169 ~LexingFor_PragmaRAII() {
170 if (InMacroArgPreExpansion) {
Alex Lorenz24a1bed2017-02-24 17:45:16 +0000171 // When committing/backtracking the cached pragma tokens in a macro
172 // argument pre-expansion we want to ensure that either the tokens which
173 // have been committed will be removed from the cache or that the tokens
174 // over which we just backtracked won't remain in the cache after they're
175 // consumed and that the caching will stop after consuming them.
176 // Otherwise the caching will interfere with the way macro expansion
177 // works, because we will continue to cache tokens after consuming the
178 // backtracked tokens, which shouldn't happen when we're dealing with
179 // macro argument pre-expansion.
180 auto CachedTokenRange = PP.LastCachedTokenRange();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000181 if (Failed) {
182 PP.CommitBacktrackedTokens();
183 } else {
184 PP.Backtrack();
185 OutTok = PragmaTok;
186 }
Alex Lorenz24a1bed2017-02-24 17:45:16 +0000187 PP.EraseCachedTokens(CachedTokenRange);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000188 }
189 }
190
191 void failed() {
192 Failed = true;
193 }
194};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000195
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000196} // namespace
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000197
Chris Lattnerb694ba72006-07-02 22:41:36 +0000198/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
199/// return the first token after the directive. The _Pragma token has just
200/// been read into 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +0000201void Preprocessor::Handle_Pragma(Token &Tok) {
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000202 // This works differently if we are pre-expanding a macro argument.
203 // In that case we don't actually "activate" the pragma now, we only lex it
204 // until we are sure it is lexically correct and then we backtrack so that
205 // we activate the pragma whenever we encounter the tokens again in the token
206 // stream. This ensures that we will activate it in the correct location
207 // or that we will ignore it if it never enters the token stream, e.g:
208 //
209 // #define EMPTY(x)
210 // #define INACTIVE(x) EMPTY(x)
211 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
212
213 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
214
Chris Lattnerb694ba72006-07-02 22:41:36 +0000215 // Remember the pragma token location.
216 SourceLocation PragmaLoc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000217
Chris Lattnerb694ba72006-07-02 22:41:36 +0000218 // Read the '('.
219 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000220 if (Tok.isNot(tok::l_paren)) {
221 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000222 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000223 }
Chris Lattnerb694ba72006-07-02 22:41:36 +0000224
225 // Read the '"..."'.
226 Lex(Tok);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000227 if (!tok::isStringLiteral(Tok.getKind())) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000228 Diag(PragmaLoc, diag::err__Pragma_malformed);
Hubert Tong0deb6942015-07-30 21:30:00 +0000229 // Skip bad tokens, and the ')', if present.
Reid Kleckner53e6a5d2014-08-14 19:47:06 +0000230 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
Richard Smithd67aea22012-03-06 03:21:47 +0000231 Lex(Tok);
Hubert Tong0deb6942015-07-30 21:30:00 +0000232 while (Tok.isNot(tok::r_paren) &&
233 !Tok.isAtStartOfLine() &&
234 Tok.isNot(tok::eof))
235 Lex(Tok);
Richard Smithd67aea22012-03-06 03:21:47 +0000236 if (Tok.is(tok::r_paren))
237 Lex(Tok);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000238 return _PragmaLexing.failed();
Richard Smithd67aea22012-03-06 03:21:47 +0000239 }
240
241 if (Tok.hasUDSuffix()) {
242 Diag(Tok, diag::err_invalid_string_udl);
243 // Skip this token, and the ')', if present.
244 Lex(Tok);
245 if (Tok.is(tok::r_paren))
246 Lex(Tok);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000247 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000248 }
Mike Stump11289f42009-09-09 15:08:12 +0000249
Chris Lattnerb694ba72006-07-02 22:41:36 +0000250 // Remember the string.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000251 Token StrTok = Tok;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000252
253 // Read the ')'.
254 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000255 if (Tok.isNot(tok::r_paren)) {
256 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000257 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000258 }
Mike Stump11289f42009-09-09 15:08:12 +0000259
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000260 if (InMacroArgPreExpansion)
261 return;
262
Chris Lattner9dc9c202009-02-15 20:52:18 +0000263 SourceLocation RParenLoc = Tok.getLocation();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000264 std::string StrVal = getSpelling(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000265
Richard Smithc98bb4e2013-03-09 23:30:15 +0000266 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
267 // "The string literal is destringized by deleting any encoding prefix,
Chris Lattner262d4e32009-01-16 18:59:23 +0000268 // deleting the leading and trailing double-quotes, replacing each escape
269 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
270 // single backslash."
Richard Smithc98bb4e2013-03-09 23:30:15 +0000271 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
272 (StrVal[0] == 'u' && StrVal[1] != '8'))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000273 StrVal.erase(StrVal.begin());
Richard Smithc98bb4e2013-03-09 23:30:15 +0000274 else if (StrVal[0] == 'u')
275 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
276
277 if (StrVal[0] == 'R') {
278 // FIXME: C++11 does not specify how to handle raw-string-literals here.
279 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
280 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
281 "Invalid raw string token!");
282
283 // Measure the length of the d-char-sequence.
284 unsigned NumDChars = 0;
285 while (StrVal[2 + NumDChars] != '(') {
286 assert(NumDChars < (StrVal.size() - 5) / 2 &&
287 "Invalid raw string token!");
288 ++NumDChars;
289 }
290 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
291
292 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
293 // parens below.
294 StrVal.erase(0, 2 + NumDChars);
295 StrVal.erase(StrVal.size() - 1 - NumDChars);
296 } else {
297 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
298 "Invalid string token!");
299
300 // Remove escaped quotes and escapes.
Benjamin Kramerc2f5f292013-05-04 10:37:20 +0000301 unsigned ResultPos = 1;
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000302 for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
Reid Kleckner95e036c2013-09-25 16:42:48 +0000303 // Skip escapes. \\ -> '\' and \" -> '"'.
304 if (StrVal[i] == '\\' && i + 1 < e &&
305 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
306 ++i;
307 StrVal[ResultPos++] = StrVal[i];
Richard Smithc98bb4e2013-03-09 23:30:15 +0000308 }
Reid Kleckner95e036c2013-09-25 16:42:48 +0000309 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000310 }
Mike Stump11289f42009-09-09 15:08:12 +0000311
Chris Lattnerb694ba72006-07-02 22:41:36 +0000312 // Remove the front quote, replacing it with a space, so that the pragma
313 // contents appear to have a space before them.
314 StrVal[0] = ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000315
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000316 // Replace the terminating quote with a \n.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000317 StrVal[StrVal.size()-1] = '\n';
Mike Stump11289f42009-09-09 15:08:12 +0000318
Peter Collingbournef29ce972011-02-22 13:49:06 +0000319 // Plop the string (including the newline and trailing null) into a buffer
320 // where we can lex it.
321 Token TmpTok;
322 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000323 CreateString(StrVal, TmpTok);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000324 SourceLocation TokLoc = TmpTok.getLocation();
325
326 // Make and enter a lexer object so that we lex and expand the tokens just
327 // like any others.
328 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
329 StrVal.size(), *this);
330
Craig Topperd2d442c2014-05-17 23:10:59 +0000331 EnterSourceFileWithLexer(TL, nullptr);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000332
333 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000334 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
John McCall89e925d2010-08-28 22:34:47 +0000335
336 // Finally, return whatever came after the pragma directive.
337 return Lex(Tok);
338}
339
340/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
341/// is not enclosed within a string literal.
342void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
343 // Remember the pragma token location.
344 SourceLocation PragmaLoc = Tok.getLocation();
345
346 // Read the '('.
347 Lex(Tok);
348 if (Tok.isNot(tok::l_paren)) {
349 Diag(PragmaLoc, diag::err__Pragma_malformed);
350 return;
351 }
352
Peter Collingbournef29ce972011-02-22 13:49:06 +0000353 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000354 SmallVector<Token, 32> PragmaToks;
John McCall89e925d2010-08-28 22:34:47 +0000355 int NumParens = 0;
356 Lex(Tok);
357 while (Tok.isNot(tok::eof)) {
Peter Collingbournef29ce972011-02-22 13:49:06 +0000358 PragmaToks.push_back(Tok);
John McCall89e925d2010-08-28 22:34:47 +0000359 if (Tok.is(tok::l_paren))
360 NumParens++;
361 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
362 break;
John McCall89e925d2010-08-28 22:34:47 +0000363 Lex(Tok);
364 }
365
John McCall49039d42010-08-29 01:09:54 +0000366 if (Tok.is(tok::eof)) {
367 Diag(PragmaLoc, diag::err_unterminated___pragma);
368 return;
369 }
370
Peter Collingbournef29ce972011-02-22 13:49:06 +0000371 PragmaToks.front().setFlag(Token::LeadingSpace);
John McCall89e925d2010-08-28 22:34:47 +0000372
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000373 // Replace the ')' with an EOD to mark the end of the pragma.
374 PragmaToks.back().setKind(tok::eod);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000375
376 Token *TokArray = new Token[PragmaToks.size()];
377 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
378
379 // Push the tokens onto the stack.
380 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
381
382 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000383 HandlePragmaDirective(PragmaLoc, PIK___pragma);
John McCall89e925d2010-08-28 22:34:47 +0000384
385 // Finally, return whatever came after the pragma directive.
386 return Lex(Tok);
387}
388
James Dennett18a6d792012-06-17 03:26:26 +0000389/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
Chris Lattner146762e2007-07-20 16:59:19 +0000390void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
Sunil Srivastavafe583272016-07-25 17:17:06 +0000391 // Don't honor the 'once' when handling the primary source file, unless
Erik Verbruggene0bde752016-10-27 14:17:10 +0000392 // this is a prefix to a TU, which indicates we're generating a PCH file, or
393 // when the main file is a header (e.g. when -xc-header is provided on the
394 // commandline).
395 if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000396 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
397 return;
398 }
Mike Stump11289f42009-09-09 15:08:12 +0000399
Chris Lattnerb694ba72006-07-02 22:41:36 +0000400 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000401 // Mark the file as a once-only file now.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000402 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
Chris Lattnerb694ba72006-07-02 22:41:36 +0000403}
404
Chris Lattnerc2383312007-12-19 19:38:36 +0000405void Preprocessor::HandlePragmaMark() {
Ted Kremenek76c34412008-11-19 22:21:33 +0000406 assert(CurPPLexer && "No current lexer?");
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000407 if (CurLexer)
408 CurLexer->ReadToEndOfLine();
409 else
410 CurPTHLexer->DiscardToEndOfLine();
Chris Lattnerc2383312007-12-19 19:38:36 +0000411}
412
James Dennett18a6d792012-06-17 03:26:26 +0000413/// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
Erik Verbruggen851ce0e2016-10-26 11:46:10 +0000414void Preprocessor::HandlePragmaPoison() {
Chris Lattner146762e2007-07-20 16:59:19 +0000415 Token Tok;
Chris Lattner538d7f32006-07-20 04:31:52 +0000416
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000417 while (true) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000418 // Read the next token to poison. While doing this, pretend that we are
419 // skipping while reading the identifier to poison.
420 // This avoids errors on code like:
421 // #pragma GCC poison X
422 // #pragma GCC poison X
Ted Kremenek551c82a2008-11-18 01:12:54 +0000423 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000424 LexUnexpandedToken(Tok);
Ted Kremenek551c82a2008-11-18 01:12:54 +0000425 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000426
Chris Lattnerb694ba72006-07-02 22:41:36 +0000427 // If we reached the end of line, we're done.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000428 if (Tok.is(tok::eod)) return;
Mike Stump11289f42009-09-09 15:08:12 +0000429
Chris Lattnerb694ba72006-07-02 22:41:36 +0000430 // Can only poison identifiers.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000431 if (Tok.isNot(tok::raw_identifier)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000432 Diag(Tok, diag::err_pp_invalid_poison);
433 return;
434 }
Mike Stump11289f42009-09-09 15:08:12 +0000435
Chris Lattnercefc7682006-07-08 08:28:12 +0000436 // Look up the identifier info for the token. We disabled identifier lookup
437 // by saying we're skipping contents, so we need to do this manually.
438 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000439
Chris Lattnerb694ba72006-07-02 22:41:36 +0000440 // Already poisoned.
441 if (II->isPoisoned()) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000442
Chris Lattnerb694ba72006-07-02 22:41:36 +0000443 // If this is a macro identifier, emit a warning.
Richard Smith20e883e2015-04-29 23:20:19 +0000444 if (isMacroDefined(II))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000445 Diag(Tok, diag::pp_poisoning_existing_macro);
Mike Stump11289f42009-09-09 15:08:12 +0000446
Chris Lattnerb694ba72006-07-02 22:41:36 +0000447 // Finally, poison it!
448 II->setIsPoisoned();
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000449 if (II->isFromAST())
450 II->setChangedSinceDeserialization();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000451 }
452}
453
James Dennett18a6d792012-06-17 03:26:26 +0000454/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
Chris Lattnerb694ba72006-07-02 22:41:36 +0000455/// that the whole directive has been parsed.
Chris Lattner146762e2007-07-20 16:59:19 +0000456void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000457 if (isInPrimaryFile()) {
458 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
459 return;
460 }
Mike Stump11289f42009-09-09 15:08:12 +0000461
Chris Lattnerb694ba72006-07-02 22:41:36 +0000462 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Ted Kremenek300590b2008-11-20 01:45:11 +0000463 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump11289f42009-09-09 15:08:12 +0000464
Chris Lattnerb694ba72006-07-02 22:41:36 +0000465 // Mark the file as a system header.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000466 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
Mike Stump11289f42009-09-09 15:08:12 +0000467
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000468 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000469 if (PLoc.isInvalid())
470 return;
471
Jay Foad9a6b0982011-06-21 15:13:30 +0000472 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
Mike Stump11289f42009-09-09 15:08:12 +0000473
Chris Lattner3bdc7672011-05-22 22:10:16 +0000474 // Notify the client, if desired, that we are in a new source file.
475 if (Callbacks)
476 Callbacks->FileChanged(SysHeaderTok.getLocation(),
477 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
478
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000479 // Emit a line marker. This will change any source locations from this point
480 // forward to realize they are in a system header.
481 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +0000482 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
Jordan Rose111c4a62013-04-17 19:09:18 +0000483 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
Reid Klecknereb00ee02017-05-22 21:42:58 +0000484 SrcMgr::C_System);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000485}
486
James Dennett18a6d792012-06-17 03:26:26 +0000487/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
Chris Lattner146762e2007-07-20 16:59:19 +0000488void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
489 Token FilenameTok;
Ted Kremenek551c82a2008-11-18 01:12:54 +0000490 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000491
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000492 // If the token kind is EOD, the error has already been diagnosed.
493 if (FilenameTok.is(tok::eod))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000494 return;
Mike Stump11289f42009-09-09 15:08:12 +0000495
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000496 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000497 SmallString<128> FilenameBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +0000498 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000499 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +0000500 if (Invalid)
501 return;
Mike Stump11289f42009-09-09 15:08:12 +0000502
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000503 bool isAngled =
504 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000505 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
506 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000507 if (Filename.empty())
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000508 return;
Mike Stump11289f42009-09-09 15:08:12 +0000509
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000510 // Search include directories for this file.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000511 const DirectoryLookup *CurDir;
Richard Smith25d50752014-10-20 00:15:49 +0000512 const FileEntry *File =
513 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000514 nullptr, CurDir, nullptr, nullptr, nullptr, nullptr);
Craig Topperd2d442c2014-05-17 23:10:59 +0000515 if (!File) {
Eli Friedman3781a362011-08-30 23:07:51 +0000516 if (!SuppressIncludeNotFoundError)
517 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +0000518 return;
519 }
Mike Stump11289f42009-09-09 15:08:12 +0000520
Chris Lattnerd32480d2009-01-17 06:22:33 +0000521 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000522
523 // If this file is older than the file it depends on, emit a diagnostic.
524 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
525 // Lex tokens at the end of the message and include them in the message.
526 std::string Message;
527 Lex(DependencyTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000528 while (DependencyTok.isNot(tok::eod)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000529 Message += getSpelling(DependencyTok) + " ";
530 Lex(DependencyTok);
531 }
Mike Stump11289f42009-09-09 15:08:12 +0000532
Chris Lattnerf0b04972010-09-05 23:16:09 +0000533 // Remove the trailing ' ' if present.
534 if (!Message.empty())
535 Message.erase(Message.end()-1);
Chris Lattner97b8e842008-11-18 08:02:48 +0000536 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000537 }
538}
539
Reid Kleckner002562a2013-05-06 21:02:12 +0000540/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000541/// Return the IdentifierInfo* associated with the macro to push or pop.
542IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
543 // Remember the pragma token location.
544 Token PragmaTok = Tok;
545
546 // Read the '('.
547 Lex(Tok);
548 if (Tok.isNot(tok::l_paren)) {
549 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
550 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000551 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000552 }
553
554 // Read the macro name string.
555 Lex(Tok);
556 if (Tok.isNot(tok::string_literal)) {
557 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
558 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000559 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000560 }
561
Richard Smithd67aea22012-03-06 03:21:47 +0000562 if (Tok.hasUDSuffix()) {
563 Diag(Tok, diag::err_invalid_string_udl);
Craig Topperd2d442c2014-05-17 23:10:59 +0000564 return nullptr;
Richard Smithd67aea22012-03-06 03:21:47 +0000565 }
566
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000567 // Remember the macro string.
568 std::string StrVal = getSpelling(Tok);
569
570 // Read the ')'.
571 Lex(Tok);
572 if (Tok.isNot(tok::r_paren)) {
573 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
574 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000575 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000576 }
577
578 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
579 "Invalid string token!");
580
581 // Create a Token from the string.
582 Token MacroTok;
583 MacroTok.startToken();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000584 MacroTok.setKind(tok::raw_identifier);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000585 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000586
587 // Get the IdentifierInfo of MacroToPushTok.
588 return LookUpIdentifierInfo(MacroTok);
589}
590
James Dennett18a6d792012-06-17 03:26:26 +0000591/// \brief Handle \#pragma push_macro.
592///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000593/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000594/// \code
Dmitri Gribenko9ebd1612012-11-30 20:04:39 +0000595/// #pragma push_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000596/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000597void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
598 // Parse the pragma directive and get the macro IdentifierInfo*.
599 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
600 if (!IdentInfo) return;
601
602 // Get the MacroInfo associated with IdentInfo.
603 MacroInfo *MI = getMacroInfo(IdentInfo);
604
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000605 if (MI) {
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000606 // Allow the original MacroInfo to be redefined later.
607 MI->setIsAllowRedefinitionsWithoutWarning(true);
608 }
609
610 // Push the cloned MacroInfo so we can retrieve it later.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +0000611 PragmaPushMacroInfo[IdentInfo].push_back(MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000612}
613
James Dennett18a6d792012-06-17 03:26:26 +0000614/// \brief Handle \#pragma pop_macro.
615///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000616/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000617/// \code
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000618/// #pragma pop_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000619/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000620void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
621 SourceLocation MessageLoc = PopMacroTok.getLocation();
622
623 // Parse the pragma directive and get the macro IdentifierInfo*.
624 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
625 if (!IdentInfo) return;
626
627 // Find the vector<MacroInfo*> associated with the macro.
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000628 llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter =
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000629 PragmaPushMacroInfo.find(IdentInfo);
630 if (iter != PragmaPushMacroInfo.end()) {
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000631 // Forget the MacroInfo currently associated with IdentInfo.
Richard Smith20e883e2015-04-29 23:20:19 +0000632 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000633 if (MI->isWarnIfUnused())
634 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
635 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000636 }
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000637
638 // Get the MacroInfo we want to reinstall.
639 MacroInfo *MacroToReInstall = iter->second.back();
640
Richard Smith713369b2015-04-23 20:40:50 +0000641 if (MacroToReInstall)
Alexander Kornienkoc0b49282012-08-29 16:56:24 +0000642 // Reinstall the previously pushed macro.
Richard Smith713369b2015-04-23 20:40:50 +0000643 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000644
645 // Pop PragmaPushMacroInfo stack.
646 iter->second.pop_back();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000647 if (iter->second.empty())
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000648 PragmaPushMacroInfo.erase(iter);
649 } else {
650 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
651 << IdentInfo->getName();
652 }
653}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000654
Aaron Ballman611306e2012-03-02 22:51:54 +0000655void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
656 // We will either get a quoted filename or a bracketed filename, and we
657 // have to track which we got. The first filename is the source name,
658 // and the second name is the mapped filename. If the first is quoted,
659 // the second must be as well (cannot mix and match quotes and brackets).
Aaron Ballman611306e2012-03-02 22:51:54 +0000660
661 // Get the open paren
662 Lex(Tok);
663 if (Tok.isNot(tok::l_paren)) {
664 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
665 return;
666 }
667
668 // We expect either a quoted string literal, or a bracketed name
669 Token SourceFilenameTok;
670 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
671 if (SourceFilenameTok.is(tok::eod)) {
672 // The diagnostic has already been handled
673 return;
674 }
675
676 StringRef SourceFileName;
677 SmallString<128> FileNameBuffer;
678 if (SourceFilenameTok.is(tok::string_literal) ||
679 SourceFilenameTok.is(tok::angle_string_literal)) {
680 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
681 } else if (SourceFilenameTok.is(tok::less)) {
682 // This could be a path instead of just a name
683 FileNameBuffer.push_back('<');
684 SourceLocation End;
685 if (ConcatenateIncludeName(FileNameBuffer, End))
686 return; // Diagnostic already emitted
Yaron Keren92e1b622015-03-18 10:17:07 +0000687 SourceFileName = FileNameBuffer;
Aaron Ballman611306e2012-03-02 22:51:54 +0000688 } else {
689 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
690 return;
691 }
692 FileNameBuffer.clear();
693
694 // Now we expect a comma, followed by another include name
695 Lex(Tok);
696 if (Tok.isNot(tok::comma)) {
697 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
698 return;
699 }
700
701 Token ReplaceFilenameTok;
702 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
703 if (ReplaceFilenameTok.is(tok::eod)) {
704 // The diagnostic has already been handled
705 return;
706 }
707
708 StringRef ReplaceFileName;
709 if (ReplaceFilenameTok.is(tok::string_literal) ||
710 ReplaceFilenameTok.is(tok::angle_string_literal)) {
711 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
712 } else if (ReplaceFilenameTok.is(tok::less)) {
713 // This could be a path instead of just a name
714 FileNameBuffer.push_back('<');
715 SourceLocation End;
716 if (ConcatenateIncludeName(FileNameBuffer, End))
717 return; // Diagnostic already emitted
Yaron Keren92e1b622015-03-18 10:17:07 +0000718 ReplaceFileName = FileNameBuffer;
Aaron Ballman611306e2012-03-02 22:51:54 +0000719 } else {
720 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
721 return;
722 }
723
724 // Finally, we expect the closing paren
725 Lex(Tok);
726 if (Tok.isNot(tok::r_paren)) {
727 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
728 return;
729 }
730
731 // Now that we have the source and target filenames, we need to make sure
732 // they're both of the same type (angled vs non-angled)
733 StringRef OriginalSource = SourceFileName;
734
735 bool SourceIsAngled =
736 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
737 SourceFileName);
738 bool ReplaceIsAngled =
739 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
740 ReplaceFileName);
741 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
742 (SourceIsAngled != ReplaceIsAngled)) {
743 unsigned int DiagID;
744 if (SourceIsAngled)
745 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
746 else
747 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
748
749 Diag(SourceFilenameTok.getLocation(), DiagID)
750 << SourceFileName
751 << ReplaceFileName;
752
753 return;
754 }
755
756 // Now we can let the include handler know about this mapping
757 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
758}
759
Richard Smith9565c75b2017-06-19 23:09:36 +0000760// Lex a component of a module name: either an identifier or a string literal;
761// for components that can be expressed both ways, the two forms are equivalent.
762static bool LexModuleNameComponent(
763 Preprocessor &PP, Token &Tok,
764 std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent,
765 bool First) {
766 PP.LexUnexpandedToken(Tok);
767 if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
768 StringLiteralParser Literal(Tok, PP);
769 if (Literal.hadError)
770 return true;
771 ModuleNameComponent = std::make_pair(
772 PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation());
773 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
774 ModuleNameComponent =
775 std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
776 } else {
777 PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
778 return true;
779 }
780 return false;
781}
782
783static bool LexModuleName(
784 Preprocessor &PP, Token &Tok,
785 llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
786 &ModuleName) {
787 while (true) {
788 std::pair<IdentifierInfo*, SourceLocation> NameComponent;
789 if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
790 return true;
791 ModuleName.push_back(NameComponent);
792
793 PP.LexUnexpandedToken(Tok);
794 if (Tok.isNot(tok::period))
795 return false;
796 }
797}
798
Richard Smith5d2ed482017-06-09 19:22:32 +0000799void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
800 SourceLocation Loc = Tok.getLocation();
801
Richard Smith9565c75b2017-06-19 23:09:36 +0000802 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
803 if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
Richard Smith5d2ed482017-06-09 19:22:32 +0000804 return;
Richard Smith9565c75b2017-06-19 23:09:36 +0000805 IdentifierInfo *ModuleName = ModuleNameLoc.first;
Richard Smith5d2ed482017-06-09 19:22:32 +0000806
807 LexUnexpandedToken(Tok);
808 if (Tok.isNot(tok::eod)) {
809 Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
810 DiscardUntilEndOfDirective();
811 }
812
813 if (CurPTHLexer) {
814 // FIXME: Support this somehow?
815 Diag(Loc, diag::err_pp_module_build_pth);
816 return;
817 }
818
819 CurLexer->LexingRawMode = true;
820
821 auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
822 if (Tok.getKind() != tok::raw_identifier ||
823 Tok.getRawIdentifier() != Ident)
824 return false;
825 CurLexer->Lex(Tok);
826 return true;
827 };
828
829 // Scan forward looking for the end of the module.
830 const char *Start = CurLexer->getBufferLocation();
831 const char *End = nullptr;
832 unsigned NestingLevel = 1;
833 while (true) {
834 End = CurLexer->getBufferLocation();
835 CurLexer->Lex(Tok);
836
837 if (Tok.is(tok::eof)) {
838 Diag(Loc, diag::err_pp_module_build_missing_end);
839 break;
840 }
841
842 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
843 // Token was part of module; keep going.
844 continue;
845 }
846
847 // We hit something directive-shaped; check to see if this is the end
848 // of the module build.
849 CurLexer->ParsingPreprocessorDirective = true;
850 CurLexer->Lex(Tok);
851 if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
852 TryConsumeIdentifier("module")) {
853 if (TryConsumeIdentifier("build"))
854 // #pragma clang module build -> entering a nested module build.
855 ++NestingLevel;
856 else if (TryConsumeIdentifier("endbuild")) {
857 // #pragma clang module endbuild -> leaving a module build.
858 if (--NestingLevel == 0)
859 break;
860 }
861 // We should either be looking at the EOD or more of the current directive
862 // preceding the EOD. Either way we can ignore this token and keep going.
863 assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
864 }
865 }
866
867 CurLexer->LexingRawMode = false;
868
869 // Load the extracted text as a preprocessed module.
870 assert(CurLexer->getBuffer().begin() <= Start &&
871 Start <= CurLexer->getBuffer().end() &&
872 CurLexer->getBuffer().begin() <= End &&
873 End <= CurLexer->getBuffer().end() &&
874 "module source range not contained within same file buffer");
875 TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(),
876 StringRef(Start, End - Start));
877}
878
Chris Lattnerb694ba72006-07-02 22:41:36 +0000879/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
880/// If 'Namespace' is non-null, then it is a token required to exist on the
881/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000882void Preprocessor::AddPragmaHandler(StringRef Namespace,
Chris Lattnerb694ba72006-07-02 22:41:36 +0000883 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000884 PragmaNamespace *InsertNS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000885
Chris Lattnerb694ba72006-07-02 22:41:36 +0000886 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000887 if (!Namespace.empty()) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000888 // If there is already a pragma handler with the name of this namespace,
889 // we either have an error (directive with the same name as a namespace) or
890 // we already have the namespace to insert into.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000891 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000892 InsertNS = Existing->getIfNamespace();
Craig Topperd2d442c2014-05-17 23:10:59 +0000893 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
Chris Lattnerb694ba72006-07-02 22:41:36 +0000894 " handler with the same name!");
895 } else {
896 // Otherwise, this namespace doesn't exist yet, create and insert the
897 // handler for it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000898 InsertNS = new PragmaNamespace(Namespace);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000899 PragmaHandlers->AddPragma(InsertNS);
900 }
901 }
Mike Stump11289f42009-09-09 15:08:12 +0000902
Chris Lattnerb694ba72006-07-02 22:41:36 +0000903 // Check to make sure we don't already have a pragma for this identifier.
904 assert(!InsertNS->FindHandler(Handler->getName()) &&
905 "Pragma handler already exists for this identifier!");
906 InsertNS->AddPragma(Handler);
907}
908
Daniel Dunbar40596532008-10-04 19:17:46 +0000909/// RemovePragmaHandler - Remove the specific pragma handler from the
910/// preprocessor. If \arg Namespace is non-null, then it should be the
911/// namespace that \arg Handler was added to. It is an error to remove
912/// a handler that has not been registered.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000913void Preprocessor::RemovePragmaHandler(StringRef Namespace,
Daniel Dunbar40596532008-10-04 19:17:46 +0000914 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000915 PragmaNamespace *NS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000916
Daniel Dunbar40596532008-10-04 19:17:46 +0000917 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000918 if (!Namespace.empty()) {
919 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
Daniel Dunbar40596532008-10-04 19:17:46 +0000920 assert(Existing && "Namespace containing handler does not exist!");
921
922 NS = Existing->getIfNamespace();
923 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
924 }
925
926 NS->RemovePragmaHandler(Handler);
Mike Stump11289f42009-09-09 15:08:12 +0000927
Craig Topperbe250302014-09-12 05:19:24 +0000928 // If this is a non-default namespace and it is now empty, remove it.
929 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
Daniel Dunbar40596532008-10-04 19:17:46 +0000930 PragmaHandlers->RemovePragmaHandler(NS);
Argyrios Kyrtzidis7ce75262012-01-06 00:22:09 +0000931 delete NS;
932 }
Daniel Dunbar40596532008-10-04 19:17:46 +0000933}
934
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000935bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
936 Token Tok;
937 LexUnexpandedToken(Tok);
938
939 if (Tok.isNot(tok::identifier)) {
940 Diag(Tok, diag::ext_on_off_switch_syntax);
941 return true;
942 }
943 IdentifierInfo *II = Tok.getIdentifierInfo();
944 if (II->isStr("ON"))
945 Result = tok::OOS_ON;
946 else if (II->isStr("OFF"))
947 Result = tok::OOS_OFF;
948 else if (II->isStr("DEFAULT"))
949 Result = tok::OOS_DEFAULT;
950 else {
951 Diag(Tok, diag::ext_on_off_switch_syntax);
952 return true;
953 }
954
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000955 // Verify that this is followed by EOD.
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000956 LexUnexpandedToken(Tok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000957 if (Tok.isNot(tok::eod))
958 Diag(Tok, diag::ext_pragma_syntax_eod);
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000959 return false;
960}
961
Chris Lattnerb694ba72006-07-02 22:41:36 +0000962namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000963
James Dennett18a6d792012-06-17 03:26:26 +0000964/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000965struct PragmaOnceHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000966 PragmaOnceHandler() : PragmaHandler("once") {}
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000967
Craig Topper9140dd22014-03-11 06:50:42 +0000968 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
969 Token &OnceTok) override {
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000970 PP.CheckEndOfDirective("pragma once");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000971 PP.HandlePragmaOnce(OnceTok);
972 }
973};
974
James Dennett18a6d792012-06-17 03:26:26 +0000975/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
Chris Lattnerc2383312007-12-19 19:38:36 +0000976/// rest of the line is not lexed.
977struct PragmaMarkHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000978 PragmaMarkHandler() : PragmaHandler("mark") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000979
Craig Topper9140dd22014-03-11 06:50:42 +0000980 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
981 Token &MarkTok) override {
Chris Lattnerc2383312007-12-19 19:38:36 +0000982 PP.HandlePragmaMark();
983 }
984};
985
James Dennett18a6d792012-06-17 03:26:26 +0000986/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000987struct PragmaPoisonHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000988 PragmaPoisonHandler() : PragmaHandler("poison") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000989
Craig Topper9140dd22014-03-11 06:50:42 +0000990 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
991 Token &PoisonTok) override {
Erik Verbruggen851ce0e2016-10-26 11:46:10 +0000992 PP.HandlePragmaPoison();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000993 }
994};
995
James Dennett18a6d792012-06-17 03:26:26 +0000996/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
Chris Lattnerc2383312007-12-19 19:38:36 +0000997/// as a system header, which silences warnings in it.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000998struct PragmaSystemHeaderHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000999 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001000
Craig Topper9140dd22014-03-11 06:50:42 +00001001 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1002 Token &SHToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +00001003 PP.HandlePragmaSystemHeader(SHToken);
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001004 PP.CheckEndOfDirective("pragma");
Chris Lattnerb694ba72006-07-02 22:41:36 +00001005 }
1006};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001007
Chris Lattnerb694ba72006-07-02 22:41:36 +00001008struct PragmaDependencyHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001009 PragmaDependencyHandler() : PragmaHandler("dependency") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001010
Craig Topper9140dd22014-03-11 06:50:42 +00001011 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1012 Token &DepToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +00001013 PP.HandlePragmaDependency(DepToken);
1014 }
1015};
Mike Stump11289f42009-09-09 15:08:12 +00001016
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001017struct PragmaDebugHandler : public PragmaHandler {
1018 PragmaDebugHandler() : PragmaHandler("__debug") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001019
Craig Topper9140dd22014-03-11 06:50:42 +00001020 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1021 Token &DepToken) override {
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001022 Token Tok;
1023 PP.LexUnexpandedToken(Tok);
1024 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001025 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001026 return;
1027 }
1028 IdentifierInfo *II = Tok.getIdentifierInfo();
1029
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001030 if (II->isStr("assert")) {
David Blaikie83d382b2011-09-23 05:06:16 +00001031 llvm_unreachable("This is an assertion!");
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001032 } else if (II->isStr("crash")) {
David Blaikie5bd4c2a2012-08-21 18:56:49 +00001033 LLVM_BUILTIN_TRAP;
David Blaikie5d577a22012-06-29 22:03:56 +00001034 } else if (II->isStr("parser_crash")) {
1035 Token Crasher;
Benjamin Kramer3162f292015-03-08 19:28:24 +00001036 Crasher.startToken();
David Blaikie5d577a22012-06-29 22:03:56 +00001037 Crasher.setKind(tok::annot_pragma_parser_crash);
Benjamin Kramer3162f292015-03-08 19:28:24 +00001038 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
David Blaikie5d577a22012-06-29 22:03:56 +00001039 PP.EnterToken(Crasher);
Richard Smithba3a4f92016-01-12 21:59:26 +00001040 } else if (II->isStr("dump")) {
1041 Token Identifier;
1042 PP.LexUnexpandedToken(Identifier);
1043 if (auto *DumpII = Identifier.getIdentifierInfo()) {
1044 Token DumpAnnot;
1045 DumpAnnot.startToken();
1046 DumpAnnot.setKind(tok::annot_pragma_dump);
1047 DumpAnnot.setAnnotationRange(
1048 SourceRange(Tok.getLocation(), Identifier.getLocation()));
1049 DumpAnnot.setAnnotationValue(DumpII);
1050 PP.DiscardUntilEndOfDirective();
1051 PP.EnterToken(DumpAnnot);
1052 } else {
1053 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
1054 << II->getName();
1055 }
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001056 } else if (II->isStr("llvm_fatal_error")) {
1057 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1058 } else if (II->isStr("llvm_unreachable")) {
1059 llvm_unreachable("#pragma clang __debug llvm_unreachable");
Richard Smith3ffa61d2015-04-30 23:10:40 +00001060 } else if (II->isStr("macro")) {
1061 Token MacroName;
1062 PP.LexUnexpandedToken(MacroName);
1063 auto *MacroII = MacroName.getIdentifierInfo();
1064 if (MacroII)
1065 PP.dumpMacroInfo(MacroII);
1066 else
Richard Smithba3a4f92016-01-12 21:59:26 +00001067 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1068 << II->getName();
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001069 } else if (II->isStr("overflow_stack")) {
1070 DebugOverflowStack();
Daniel Dunbar211a7872010-08-18 23:09:23 +00001071 } else if (II->isStr("handle_crash")) {
1072 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
1073 if (CRC)
1074 CRC->HandleCrash();
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001075 } else if (II->isStr("captured")) {
1076 HandleCaptured(PP);
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001077 } else {
1078 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1079 << II->getName();
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001080 }
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001081
1082 PPCallbacks *Callbacks = PP.getPPCallbacks();
1083 if (Callbacks)
1084 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1085 }
1086
1087 void HandleCaptured(Preprocessor &PP) {
1088 // Skip if emitting preprocessed output.
1089 if (PP.isPreprocessedOutput())
1090 return;
1091
1092 Token Tok;
1093 PP.LexUnexpandedToken(Tok);
1094
1095 if (Tok.isNot(tok::eod)) {
1096 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1097 << "pragma clang __debug captured";
1098 return;
1099 }
1100
1101 SourceLocation NameLoc = Tok.getLocation();
David Blaikie2eabcc92016-02-09 18:52:09 +00001102 MutableArrayRef<Token> Toks(
1103 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1104 Toks[0].startToken();
1105 Toks[0].setKind(tok::annot_pragma_captured);
1106 Toks[0].setLocation(NameLoc);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001107
David Blaikie2eabcc92016-02-09 18:52:09 +00001108 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001109 }
1110
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001111// Disable MSVC warning about runtime stack overflow.
1112#ifdef _MSC_VER
1113 #pragma warning(disable : 4717)
1114#endif
Matthias Braun285f88d2017-04-24 18:41:00 +00001115 static void DebugOverflowStack(void (*P)() = nullptr) {
1116 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1117 Self(reinterpret_cast<void(*)()>(Self));
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001118 }
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001119#ifdef _MSC_VER
1120 #pragma warning(default : 4717)
1121#endif
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001122};
1123
James Dennett18a6d792012-06-17 03:26:26 +00001124/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
Chris Lattner504af112009-04-19 23:16:58 +00001125struct PragmaDiagnosticHandler : public PragmaHandler {
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001126private:
1127 const char *Namespace;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001128
Chris Lattnerfb42a182009-07-12 21:18:45 +00001129public:
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001130 explicit PragmaDiagnosticHandler(const char *NS)
1131 : PragmaHandler("diagnostic"), Namespace(NS) {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001132
Craig Topper9140dd22014-03-11 06:50:42 +00001133 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1134 Token &DiagToken) override {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001135 SourceLocation DiagLoc = DiagToken.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001136 Token Tok;
1137 PP.LexUnexpandedToken(Tok);
1138 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001139 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001140 return;
1141 }
1142 IdentifierInfo *II = Tok.getIdentifierInfo();
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001143 PPCallbacks *Callbacks = PP.getPPCallbacks();
Mike Stump11289f42009-09-09 15:08:12 +00001144
Alp Toker46df1c02014-06-12 10:15:20 +00001145 if (II->isStr("pop")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001146 if (!PP.getDiagnostics().popMappings(DiagLoc))
Douglas Gregor3cc26482010-08-30 15:15:34 +00001147 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001148 else if (Callbacks)
1149 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
Douglas Gregor3cc26482010-08-30 15:15:34 +00001150 return;
1151 } else if (II->isStr("push")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001152 PP.getDiagnostics().pushMappings(DiagLoc);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001153 if (Callbacks)
1154 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
Chris Lattnerfb42a182009-07-12 21:18:45 +00001155 return;
Alp Toker46df1c02014-06-12 10:15:20 +00001156 }
1157
1158 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1159 .Case("ignored", diag::Severity::Ignored)
1160 .Case("warning", diag::Severity::Warning)
1161 .Case("error", diag::Severity::Error)
1162 .Case("fatal", diag::Severity::Fatal)
1163 .Default(diag::Severity());
1164
1165 if (SV == diag::Severity()) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001166 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001167 return;
1168 }
Mike Stump11289f42009-09-09 15:08:12 +00001169
Chris Lattner504af112009-04-19 23:16:58 +00001170 PP.LexUnexpandedToken(Tok);
Andy Gibbs58905d22012-11-17 19:15:38 +00001171 SourceLocation StringLoc = Tok.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001172
Andy Gibbs58905d22012-11-17 19:15:38 +00001173 std::string WarningName;
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001174 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1175 /*MacroExpansion=*/false))
Chris Lattner504af112009-04-19 23:16:58 +00001176 return;
Mike Stump11289f42009-09-09 15:08:12 +00001177
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001178 if (Tok.isNot(tok::eod)) {
Chris Lattner504af112009-04-19 23:16:58 +00001179 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1180 return;
1181 }
Mike Stump11289f42009-09-09 15:08:12 +00001182
Chris Lattner504af112009-04-19 23:16:58 +00001183 if (WarningName.size() < 3 || WarningName[0] != '-' ||
Richard Smith3be1cb22014-08-07 00:24:21 +00001184 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001185 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
Chris Lattner504af112009-04-19 23:16:58 +00001186 return;
1187 }
Mike Stump11289f42009-09-09 15:08:12 +00001188
Sunil Srivastava5239de72016-02-13 01:44:05 +00001189 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1190 : diag::Flavor::Remark;
Benjamin Kramer2193e232016-02-13 13:42:41 +00001191 StringRef Group = StringRef(WarningName).substr(2);
Sunil Srivastava5239de72016-02-13 01:44:05 +00001192 bool unknownDiag = false;
1193 if (Group == "everything") {
1194 // Special handling for pragma clang diagnostic ... "-Weverything".
1195 // There is no formal group named "everything", so there has to be a
1196 // special case for it.
1197 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1198 } else
1199 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1200 DiagLoc);
1201 if (unknownDiag)
Andy Gibbs58905d22012-11-17 19:15:38 +00001202 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1203 << WarningName;
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001204 else if (Callbacks)
Alp Toker46df1c02014-06-12 10:15:20 +00001205 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
Chris Lattner504af112009-04-19 23:16:58 +00001206 }
1207};
Mike Stump11289f42009-09-09 15:08:12 +00001208
Reid Kleckner881dff32013-09-13 22:00:30 +00001209/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1210/// diagnostics, so we don't really implement this pragma. We parse it and
1211/// ignore it to avoid -Wunknown-pragma warnings.
1212struct PragmaWarningHandler : public PragmaHandler {
1213 PragmaWarningHandler() : PragmaHandler("warning") {}
1214
Craig Topper9140dd22014-03-11 06:50:42 +00001215 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1216 Token &Tok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001217 // Parse things like:
1218 // warning(push, 1)
1219 // warning(pop)
John Thompson4762b232013-11-16 00:16:03 +00001220 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
Reid Kleckner881dff32013-09-13 22:00:30 +00001221 SourceLocation DiagLoc = Tok.getLocation();
1222 PPCallbacks *Callbacks = PP.getPPCallbacks();
1223
1224 PP.Lex(Tok);
1225 if (Tok.isNot(tok::l_paren)) {
1226 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1227 return;
1228 }
1229
1230 PP.Lex(Tok);
1231 IdentifierInfo *II = Tok.getIdentifierInfo();
Reid Kleckner881dff32013-09-13 22:00:30 +00001232
Alexander Musman6b080fc2015-05-25 11:21:20 +00001233 if (II && II->isStr("push")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001234 // #pragma warning( push[ ,n ] )
Reid Kleckner4d185102013-10-02 15:19:23 +00001235 int Level = -1;
Reid Kleckner881dff32013-09-13 22:00:30 +00001236 PP.Lex(Tok);
1237 if (Tok.is(tok::comma)) {
1238 PP.Lex(Tok);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001239 uint64_t Value;
1240 if (Tok.is(tok::numeric_constant) &&
1241 PP.parseSimpleIntegerLiteral(Tok, Value))
1242 Level = int(Value);
Reid Kleckner4d185102013-10-02 15:19:23 +00001243 if (Level < 0 || Level > 4) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001244 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1245 return;
1246 }
1247 }
1248 if (Callbacks)
1249 Callbacks->PragmaWarningPush(DiagLoc, Level);
Alexander Musman6b080fc2015-05-25 11:21:20 +00001250 } else if (II && II->isStr("pop")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001251 // #pragma warning( pop )
1252 PP.Lex(Tok);
1253 if (Callbacks)
1254 Callbacks->PragmaWarningPop(DiagLoc);
1255 } else {
1256 // #pragma warning( warning-specifier : warning-number-list
1257 // [; warning-specifier : warning-number-list...] )
1258 while (true) {
1259 II = Tok.getIdentifierInfo();
Alexander Musman6b080fc2015-05-25 11:21:20 +00001260 if (!II && !Tok.is(tok::numeric_constant)) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001261 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1262 return;
1263 }
1264
1265 // Figure out which warning specifier this is.
Alexander Musman6b080fc2015-05-25 11:21:20 +00001266 bool SpecifierValid;
1267 StringRef Specifier;
1268 llvm::SmallString<1> SpecifierBuf;
1269 if (II) {
1270 Specifier = II->getName();
1271 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1272 .Cases("default", "disable", "error", "once",
1273 "suppress", true)
1274 .Default(false);
1275 // If we read a correct specifier, snatch next token (that should be
1276 // ":", checked later).
1277 if (SpecifierValid)
1278 PP.Lex(Tok);
1279 } else {
1280 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1281 uint64_t Value;
1282 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1283 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1284 SpecifierValid = (Value >= 1) && (Value <= 4);
1285 } else
1286 SpecifierValid = false;
1287 // Next token already snatched by parseSimpleIntegerLiteral.
1288 }
1289
Reid Kleckner881dff32013-09-13 22:00:30 +00001290 if (!SpecifierValid) {
1291 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1292 return;
1293 }
Reid Kleckner881dff32013-09-13 22:00:30 +00001294 if (Tok.isNot(tok::colon)) {
1295 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1296 return;
1297 }
1298
1299 // Collect the warning ids.
1300 SmallVector<int, 4> Ids;
1301 PP.Lex(Tok);
1302 while (Tok.is(tok::numeric_constant)) {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001303 uint64_t Value;
1304 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001305 Value > std::numeric_limits<int>::max()) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001306 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1307 return;
1308 }
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001309 Ids.push_back(int(Value));
Reid Kleckner881dff32013-09-13 22:00:30 +00001310 }
1311 if (Callbacks)
1312 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1313
1314 // Parse the next specifier if there is a semicolon.
1315 if (Tok.isNot(tok::semi))
1316 break;
1317 PP.Lex(Tok);
1318 }
1319 }
1320
1321 if (Tok.isNot(tok::r_paren)) {
1322 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1323 return;
1324 }
1325
1326 PP.Lex(Tok);
1327 if (Tok.isNot(tok::eod))
1328 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1329 }
1330};
1331
James Dennett18a6d792012-06-17 03:26:26 +00001332/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
Aaron Ballman611306e2012-03-02 22:51:54 +00001333struct PragmaIncludeAliasHandler : public PragmaHandler {
1334 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001335
Craig Topper9140dd22014-03-11 06:50:42 +00001336 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1337 Token &IncludeAliasTok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001338 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
Aaron Ballman611306e2012-03-02 22:51:54 +00001339 }
1340};
1341
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001342/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1343/// extension. The syntax is:
1344/// \code
1345/// #pragma message(string)
1346/// \endcode
1347/// OR, in GCC mode:
1348/// \code
1349/// #pragma message string
1350/// \endcode
1351/// string is a string, which is fully macro expanded, and permits string
1352/// concatenation, embedded escape characters, etc... See MSDN for more details.
1353/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1354/// form as \#pragma message.
Chris Lattner30c924b2010-06-26 17:11:39 +00001355struct PragmaMessageHandler : public PragmaHandler {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001356private:
1357 const PPCallbacks::PragmaMessageKind Kind;
1358 const StringRef Namespace;
1359
1360 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1361 bool PragmaNameOnly = false) {
1362 switch (Kind) {
1363 case PPCallbacks::PMK_Message:
1364 return PragmaNameOnly ? "message" : "pragma message";
1365 case PPCallbacks::PMK_Warning:
1366 return PragmaNameOnly ? "warning" : "pragma warning";
1367 case PPCallbacks::PMK_Error:
1368 return PragmaNameOnly ? "error" : "pragma error";
1369 }
1370 llvm_unreachable("Unknown PragmaMessageKind!");
1371 }
1372
1373public:
1374 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1375 StringRef Namespace = StringRef())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001376 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
1377 Namespace(Namespace) {}
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001378
Craig Topper9140dd22014-03-11 06:50:42 +00001379 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1380 Token &Tok) override {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001381 SourceLocation MessageLoc = Tok.getLocation();
1382 PP.Lex(Tok);
1383 bool ExpectClosingParen = false;
1384 switch (Tok.getKind()) {
1385 case tok::l_paren:
1386 // We have a MSVC style pragma message.
1387 ExpectClosingParen = true;
1388 // Read the string.
1389 PP.Lex(Tok);
1390 break;
1391 case tok::string_literal:
1392 // We have a GCC style pragma message, and we just read the string.
1393 break;
1394 default:
1395 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1396 return;
1397 }
1398
1399 std::string MessageString;
1400 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1401 /*MacroExpansion=*/true))
1402 return;
1403
1404 if (ExpectClosingParen) {
1405 if (Tok.isNot(tok::r_paren)) {
1406 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1407 return;
1408 }
1409 PP.Lex(Tok); // eat the r_paren.
1410 }
1411
1412 if (Tok.isNot(tok::eod)) {
1413 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1414 return;
1415 }
1416
1417 // Output the message.
1418 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1419 ? diag::err_pragma_message
1420 : diag::warn_pragma_message) << MessageString;
1421
1422 // If the pragma is lexically sound, notify any interested PPCallbacks.
1423 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1424 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
Chris Lattner30c924b2010-06-26 17:11:39 +00001425 }
1426};
1427
Richard Smithc51c38b2017-04-29 00:34:47 +00001428/// Handle the clang \#pragma module import extension. The syntax is:
1429/// \code
1430/// #pragma clang module import some.module.name
1431/// \endcode
1432struct PragmaModuleImportHandler : public PragmaHandler {
1433 PragmaModuleImportHandler() : PragmaHandler("import") {}
1434
1435 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
Richard Smithd1386302017-05-04 00:29:54 +00001436 Token &Tok) override {
1437 SourceLocation ImportLoc = Tok.getLocation();
1438
1439 // Read the module name.
1440 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1441 ModuleName;
1442 if (LexModuleName(PP, Tok, ModuleName))
1443 return;
1444
1445 if (Tok.isNot(tok::eod))
1446 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1447
1448 // If we have a non-empty module path, load the named module.
1449 Module *Imported =
1450 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1451 /*IsIncludeDirective=*/false);
1452 if (!Imported)
1453 return;
1454
1455 PP.makeModuleVisible(Imported, ImportLoc);
1456 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1457 tok::annot_module_include, Imported);
1458 if (auto *CB = PP.getPPCallbacks())
1459 CB->moduleImport(ImportLoc, ModuleName, Imported);
1460 }
1461};
1462
1463/// Handle the clang \#pragma module begin extension. The syntax is:
1464/// \code
1465/// #pragma clang module begin some.module.name
1466/// ...
1467/// #pragma clang module end
1468/// \endcode
1469struct PragmaModuleBeginHandler : public PragmaHandler {
1470 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1471
1472 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1473 Token &Tok) override {
1474 SourceLocation BeginLoc = Tok.getLocation();
1475
1476 // Read the module name.
1477 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1478 ModuleName;
1479 if (LexModuleName(PP, Tok, ModuleName))
1480 return;
1481
1482 if (Tok.isNot(tok::eod))
1483 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1484
1485 // We can only enter submodules of the current module.
1486 StringRef Current = PP.getLangOpts().CurrentModule;
1487 if (ModuleName.front().first->getName() != Current) {
1488 PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1489 << ModuleName.front().first << (ModuleName.size() > 1)
1490 << Current.empty() << Current;
1491 return;
1492 }
1493
1494 // Find the module we're entering. We require that a module map for it
1495 // be loaded or implicitly loadable.
1496 // FIXME: We could create the submodule here. We'd need to know whether
1497 // it's supposed to be explicit, but not much else.
Richard Smith9565c75b2017-06-19 23:09:36 +00001498 Module *M = PP.getHeaderSearchInfo().lookupModule(Current);
Richard Smithd1386302017-05-04 00:29:54 +00001499 if (!M) {
1500 PP.Diag(ModuleName.front().second,
1501 diag::err_pp_module_begin_no_module_map) << Current;
1502 return;
1503 }
1504 for (unsigned I = 1; I != ModuleName.size(); ++I) {
1505 auto *NewM = M->findSubmodule(ModuleName[I].first->getName());
1506 if (!NewM) {
1507 PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1508 << M->getFullModuleName() << ModuleName[I].first;
1509 return;
1510 }
1511 M = NewM;
1512 }
1513
Richard Smith51d09c52017-05-30 05:22:59 +00001514 // If the module isn't available, it doesn't make sense to enter it.
Richard Smith27e5aa02017-06-05 18:57:56 +00001515 if (Preprocessor::checkModuleIsAvailable(
1516 PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
Richard Smith51d09c52017-05-30 05:22:59 +00001517 PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1518 << M->getTopLevelModuleName();
1519 return;
1520 }
1521
Richard Smithd1386302017-05-04 00:29:54 +00001522 // Enter the scope of the submodule.
1523 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1524 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1525 tok::annot_module_begin, M);
1526 }
1527};
1528
1529/// Handle the clang \#pragma module end extension.
1530struct PragmaModuleEndHandler : public PragmaHandler {
1531 PragmaModuleEndHandler() : PragmaHandler("end") {}
1532
1533 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1534 Token &Tok) override {
1535 SourceLocation Loc = Tok.getLocation();
1536
1537 PP.LexUnexpandedToken(Tok);
1538 if (Tok.isNot(tok::eod))
1539 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1540
1541 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1542 if (M)
1543 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1544 else
1545 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
Richard Smithc51c38b2017-04-29 00:34:47 +00001546 }
1547};
1548
Richard Smith5d2ed482017-06-09 19:22:32 +00001549/// Handle the clang \#pragma module build extension.
1550struct PragmaModuleBuildHandler : public PragmaHandler {
1551 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1552
1553 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1554 Token &Tok) override {
1555 PP.HandlePragmaModuleBuild(Tok);
1556 }
1557};
1558
1559/// Handle the clang \#pragma module load extension.
1560struct PragmaModuleLoadHandler : public PragmaHandler {
1561 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1562
1563 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1564 Token &Tok) override {
1565 SourceLocation Loc = 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 // Load the module, don't make it visible.
1577 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1578 /*IsIncludeDirective=*/false);
1579 }
1580};
1581
James Dennett18a6d792012-06-17 03:26:26 +00001582/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001583/// macro on the top of the stack.
1584struct PragmaPushMacroHandler : public PragmaHandler {
1585 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001586
Craig Topper9140dd22014-03-11 06:50:42 +00001587 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1588 Token &PushMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001589 PP.HandlePragmaPushMacro(PushMacroTok);
1590 }
1591};
1592
James Dennett18a6d792012-06-17 03:26:26 +00001593/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001594/// macro to the value on the top of the stack.
1595struct PragmaPopMacroHandler : public PragmaHandler {
1596 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001597
Craig Topper9140dd22014-03-11 06:50:42 +00001598 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1599 Token &PopMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001600 PP.HandlePragmaPopMacro(PopMacroTok);
1601 }
1602};
1603
John McCall32f5fe12011-09-30 05:12:12 +00001604/// PragmaARCCFCodeAuditedHandler -
James Dennett18a6d792012-06-17 03:26:26 +00001605/// \#pragma clang arc_cf_code_audited begin/end
John McCall32f5fe12011-09-30 05:12:12 +00001606struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1607 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001608
Craig Topper9140dd22014-03-11 06:50:42 +00001609 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1610 Token &NameTok) override {
John McCall32f5fe12011-09-30 05:12:12 +00001611 SourceLocation Loc = NameTok.getLocation();
1612 bool IsBegin;
1613
1614 Token Tok;
1615
1616 // Lex the 'begin' or 'end'.
1617 PP.LexUnexpandedToken(Tok);
1618 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1619 if (BeginEnd && BeginEnd->isStr("begin")) {
1620 IsBegin = true;
1621 } else if (BeginEnd && BeginEnd->isStr("end")) {
1622 IsBegin = false;
1623 } else {
1624 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1625 return;
1626 }
1627
1628 // Verify that this is followed by EOD.
1629 PP.LexUnexpandedToken(Tok);
1630 if (Tok.isNot(tok::eod))
1631 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1632
1633 // The start location of the active audit.
1634 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1635
1636 // The start location we want after processing this.
1637 SourceLocation NewLoc;
1638
1639 if (IsBegin) {
1640 // Complain about attempts to re-enter an audit.
1641 if (BeginLoc.isValid()) {
1642 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1643 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1644 }
1645 NewLoc = Loc;
1646 } else {
1647 // Complain about attempts to leave an audit that doesn't exist.
1648 if (!BeginLoc.isValid()) {
1649 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1650 return;
1651 }
1652 NewLoc = SourceLocation();
1653 }
1654
1655 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1656 }
1657};
1658
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001659/// PragmaAssumeNonNullHandler -
1660/// \#pragma clang assume_nonnull begin/end
1661struct PragmaAssumeNonNullHandler : public PragmaHandler {
1662 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001663
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001664 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1665 Token &NameTok) override {
1666 SourceLocation Loc = NameTok.getLocation();
1667 bool IsBegin;
1668
1669 Token Tok;
1670
1671 // Lex the 'begin' or 'end'.
1672 PP.LexUnexpandedToken(Tok);
1673 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1674 if (BeginEnd && BeginEnd->isStr("begin")) {
1675 IsBegin = true;
1676 } else if (BeginEnd && BeginEnd->isStr("end")) {
1677 IsBegin = false;
1678 } else {
1679 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1680 return;
1681 }
1682
1683 // Verify that this is followed by EOD.
1684 PP.LexUnexpandedToken(Tok);
1685 if (Tok.isNot(tok::eod))
1686 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1687
1688 // The start location of the active audit.
1689 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1690
1691 // The start location we want after processing this.
1692 SourceLocation NewLoc;
Eli Friedman16fee082017-09-27 23:29:37 +00001693 PPCallbacks *Callbacks = PP.getPPCallbacks();
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001694
1695 if (IsBegin) {
1696 // Complain about attempts to re-enter an audit.
1697 if (BeginLoc.isValid()) {
1698 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1699 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1700 }
1701 NewLoc = Loc;
Eli Friedman16fee082017-09-27 23:29:37 +00001702 if (Callbacks)
1703 Callbacks->PragmaAssumeNonNullBegin(NewLoc);
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001704 } else {
1705 // Complain about attempts to leave an audit that doesn't exist.
1706 if (!BeginLoc.isValid()) {
1707 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1708 return;
1709 }
1710 NewLoc = SourceLocation();
Eli Friedman16fee082017-09-27 23:29:37 +00001711 if (Callbacks)
1712 Callbacks->PragmaAssumeNonNullEnd(NewLoc);
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001713 }
1714
1715 PP.setPragmaAssumeNonNullLoc(NewLoc);
1716 }
1717};
1718
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001719/// \brief Handle "\#pragma region [...]"
1720///
1721/// The syntax is
1722/// \code
1723/// #pragma region [optional name]
1724/// #pragma endregion [optional comment]
1725/// \endcode
1726///
1727/// \note This is
1728/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1729/// pragma, just skipped by compiler.
1730struct PragmaRegionHandler : public PragmaHandler {
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001731 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
Aaron Ballman406ea512012-11-30 19:52:30 +00001732
Craig Topper9140dd22014-03-11 06:50:42 +00001733 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1734 Token &NameTok) override {
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001735 // #pragma region: endregion matches can be verified
1736 // __pragma(region): no sense, but ignored by msvc
1737 // _Pragma is not valid for MSVC, but there isn't any point
1738 // to handle a _Pragma differently.
1739 }
1740};
Aaron Ballman406ea512012-11-30 19:52:30 +00001741
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001742} // namespace
Chris Lattnerb694ba72006-07-02 22:41:36 +00001743
1744/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
James Dennett18a6d792012-06-17 03:26:26 +00001745/// \#pragma GCC poison/system_header/dependency and \#pragma once.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001746void Preprocessor::RegisterBuiltinPragmas() {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001747 AddPragmaHandler(new PragmaOnceHandler());
1748 AddPragmaHandler(new PragmaMarkHandler());
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001749 AddPragmaHandler(new PragmaPushMacroHandler());
1750 AddPragmaHandler(new PragmaPopMacroHandler());
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001751 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
Mike Stump11289f42009-09-09 15:08:12 +00001752
Chris Lattnerb61448d2009-05-12 18:21:11 +00001753 // #pragma GCC ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001754 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1755 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1756 AddPragmaHandler("GCC", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001757 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001758 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1759 "GCC"));
1760 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1761 "GCC"));
Chris Lattnerb61448d2009-05-12 18:21:11 +00001762 // #pragma clang ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001763 AddPragmaHandler("clang", new PragmaPoisonHandler());
1764 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001765 AddPragmaHandler("clang", new PragmaDebugHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001766 AddPragmaHandler("clang", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001767 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
John McCall32f5fe12011-09-30 05:12:12 +00001768 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001769 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
Chris Lattnerb61448d2009-05-12 18:21:11 +00001770
Richard Smithc51c38b2017-04-29 00:34:47 +00001771 // #pragma clang module ...
1772 auto *ModuleHandler = new PragmaNamespace("module");
1773 AddPragmaHandler("clang", ModuleHandler);
1774 ModuleHandler->AddPragma(new PragmaModuleImportHandler());
Richard Smithd1386302017-05-04 00:29:54 +00001775 ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
1776 ModuleHandler->AddPragma(new PragmaModuleEndHandler());
Richard Smith5d2ed482017-06-09 19:22:32 +00001777 ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
1778 ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
Matt Davis1edb9052018-01-27 00:25:29 +00001779
1780 // Add region pragmas.
1781 AddPragmaHandler(new PragmaRegionHandler("region"));
1782 AddPragmaHandler(new PragmaRegionHandler("endregion"));
Richard Smithc51c38b2017-04-29 00:34:47 +00001783
Chris Lattner2ff698d2009-01-16 08:21:25 +00001784 // MS extensions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001785 if (LangOpts.MicrosoftExt) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001786 AddPragmaHandler(new PragmaWarningHandler());
Aaron Ballman611306e2012-03-02 22:51:54 +00001787 AddPragmaHandler(new PragmaIncludeAliasHandler());
Chris Lattner30c924b2010-06-26 17:11:39 +00001788 }
John Brawn8e62db32016-04-04 14:22:58 +00001789
1790 // Pragmas added by plugins
1791 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1792 ie = PragmaHandlerRegistry::end();
1793 it != ie; ++it) {
1794 AddPragmaHandler(it->instantiate().release());
1795 }
Chris Lattnerb694ba72006-07-02 22:41:36 +00001796}
Lubos Lunak576a0412014-05-01 12:54:03 +00001797
1798/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1799/// warn about those pragmas being unknown.
1800void Preprocessor::IgnorePragmas() {
1801 AddPragmaHandler(new EmptyPragmaHandler());
1802 // Also ignore all pragmas in all namespaces created
1803 // in Preprocessor::RegisterBuiltinPragmas().
1804 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1805 AddPragmaHandler("clang", new EmptyPragmaHandler());
Lubos Lunak576a0412014-05-01 12:54:03 +00001806}