blob: 575935119f6f10a5a95e150ac72a08883c93a84b [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"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000034#include "clang/Lex/Token.h"
35#include "clang/Lex/TokenLexer.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/DenseMap.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000038#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000039#include "llvm/ADT/SmallString.h"
40#include "llvm/ADT/SmallVector.h"
Andrew V. Tischenkoc88deb12018-04-10 10:34:13 +000041#include "llvm/ADT/StringSwitch.h"
Nico Weberade321e2018-04-10 18:53:28 +000042#include "llvm/ADT/StringRef.h"
Andrew V. Tischenkoc88deb12018-04-10 10:34:13 +000043#include "llvm/Support/CrashRecoveryContext.h"
Nico Weberade321e2018-04-10 18:53:28 +000044#include "llvm/Support/Compiler.h"
Daniel Dunbarf2cf3292010-08-17 22:32:48 +000045#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000046#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000047#include <cassert>
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000048#include <cstddef>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000049#include <cstdint>
50#include <limits>
51#include <string>
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000052#include <utility>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000053#include <vector>
54
Chris Lattnerb8761832006-06-24 21:31:03 +000055using namespace clang;
56
57// Out-of-line destructor to provide a home for the class.
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000058PragmaHandler::~PragmaHandler() = default;
Chris Lattnerb8761832006-06-24 21:31:03 +000059
Chris Lattner2e155302006-07-03 05:34:41 +000060//===----------------------------------------------------------------------===//
Daniel Dunbard839e772010-06-11 20:10:12 +000061// EmptyPragmaHandler Implementation.
62//===----------------------------------------------------------------------===//
63
Hans Wennborg7357bbc2015-10-12 20:47:58 +000064EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000065
Fangrui Song6907ce22018-07-30 19:24:48 +000066void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
Douglas Gregorc7d65762010-09-09 22:45:38 +000067 PragmaIntroducerKind Introducer,
68 Token &FirstToken) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000069
70//===----------------------------------------------------------------------===//
Chris Lattner2e155302006-07-03 05:34:41 +000071// PragmaNamespace Implementation.
72//===----------------------------------------------------------------------===//
73
Chris Lattner2e155302006-07-03 05:34:41 +000074PragmaNamespace::~PragmaNamespace() {
Reid Kleckner588c9372014-02-19 23:44:52 +000075 llvm::DeleteContainerSeconds(Handlers);
Chris Lattner2e155302006-07-03 05:34:41 +000076}
77
78/// FindHandler - Check to see if there is already a handler for the
79/// specified name. If not, return the handler for the null identifier if it
80/// exists, otherwise return null. If IgnoreNull is true (the default) then
81/// the null handler isn't returned on failure to match.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000082PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
Chris Lattner2e155302006-07-03 05:34:41 +000083 bool IgnoreNull) const {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000084 if (PragmaHandler *Handler = Handlers.lookup(Name))
85 return Handler;
Craig Topperd2d442c2014-05-17 23:10:59 +000086 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000087}
Mike Stump11289f42009-09-09 15:08:12 +000088
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000089void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
90 assert(!Handlers.lookup(Handler->getName()) &&
91 "A handler with this name is already registered in this namespace");
David Blaikie13156b62014-11-19 03:06:06 +000092 Handlers[Handler->getName()] = Handler;
Chris Lattner2e155302006-07-03 05:34:41 +000093}
94
Daniel Dunbar40596532008-10-04 19:17:46 +000095void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000096 assert(Handlers.lookup(Handler->getName()) &&
97 "Handler not registered in this namespace");
98 Handlers.erase(Handler->getName());
Daniel Dunbar40596532008-10-04 19:17:46 +000099}
100
Fangrui Song6907ce22018-07-30 19:24:48 +0000101void PragmaNamespace::HandlePragma(Preprocessor &PP,
Douglas Gregorc7d65762010-09-09 22:45:38 +0000102 PragmaIntroducerKind Introducer,
103 Token &Tok) {
Chris Lattnerb8761832006-06-24 21:31:03 +0000104 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
105 // expand it, the user can have a STDC #define, that should not affect this.
106 PP.LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000107
Chris Lattnerb8761832006-06-24 21:31:03 +0000108 // Get the handler for this token. If there is no handler, ignore the pragma.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000109 PragmaHandler *Handler
110 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000111 : StringRef(),
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000112 /*IgnoreNull=*/false);
Craig Topperd2d442c2014-05-17 23:10:59 +0000113 if (!Handler) {
Chris Lattner21656f22009-04-19 21:10:26 +0000114 PP.Diag(Tok, diag::warn_pragma_ignored);
115 return;
116 }
Mike Stump11289f42009-09-09 15:08:12 +0000117
Chris Lattnerb8761832006-06-24 21:31:03 +0000118 // Otherwise, pass it down.
Douglas Gregorc7d65762010-09-09 22:45:38 +0000119 Handler->HandlePragma(PP, Introducer, Tok);
Chris Lattnerb8761832006-06-24 21:31:03 +0000120}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000121
Chris Lattnerb694ba72006-07-02 22:41:36 +0000122//===----------------------------------------------------------------------===//
123// Preprocessor Pragma Directive Handling.
124//===----------------------------------------------------------------------===//
125
James Dennett18a6d792012-06-17 03:26:26 +0000126/// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
Chris Lattnerb694ba72006-07-02 22:41:36 +0000127/// rest of the pragma, passing it to the registered pragma handlers.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000128void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
129 PragmaIntroducerKind Introducer) {
130 if (Callbacks)
131 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
132
Jordan Rosede1a2922012-06-08 18:06:21 +0000133 if (!PragmasEnabled)
134 return;
135
Chris Lattnerb694ba72006-07-02 22:41:36 +0000136 ++NumPragma;
Mike Stump11289f42009-09-09 15:08:12 +0000137
Chris Lattnerb694ba72006-07-02 22:41:36 +0000138 // Invoke the first level of pragma handlers which reads the namespace id.
Chris Lattner146762e2007-07-20 16:59:19 +0000139 Token Tok;
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000140 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Chris Lattnerb694ba72006-07-02 22:41:36 +0000142 // If the pragma handler didn't read the rest of the line, consume it now.
Fangrui Song6907ce22018-07-30 19:24:48 +0000143 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000144 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000145 DiscardUntilEndOfDirective();
146}
147
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000148namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000149
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000150/// Helper class for \see Preprocessor::Handle_Pragma.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000151class LexingFor_PragmaRAII {
152 Preprocessor &PP;
153 bool InMacroArgPreExpansion;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000154 bool Failed = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000155 Token &OutTok;
156 Token PragmaTok;
157
158public:
159 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
160 Token &Tok)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000161 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion), OutTok(Tok) {
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000162 if (InMacroArgPreExpansion) {
163 PragmaTok = OutTok;
164 PP.EnableBacktrackAtThisPos();
165 }
166 }
167
168 ~LexingFor_PragmaRAII() {
169 if (InMacroArgPreExpansion) {
Alex Lorenz24a1bed2017-02-24 17:45:16 +0000170 // When committing/backtracking the cached pragma tokens in a macro
171 // argument pre-expansion we want to ensure that either the tokens which
172 // have been committed will be removed from the cache or that the tokens
173 // over which we just backtracked won't remain in the cache after they're
174 // consumed and that the caching will stop after consuming them.
175 // Otherwise the caching will interfere with the way macro expansion
176 // works, because we will continue to cache tokens after consuming the
177 // backtracked tokens, which shouldn't happen when we're dealing with
178 // macro argument pre-expansion.
179 auto CachedTokenRange = PP.LastCachedTokenRange();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000180 if (Failed) {
181 PP.CommitBacktrackedTokens();
182 } else {
183 PP.Backtrack();
184 OutTok = PragmaTok;
185 }
Alex Lorenz24a1bed2017-02-24 17:45:16 +0000186 PP.EraseCachedTokens(CachedTokenRange);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000187 }
188 }
189
190 void failed() {
191 Failed = true;
192 }
193};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000194
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000195} // namespace
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000196
Chris Lattnerb694ba72006-07-02 22:41:36 +0000197/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
198/// return the first token after the directive. The _Pragma token has just
199/// been read into 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +0000200void Preprocessor::Handle_Pragma(Token &Tok) {
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000201 // This works differently if we are pre-expanding a macro argument.
202 // In that case we don't actually "activate" the pragma now, we only lex it
203 // until we are sure it is lexically correct and then we backtrack so that
204 // we activate the pragma whenever we encounter the tokens again in the token
205 // stream. This ensures that we will activate it in the correct location
206 // or that we will ignore it if it never enters the token stream, e.g:
207 //
208 // #define EMPTY(x)
209 // #define INACTIVE(x) EMPTY(x)
210 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
211
212 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
213
Chris Lattnerb694ba72006-07-02 22:41:36 +0000214 // Remember the pragma token location.
215 SourceLocation PragmaLoc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattnerb694ba72006-07-02 22:41:36 +0000217 // Read the '('.
218 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000219 if (Tok.isNot(tok::l_paren)) {
220 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000221 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000222 }
Chris Lattnerb694ba72006-07-02 22:41:36 +0000223
224 // Read the '"..."'.
225 Lex(Tok);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000226 if (!tok::isStringLiteral(Tok.getKind())) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000227 Diag(PragmaLoc, diag::err__Pragma_malformed);
Hubert Tong0deb6942015-07-30 21:30:00 +0000228 // Skip bad tokens, and the ')', if present.
Reid Kleckner53e6a5d2014-08-14 19:47:06 +0000229 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
Richard Smithd67aea22012-03-06 03:21:47 +0000230 Lex(Tok);
Hubert Tong0deb6942015-07-30 21:30:00 +0000231 while (Tok.isNot(tok::r_paren) &&
232 !Tok.isAtStartOfLine() &&
233 Tok.isNot(tok::eof))
234 Lex(Tok);
Richard Smithd67aea22012-03-06 03:21:47 +0000235 if (Tok.is(tok::r_paren))
236 Lex(Tok);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000237 return _PragmaLexing.failed();
Richard Smithd67aea22012-03-06 03:21:47 +0000238 }
239
240 if (Tok.hasUDSuffix()) {
241 Diag(Tok, diag::err_invalid_string_udl);
242 // Skip this token, and the ')', if present.
243 Lex(Tok);
244 if (Tok.is(tok::r_paren))
245 Lex(Tok);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000246 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000247 }
Mike Stump11289f42009-09-09 15:08:12 +0000248
Chris Lattnerb694ba72006-07-02 22:41:36 +0000249 // Remember the string.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000250 Token StrTok = Tok;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000251
252 // Read the ')'.
253 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000254 if (Tok.isNot(tok::r_paren)) {
255 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000256 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000257 }
Mike Stump11289f42009-09-09 15:08:12 +0000258
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000259 if (InMacroArgPreExpansion)
260 return;
261
Chris Lattner9dc9c202009-02-15 20:52:18 +0000262 SourceLocation RParenLoc = Tok.getLocation();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000263 std::string StrVal = getSpelling(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000264
Richard Smithc98bb4e2013-03-09 23:30:15 +0000265 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
266 // "The string literal is destringized by deleting any encoding prefix,
Chris Lattner262d4e32009-01-16 18:59:23 +0000267 // deleting the leading and trailing double-quotes, replacing each escape
268 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
269 // single backslash."
Richard Smithc98bb4e2013-03-09 23:30:15 +0000270 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
271 (StrVal[0] == 'u' && StrVal[1] != '8'))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000272 StrVal.erase(StrVal.begin());
Richard Smithc98bb4e2013-03-09 23:30:15 +0000273 else if (StrVal[0] == 'u')
274 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
275
276 if (StrVal[0] == 'R') {
277 // FIXME: C++11 does not specify how to handle raw-string-literals here.
278 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
279 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
280 "Invalid raw string token!");
281
282 // Measure the length of the d-char-sequence.
283 unsigned NumDChars = 0;
284 while (StrVal[2 + NumDChars] != '(') {
285 assert(NumDChars < (StrVal.size() - 5) / 2 &&
286 "Invalid raw string token!");
287 ++NumDChars;
288 }
289 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
290
291 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
292 // parens below.
293 StrVal.erase(0, 2 + NumDChars);
294 StrVal.erase(StrVal.size() - 1 - NumDChars);
295 } else {
296 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
297 "Invalid string token!");
298
299 // Remove escaped quotes and escapes.
Benjamin Kramerc2f5f292013-05-04 10:37:20 +0000300 unsigned ResultPos = 1;
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000301 for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
Reid Kleckner95e036c2013-09-25 16:42:48 +0000302 // Skip escapes. \\ -> '\' and \" -> '"'.
303 if (StrVal[i] == '\\' && i + 1 < e &&
304 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
305 ++i;
306 StrVal[ResultPos++] = StrVal[i];
Richard Smithc98bb4e2013-03-09 23:30:15 +0000307 }
Reid Kleckner95e036c2013-09-25 16:42:48 +0000308 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000309 }
Mike Stump11289f42009-09-09 15:08:12 +0000310
Chris Lattnerb694ba72006-07-02 22:41:36 +0000311 // Remove the front quote, replacing it with a space, so that the pragma
312 // contents appear to have a space before them.
313 StrVal[0] = ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000314
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000315 // Replace the terminating quote with a \n.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000316 StrVal[StrVal.size()-1] = '\n';
Mike Stump11289f42009-09-09 15:08:12 +0000317
Peter Collingbournef29ce972011-02-22 13:49:06 +0000318 // Plop the string (including the newline and trailing null) into a buffer
319 // where we can lex it.
320 Token TmpTok;
321 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000322 CreateString(StrVal, TmpTok);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000323 SourceLocation TokLoc = TmpTok.getLocation();
324
325 // Make and enter a lexer object so that we lex and expand the tokens just
326 // like any others.
327 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
328 StrVal.size(), *this);
329
Craig Topperd2d442c2014-05-17 23:10:59 +0000330 EnterSourceFileWithLexer(TL, nullptr);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000331
332 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000333 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
John McCall89e925d2010-08-28 22:34:47 +0000334
335 // Finally, return whatever came after the pragma directive.
336 return Lex(Tok);
337}
338
339/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
340/// is not enclosed within a string literal.
341void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
342 // Remember the pragma token location.
343 SourceLocation PragmaLoc = Tok.getLocation();
344
345 // Read the '('.
346 Lex(Tok);
347 if (Tok.isNot(tok::l_paren)) {
348 Diag(PragmaLoc, diag::err__Pragma_malformed);
349 return;
350 }
351
Peter Collingbournef29ce972011-02-22 13:49:06 +0000352 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000353 SmallVector<Token, 32> PragmaToks;
John McCall89e925d2010-08-28 22:34:47 +0000354 int NumParens = 0;
355 Lex(Tok);
356 while (Tok.isNot(tok::eof)) {
Peter Collingbournef29ce972011-02-22 13:49:06 +0000357 PragmaToks.push_back(Tok);
John McCall89e925d2010-08-28 22:34:47 +0000358 if (Tok.is(tok::l_paren))
359 NumParens++;
360 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
361 break;
John McCall89e925d2010-08-28 22:34:47 +0000362 Lex(Tok);
363 }
364
John McCall49039d42010-08-29 01:09:54 +0000365 if (Tok.is(tok::eof)) {
366 Diag(PragmaLoc, diag::err_unterminated___pragma);
367 return;
368 }
369
Peter Collingbournef29ce972011-02-22 13:49:06 +0000370 PragmaToks.front().setFlag(Token::LeadingSpace);
John McCall89e925d2010-08-28 22:34:47 +0000371
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000372 // Replace the ')' with an EOD to mark the end of the pragma.
373 PragmaToks.back().setKind(tok::eod);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000374
375 Token *TokArray = new Token[PragmaToks.size()];
376 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
377
378 // Push the tokens onto the stack.
379 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
380
381 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000382 HandlePragmaDirective(PragmaLoc, PIK___pragma);
John McCall89e925d2010-08-28 22:34:47 +0000383
384 // Finally, return whatever came after the pragma directive.
385 return Lex(Tok);
386}
387
James Dennett18a6d792012-06-17 03:26:26 +0000388/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
Chris Lattner146762e2007-07-20 16:59:19 +0000389void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
Sunil Srivastavafe583272016-07-25 17:17:06 +0000390 // Don't honor the 'once' when handling the primary source file, unless
Erik Verbruggene0bde752016-10-27 14:17:10 +0000391 // this is a prefix to a TU, which indicates we're generating a PCH file, or
392 // when the main file is a header (e.g. when -xc-header is provided on the
393 // commandline).
394 if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000395 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
396 return;
397 }
Mike Stump11289f42009-09-09 15:08:12 +0000398
Chris Lattnerb694ba72006-07-02 22:41:36 +0000399 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000400 // Mark the file as a once-only file now.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000401 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
Chris Lattnerb694ba72006-07-02 22:41:36 +0000402}
403
Chris Lattnerc2383312007-12-19 19:38:36 +0000404void Preprocessor::HandlePragmaMark() {
Ted Kremenek76c34412008-11-19 22:21:33 +0000405 assert(CurPPLexer && "No current lexer?");
Erich Keane0a6b5b62018-12-04 14:34:09 +0000406 CurLexer->ReadToEndOfLine();
Chris Lattnerc2383312007-12-19 19:38:36 +0000407}
408
James Dennett18a6d792012-06-17 03:26:26 +0000409/// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
Erik Verbruggen851ce0e2016-10-26 11:46:10 +0000410void Preprocessor::HandlePragmaPoison() {
Chris Lattner146762e2007-07-20 16:59:19 +0000411 Token Tok;
Chris Lattner538d7f32006-07-20 04:31:52 +0000412
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000413 while (true) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000414 // Read the next token to poison. While doing this, pretend that we are
415 // skipping while reading the identifier to poison.
416 // This avoids errors on code like:
417 // #pragma GCC poison X
418 // #pragma GCC poison X
Ted Kremenek551c82a2008-11-18 01:12:54 +0000419 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000420 LexUnexpandedToken(Tok);
Ted Kremenek551c82a2008-11-18 01:12:54 +0000421 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000422
Chris Lattnerb694ba72006-07-02 22:41:36 +0000423 // If we reached the end of line, we're done.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000424 if (Tok.is(tok::eod)) return;
Mike Stump11289f42009-09-09 15:08:12 +0000425
Chris Lattnerb694ba72006-07-02 22:41:36 +0000426 // Can only poison identifiers.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000427 if (Tok.isNot(tok::raw_identifier)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000428 Diag(Tok, diag::err_pp_invalid_poison);
429 return;
430 }
Mike Stump11289f42009-09-09 15:08:12 +0000431
Chris Lattnercefc7682006-07-08 08:28:12 +0000432 // Look up the identifier info for the token. We disabled identifier lookup
433 // by saying we're skipping contents, so we need to do this manually.
434 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000435
Chris Lattnerb694ba72006-07-02 22:41:36 +0000436 // Already poisoned.
437 if (II->isPoisoned()) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000438
Chris Lattnerb694ba72006-07-02 22:41:36 +0000439 // If this is a macro identifier, emit a warning.
Richard Smith20e883e2015-04-29 23:20:19 +0000440 if (isMacroDefined(II))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000441 Diag(Tok, diag::pp_poisoning_existing_macro);
Mike Stump11289f42009-09-09 15:08:12 +0000442
Chris Lattnerb694ba72006-07-02 22:41:36 +0000443 // Finally, poison it!
444 II->setIsPoisoned();
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000445 if (II->isFromAST())
446 II->setChangedSinceDeserialization();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000447 }
448}
449
James Dennett18a6d792012-06-17 03:26:26 +0000450/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
Chris Lattnerb694ba72006-07-02 22:41:36 +0000451/// that the whole directive has been parsed.
Chris Lattner146762e2007-07-20 16:59:19 +0000452void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000453 if (isInPrimaryFile()) {
454 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
455 return;
456 }
Mike Stump11289f42009-09-09 15:08:12 +0000457
Chris Lattnerb694ba72006-07-02 22:41:36 +0000458 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Ted Kremenek300590b2008-11-20 01:45:11 +0000459 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump11289f42009-09-09 15:08:12 +0000460
Chris Lattnerb694ba72006-07-02 22:41:36 +0000461 // Mark the file as a system header.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000462 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
Mike Stump11289f42009-09-09 15:08:12 +0000463
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000464 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000465 if (PLoc.isInvalid())
466 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000467
Jay Foad9a6b0982011-06-21 15:13:30 +0000468 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
Mike Stump11289f42009-09-09 15:08:12 +0000469
Chris Lattner3bdc7672011-05-22 22:10:16 +0000470 // Notify the client, if desired, that we are in a new source file.
471 if (Callbacks)
472 Callbacks->FileChanged(SysHeaderTok.getLocation(),
473 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
474
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000475 // Emit a line marker. This will change any source locations from this point
476 // forward to realize they are in a system header.
477 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +0000478 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
Jordan Rose111c4a62013-04-17 19:09:18 +0000479 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
Reid Klecknereb00ee02017-05-22 21:42:58 +0000480 SrcMgr::C_System);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000481}
482
James Dennett18a6d792012-06-17 03:26:26 +0000483/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
Chris Lattner146762e2007-07-20 16:59:19 +0000484void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
485 Token FilenameTok;
Ted Kremenek551c82a2008-11-18 01:12:54 +0000486 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000487
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000488 // If the token kind is EOD, the error has already been diagnosed.
489 if (FilenameTok.is(tok::eod))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000490 return;
Mike Stump11289f42009-09-09 15:08:12 +0000491
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000492 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000493 SmallString<128> FilenameBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +0000494 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000495 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +0000496 if (Invalid)
497 return;
Mike Stump11289f42009-09-09 15:08:12 +0000498
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000499 bool isAngled =
500 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000501 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
502 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000503 if (Filename.empty())
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000504 return;
Mike Stump11289f42009-09-09 15:08:12 +0000505
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000506 // Search include directories for this file.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000507 const DirectoryLookup *CurDir;
Richard Smith25d50752014-10-20 00:15:49 +0000508 const FileEntry *File =
509 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000510 nullptr, CurDir, nullptr, nullptr, nullptr, nullptr);
Craig Topperd2d442c2014-05-17 23:10:59 +0000511 if (!File) {
Eli Friedman3781a362011-08-30 23:07:51 +0000512 if (!SuppressIncludeNotFoundError)
513 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +0000514 return;
515 }
Mike Stump11289f42009-09-09 15:08:12 +0000516
Chris Lattnerd32480d2009-01-17 06:22:33 +0000517 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000518
519 // If this file is older than the file it depends on, emit a diagnostic.
520 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
521 // Lex tokens at the end of the message and include them in the message.
522 std::string Message;
523 Lex(DependencyTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000524 while (DependencyTok.isNot(tok::eod)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000525 Message += getSpelling(DependencyTok) + " ";
526 Lex(DependencyTok);
527 }
Mike Stump11289f42009-09-09 15:08:12 +0000528
Chris Lattnerf0b04972010-09-05 23:16:09 +0000529 // Remove the trailing ' ' if present.
530 if (!Message.empty())
531 Message.erase(Message.end()-1);
Chris Lattner97b8e842008-11-18 08:02:48 +0000532 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000533 }
534}
535
Reid Kleckner002562a2013-05-06 21:02:12 +0000536/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000537/// Return the IdentifierInfo* associated with the macro to push or pop.
538IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
539 // Remember the pragma token location.
540 Token PragmaTok = Tok;
541
542 // Read the '('.
543 Lex(Tok);
544 if (Tok.isNot(tok::l_paren)) {
545 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
546 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000547 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000548 }
549
550 // Read the macro name string.
551 Lex(Tok);
552 if (Tok.isNot(tok::string_literal)) {
553 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
554 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000555 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000556 }
557
Richard Smithd67aea22012-03-06 03:21:47 +0000558 if (Tok.hasUDSuffix()) {
559 Diag(Tok, diag::err_invalid_string_udl);
Craig Topperd2d442c2014-05-17 23:10:59 +0000560 return nullptr;
Richard Smithd67aea22012-03-06 03:21:47 +0000561 }
562
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000563 // Remember the macro string.
564 std::string StrVal = getSpelling(Tok);
565
566 // Read the ')'.
567 Lex(Tok);
568 if (Tok.isNot(tok::r_paren)) {
569 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
570 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000571 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000572 }
573
574 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
575 "Invalid string token!");
576
577 // Create a Token from the string.
578 Token MacroTok;
579 MacroTok.startToken();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000580 MacroTok.setKind(tok::raw_identifier);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000581 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000582
583 // Get the IdentifierInfo of MacroToPushTok.
584 return LookUpIdentifierInfo(MacroTok);
585}
586
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000587/// Handle \#pragma push_macro.
James Dennett18a6d792012-06-17 03:26:26 +0000588///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000589/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000590/// \code
Dmitri Gribenko9ebd1612012-11-30 20:04:39 +0000591/// #pragma push_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000592/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000593void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
594 // Parse the pragma directive and get the macro IdentifierInfo*.
595 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
596 if (!IdentInfo) return;
597
598 // Get the MacroInfo associated with IdentInfo.
599 MacroInfo *MI = getMacroInfo(IdentInfo);
Fangrui Song6907ce22018-07-30 19:24:48 +0000600
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000601 if (MI) {
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000602 // Allow the original MacroInfo to be redefined later.
603 MI->setIsAllowRedefinitionsWithoutWarning(true);
604 }
605
606 // Push the cloned MacroInfo so we can retrieve it later.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +0000607 PragmaPushMacroInfo[IdentInfo].push_back(MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000608}
609
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000610/// Handle \#pragma pop_macro.
James Dennett18a6d792012-06-17 03:26:26 +0000611///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000612/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000613/// \code
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000614/// #pragma pop_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000615/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000616void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
617 SourceLocation MessageLoc = PopMacroTok.getLocation();
618
619 // Parse the pragma directive and get the macro IdentifierInfo*.
620 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
621 if (!IdentInfo) return;
622
623 // Find the vector<MacroInfo*> associated with the macro.
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000624 llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter =
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000625 PragmaPushMacroInfo.find(IdentInfo);
626 if (iter != PragmaPushMacroInfo.end()) {
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000627 // Forget the MacroInfo currently associated with IdentInfo.
Richard Smith20e883e2015-04-29 23:20:19 +0000628 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000629 if (MI->isWarnIfUnused())
630 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
631 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000632 }
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000633
634 // Get the MacroInfo we want to reinstall.
635 MacroInfo *MacroToReInstall = iter->second.back();
636
Richard Smith713369b2015-04-23 20:40:50 +0000637 if (MacroToReInstall)
Alexander Kornienkoc0b49282012-08-29 16:56:24 +0000638 // Reinstall the previously pushed macro.
Richard Smith713369b2015-04-23 20:40:50 +0000639 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000640
641 // Pop PragmaPushMacroInfo stack.
642 iter->second.pop_back();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000643 if (iter->second.empty())
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000644 PragmaPushMacroInfo.erase(iter);
645 } else {
646 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
647 << IdentInfo->getName();
648 }
649}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000650
Aaron Ballman611306e2012-03-02 22:51:54 +0000651void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000652 // We will either get a quoted filename or a bracketed filename, and we
Aaron Ballman611306e2012-03-02 22:51:54 +0000653 // have to track which we got. The first filename is the source name,
654 // and the second name is the mapped filename. If the first is quoted,
655 // the second must be as well (cannot mix and match quotes and brackets).
Aaron Ballman611306e2012-03-02 22:51:54 +0000656
657 // Get the open paren
658 Lex(Tok);
659 if (Tok.isNot(tok::l_paren)) {
660 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
661 return;
662 }
663
664 // We expect either a quoted string literal, or a bracketed name
665 Token SourceFilenameTok;
666 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
667 if (SourceFilenameTok.is(tok::eod)) {
668 // The diagnostic has already been handled
669 return;
670 }
671
672 StringRef SourceFileName;
673 SmallString<128> FileNameBuffer;
Fangrui Song6907ce22018-07-30 19:24:48 +0000674 if (SourceFilenameTok.is(tok::string_literal) ||
Aaron Ballman611306e2012-03-02 22:51:54 +0000675 SourceFilenameTok.is(tok::angle_string_literal)) {
676 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
677 } else if (SourceFilenameTok.is(tok::less)) {
678 // This could be a path instead of just a name
679 FileNameBuffer.push_back('<');
680 SourceLocation End;
681 if (ConcatenateIncludeName(FileNameBuffer, End))
682 return; // Diagnostic already emitted
Yaron Keren92e1b622015-03-18 10:17:07 +0000683 SourceFileName = FileNameBuffer;
Aaron Ballman611306e2012-03-02 22:51:54 +0000684 } else {
685 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
686 return;
687 }
688 FileNameBuffer.clear();
689
690 // Now we expect a comma, followed by another include name
691 Lex(Tok);
692 if (Tok.isNot(tok::comma)) {
693 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
694 return;
695 }
696
697 Token ReplaceFilenameTok;
698 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
699 if (ReplaceFilenameTok.is(tok::eod)) {
700 // The diagnostic has already been handled
701 return;
702 }
703
704 StringRef ReplaceFileName;
Fangrui Song6907ce22018-07-30 19:24:48 +0000705 if (ReplaceFilenameTok.is(tok::string_literal) ||
Aaron Ballman611306e2012-03-02 22:51:54 +0000706 ReplaceFilenameTok.is(tok::angle_string_literal)) {
707 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
708 } else if (ReplaceFilenameTok.is(tok::less)) {
709 // This could be a path instead of just a name
710 FileNameBuffer.push_back('<');
711 SourceLocation End;
712 if (ConcatenateIncludeName(FileNameBuffer, End))
713 return; // Diagnostic already emitted
Yaron Keren92e1b622015-03-18 10:17:07 +0000714 ReplaceFileName = FileNameBuffer;
Aaron Ballman611306e2012-03-02 22:51:54 +0000715 } else {
716 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
717 return;
718 }
719
720 // Finally, we expect the closing paren
721 Lex(Tok);
722 if (Tok.isNot(tok::r_paren)) {
723 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
724 return;
725 }
726
727 // Now that we have the source and target filenames, we need to make sure
728 // they're both of the same type (angled vs non-angled)
729 StringRef OriginalSource = SourceFileName;
730
Fangrui Song6907ce22018-07-30 19:24:48 +0000731 bool SourceIsAngled =
732 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
Aaron Ballman611306e2012-03-02 22:51:54 +0000733 SourceFileName);
734 bool ReplaceIsAngled =
735 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
736 ReplaceFileName);
737 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
738 (SourceIsAngled != ReplaceIsAngled)) {
739 unsigned int DiagID;
740 if (SourceIsAngled)
741 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
742 else
743 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
744
745 Diag(SourceFilenameTok.getLocation(), DiagID)
Fangrui Song6907ce22018-07-30 19:24:48 +0000746 << SourceFileName
Aaron Ballman611306e2012-03-02 22:51:54 +0000747 << ReplaceFileName;
748
749 return;
750 }
751
752 // Now we can let the include handler know about this mapping
753 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
754}
755
Richard Smith9565c75b2017-06-19 23:09:36 +0000756// Lex a component of a module name: either an identifier or a string literal;
757// for components that can be expressed both ways, the two forms are equivalent.
758static bool LexModuleNameComponent(
759 Preprocessor &PP, Token &Tok,
760 std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent,
761 bool First) {
762 PP.LexUnexpandedToken(Tok);
763 if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
764 StringLiteralParser Literal(Tok, PP);
765 if (Literal.hadError)
766 return true;
767 ModuleNameComponent = std::make_pair(
768 PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation());
769 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
770 ModuleNameComponent =
771 std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
772 } else {
773 PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
774 return true;
775 }
776 return false;
777}
778
779static bool LexModuleName(
780 Preprocessor &PP, Token &Tok,
781 llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
782 &ModuleName) {
783 while (true) {
784 std::pair<IdentifierInfo*, SourceLocation> NameComponent;
785 if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
786 return true;
787 ModuleName.push_back(NameComponent);
788
789 PP.LexUnexpandedToken(Tok);
790 if (Tok.isNot(tok::period))
791 return false;
792 }
793}
794
Richard Smith5d2ed482017-06-09 19:22:32 +0000795void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
796 SourceLocation Loc = Tok.getLocation();
797
Richard Smith9565c75b2017-06-19 23:09:36 +0000798 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
799 if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
Richard Smith5d2ed482017-06-09 19:22:32 +0000800 return;
Richard Smith9565c75b2017-06-19 23:09:36 +0000801 IdentifierInfo *ModuleName = ModuleNameLoc.first;
Richard Smith5d2ed482017-06-09 19:22:32 +0000802
803 LexUnexpandedToken(Tok);
804 if (Tok.isNot(tok::eod)) {
805 Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
806 DiscardUntilEndOfDirective();
807 }
808
Richard Smith5d2ed482017-06-09 19:22:32 +0000809 CurLexer->LexingRawMode = true;
810
811 auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
812 if (Tok.getKind() != tok::raw_identifier ||
813 Tok.getRawIdentifier() != Ident)
814 return false;
815 CurLexer->Lex(Tok);
816 return true;
817 };
818
819 // Scan forward looking for the end of the module.
820 const char *Start = CurLexer->getBufferLocation();
821 const char *End = nullptr;
822 unsigned NestingLevel = 1;
823 while (true) {
824 End = CurLexer->getBufferLocation();
825 CurLexer->Lex(Tok);
826
827 if (Tok.is(tok::eof)) {
828 Diag(Loc, diag::err_pp_module_build_missing_end);
829 break;
830 }
831
832 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
833 // Token was part of module; keep going.
834 continue;
835 }
836
837 // We hit something directive-shaped; check to see if this is the end
838 // of the module build.
839 CurLexer->ParsingPreprocessorDirective = true;
840 CurLexer->Lex(Tok);
841 if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
842 TryConsumeIdentifier("module")) {
843 if (TryConsumeIdentifier("build"))
844 // #pragma clang module build -> entering a nested module build.
845 ++NestingLevel;
846 else if (TryConsumeIdentifier("endbuild")) {
847 // #pragma clang module endbuild -> leaving a module build.
848 if (--NestingLevel == 0)
849 break;
850 }
851 // We should either be looking at the EOD or more of the current directive
852 // preceding the EOD. Either way we can ignore this token and keep going.
853 assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
854 }
855 }
856
857 CurLexer->LexingRawMode = false;
858
859 // Load the extracted text as a preprocessed module.
860 assert(CurLexer->getBuffer().begin() <= Start &&
861 Start <= CurLexer->getBuffer().end() &&
862 CurLexer->getBuffer().begin() <= End &&
863 End <= CurLexer->getBuffer().end() &&
864 "module source range not contained within same file buffer");
865 TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(),
866 StringRef(Start, End - Start));
867}
868
Mike Rice58df1af2018-09-11 17:10:44 +0000869void Preprocessor::HandlePragmaHdrstop(Token &Tok) {
870 Lex(Tok);
871 if (Tok.is(tok::l_paren)) {
872 Diag(Tok.getLocation(), diag::warn_pp_hdrstop_filename_ignored);
873
874 std::string FileName;
875 if (!LexStringLiteral(Tok, FileName, "pragma hdrstop", false))
876 return;
877
878 if (Tok.isNot(tok::r_paren)) {
879 Diag(Tok, diag::err_expected) << tok::r_paren;
880 return;
881 }
882 Lex(Tok);
883 }
884 if (Tok.isNot(tok::eod))
885 Diag(Tok.getLocation(), diag::ext_pp_extra_tokens_at_eol)
886 << "pragma hdrstop";
887
888 if (creatingPCHWithPragmaHdrStop() &&
889 SourceMgr.isInMainFile(Tok.getLocation())) {
890 assert(CurLexer && "no lexer for #pragma hdrstop processing");
891 Token &Result = Tok;
892 Result.startToken();
893 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
894 CurLexer->cutOffLexing();
895 }
896 if (usingPCHWithPragmaHdrStop())
897 SkippingUntilPragmaHdrStop = false;
898}
899
Chris Lattnerb694ba72006-07-02 22:41:36 +0000900/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
901/// If 'Namespace' is non-null, then it is a token required to exist on the
902/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000903void Preprocessor::AddPragmaHandler(StringRef Namespace,
Chris Lattnerb694ba72006-07-02 22:41:36 +0000904 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000905 PragmaNamespace *InsertNS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000906
Chris Lattnerb694ba72006-07-02 22:41:36 +0000907 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000908 if (!Namespace.empty()) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000909 // If there is already a pragma handler with the name of this namespace,
910 // we either have an error (directive with the same name as a namespace) or
911 // we already have the namespace to insert into.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000912 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000913 InsertNS = Existing->getIfNamespace();
Craig Topperd2d442c2014-05-17 23:10:59 +0000914 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
Chris Lattnerb694ba72006-07-02 22:41:36 +0000915 " handler with the same name!");
916 } else {
917 // Otherwise, this namespace doesn't exist yet, create and insert the
918 // handler for it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000919 InsertNS = new PragmaNamespace(Namespace);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000920 PragmaHandlers->AddPragma(InsertNS);
921 }
922 }
Mike Stump11289f42009-09-09 15:08:12 +0000923
Chris Lattnerb694ba72006-07-02 22:41:36 +0000924 // Check to make sure we don't already have a pragma for this identifier.
925 assert(!InsertNS->FindHandler(Handler->getName()) &&
926 "Pragma handler already exists for this identifier!");
927 InsertNS->AddPragma(Handler);
928}
929
Daniel Dunbar40596532008-10-04 19:17:46 +0000930/// RemovePragmaHandler - Remove the specific pragma handler from the
931/// preprocessor. If \arg Namespace is non-null, then it should be the
932/// namespace that \arg Handler was added to. It is an error to remove
933/// a handler that has not been registered.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000934void Preprocessor::RemovePragmaHandler(StringRef Namespace,
Daniel Dunbar40596532008-10-04 19:17:46 +0000935 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000936 PragmaNamespace *NS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000937
Daniel Dunbar40596532008-10-04 19:17:46 +0000938 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000939 if (!Namespace.empty()) {
940 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
Daniel Dunbar40596532008-10-04 19:17:46 +0000941 assert(Existing && "Namespace containing handler does not exist!");
942
943 NS = Existing->getIfNamespace();
944 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
945 }
946
947 NS->RemovePragmaHandler(Handler);
Mike Stump11289f42009-09-09 15:08:12 +0000948
Craig Topperbe250302014-09-12 05:19:24 +0000949 // If this is a non-default namespace and it is now empty, remove it.
950 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
Daniel Dunbar40596532008-10-04 19:17:46 +0000951 PragmaHandlers->RemovePragmaHandler(NS);
Argyrios Kyrtzidis7ce75262012-01-06 00:22:09 +0000952 delete NS;
953 }
Daniel Dunbar40596532008-10-04 19:17:46 +0000954}
955
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000956bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
957 Token Tok;
958 LexUnexpandedToken(Tok);
959
960 if (Tok.isNot(tok::identifier)) {
961 Diag(Tok, diag::ext_on_off_switch_syntax);
962 return true;
963 }
964 IdentifierInfo *II = Tok.getIdentifierInfo();
965 if (II->isStr("ON"))
966 Result = tok::OOS_ON;
967 else if (II->isStr("OFF"))
968 Result = tok::OOS_OFF;
969 else if (II->isStr("DEFAULT"))
970 Result = tok::OOS_DEFAULT;
971 else {
972 Diag(Tok, diag::ext_on_off_switch_syntax);
973 return true;
974 }
975
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000976 // Verify that this is followed by EOD.
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000977 LexUnexpandedToken(Tok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000978 if (Tok.isNot(tok::eod))
979 Diag(Tok, diag::ext_pragma_syntax_eod);
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000980 return false;
981}
982
Chris Lattnerb694ba72006-07-02 22:41:36 +0000983namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000984
James Dennett18a6d792012-06-17 03:26:26 +0000985/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000986struct PragmaOnceHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000987 PragmaOnceHandler() : PragmaHandler("once") {}
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000988
Craig Topper9140dd22014-03-11 06:50:42 +0000989 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
990 Token &OnceTok) override {
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000991 PP.CheckEndOfDirective("pragma once");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000992 PP.HandlePragmaOnce(OnceTok);
993 }
994};
995
James Dennett18a6d792012-06-17 03:26:26 +0000996/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
Chris Lattnerc2383312007-12-19 19:38:36 +0000997/// rest of the line is not lexed.
998struct PragmaMarkHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000999 PragmaMarkHandler() : PragmaHandler("mark") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001000
Craig Topper9140dd22014-03-11 06:50:42 +00001001 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1002 Token &MarkTok) override {
Chris Lattnerc2383312007-12-19 19:38:36 +00001003 PP.HandlePragmaMark();
1004 }
1005};
1006
James Dennett18a6d792012-06-17 03:26:26 +00001007/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001008struct PragmaPoisonHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001009 PragmaPoisonHandler() : PragmaHandler("poison") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001010
Craig Topper9140dd22014-03-11 06:50:42 +00001011 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1012 Token &PoisonTok) override {
Erik Verbruggen851ce0e2016-10-26 11:46:10 +00001013 PP.HandlePragmaPoison();
Chris Lattnerb694ba72006-07-02 22:41:36 +00001014 }
1015};
1016
James Dennett18a6d792012-06-17 03:26:26 +00001017/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
Chris Lattnerc2383312007-12-19 19:38:36 +00001018/// as a system header, which silences warnings in it.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001019struct PragmaSystemHeaderHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001020 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001021
Craig Topper9140dd22014-03-11 06:50:42 +00001022 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1023 Token &SHToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +00001024 PP.HandlePragmaSystemHeader(SHToken);
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001025 PP.CheckEndOfDirective("pragma");
Chris Lattnerb694ba72006-07-02 22:41:36 +00001026 }
1027};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001028
Chris Lattnerb694ba72006-07-02 22:41:36 +00001029struct PragmaDependencyHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001030 PragmaDependencyHandler() : PragmaHandler("dependency") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001031
Craig Topper9140dd22014-03-11 06:50:42 +00001032 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1033 Token &DepToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +00001034 PP.HandlePragmaDependency(DepToken);
1035 }
1036};
Mike Stump11289f42009-09-09 15:08:12 +00001037
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001038struct PragmaDebugHandler : public PragmaHandler {
1039 PragmaDebugHandler() : PragmaHandler("__debug") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001040
Craig Topper9140dd22014-03-11 06:50:42 +00001041 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1042 Token &DepToken) override {
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001043 Token Tok;
1044 PP.LexUnexpandedToken(Tok);
1045 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001046 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001047 return;
1048 }
1049 IdentifierInfo *II = Tok.getIdentifierInfo();
1050
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001051 if (II->isStr("assert")) {
David Blaikie83d382b2011-09-23 05:06:16 +00001052 llvm_unreachable("This is an assertion!");
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001053 } else if (II->isStr("crash")) {
David Blaikie5bd4c2a2012-08-21 18:56:49 +00001054 LLVM_BUILTIN_TRAP;
David Blaikie5d577a22012-06-29 22:03:56 +00001055 } else if (II->isStr("parser_crash")) {
1056 Token Crasher;
Benjamin Kramer3162f292015-03-08 19:28:24 +00001057 Crasher.startToken();
David Blaikie5d577a22012-06-29 22:03:56 +00001058 Crasher.setKind(tok::annot_pragma_parser_crash);
Benjamin Kramer3162f292015-03-08 19:28:24 +00001059 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
David Blaikie5d577a22012-06-29 22:03:56 +00001060 PP.EnterToken(Crasher);
Richard Smithba3a4f92016-01-12 21:59:26 +00001061 } else if (II->isStr("dump")) {
1062 Token Identifier;
1063 PP.LexUnexpandedToken(Identifier);
1064 if (auto *DumpII = Identifier.getIdentifierInfo()) {
1065 Token DumpAnnot;
1066 DumpAnnot.startToken();
1067 DumpAnnot.setKind(tok::annot_pragma_dump);
1068 DumpAnnot.setAnnotationRange(
1069 SourceRange(Tok.getLocation(), Identifier.getLocation()));
1070 DumpAnnot.setAnnotationValue(DumpII);
1071 PP.DiscardUntilEndOfDirective();
1072 PP.EnterToken(DumpAnnot);
1073 } else {
1074 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
1075 << II->getName();
1076 }
Richard Smith6c2b5a82018-02-09 01:15:13 +00001077 } else if (II->isStr("diag_mapping")) {
1078 Token DiagName;
1079 PP.LexUnexpandedToken(DiagName);
1080 if (DiagName.is(tok::eod))
1081 PP.getDiagnostics().dump();
1082 else if (DiagName.is(tok::string_literal) && !DiagName.hasUDSuffix()) {
1083 StringLiteralParser Literal(DiagName, PP);
1084 if (Literal.hadError)
1085 return;
1086 PP.getDiagnostics().dump(Literal.GetString());
1087 } else {
1088 PP.Diag(DiagName, diag::warn_pragma_debug_missing_argument)
1089 << II->getName();
1090 }
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001091 } else if (II->isStr("llvm_fatal_error")) {
1092 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1093 } else if (II->isStr("llvm_unreachable")) {
1094 llvm_unreachable("#pragma clang __debug llvm_unreachable");
Richard Smith3ffa61d2015-04-30 23:10:40 +00001095 } else if (II->isStr("macro")) {
1096 Token MacroName;
1097 PP.LexUnexpandedToken(MacroName);
1098 auto *MacroII = MacroName.getIdentifierInfo();
1099 if (MacroII)
1100 PP.dumpMacroInfo(MacroII);
1101 else
Richard Smithba3a4f92016-01-12 21:59:26 +00001102 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1103 << II->getName();
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001104 } else if (II->isStr("overflow_stack")) {
1105 DebugOverflowStack();
Daniel Dunbar211a7872010-08-18 23:09:23 +00001106 } else if (II->isStr("handle_crash")) {
1107 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
1108 if (CRC)
1109 CRC->HandleCrash();
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001110 } else if (II->isStr("captured")) {
1111 HandleCaptured(PP);
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001112 } else {
1113 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1114 << II->getName();
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001115 }
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001116
1117 PPCallbacks *Callbacks = PP.getPPCallbacks();
1118 if (Callbacks)
1119 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1120 }
1121
1122 void HandleCaptured(Preprocessor &PP) {
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001123 Token Tok;
1124 PP.LexUnexpandedToken(Tok);
1125
1126 if (Tok.isNot(tok::eod)) {
1127 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1128 << "pragma clang __debug captured";
1129 return;
1130 }
1131
1132 SourceLocation NameLoc = Tok.getLocation();
David Blaikie2eabcc92016-02-09 18:52:09 +00001133 MutableArrayRef<Token> Toks(
1134 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1135 Toks[0].startToken();
1136 Toks[0].setKind(tok::annot_pragma_captured);
1137 Toks[0].setLocation(NameLoc);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001138
David Blaikie2eabcc92016-02-09 18:52:09 +00001139 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001140 }
1141
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001142// Disable MSVC warning about runtime stack overflow.
1143#ifdef _MSC_VER
1144 #pragma warning(disable : 4717)
1145#endif
Matthias Braun285f88d2017-04-24 18:41:00 +00001146 static void DebugOverflowStack(void (*P)() = nullptr) {
1147 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1148 Self(reinterpret_cast<void(*)()>(Self));
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001149 }
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001150#ifdef _MSC_VER
1151 #pragma warning(default : 4717)
1152#endif
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001153};
1154
James Dennett18a6d792012-06-17 03:26:26 +00001155/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
Chris Lattner504af112009-04-19 23:16:58 +00001156struct PragmaDiagnosticHandler : public PragmaHandler {
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001157private:
1158 const char *Namespace;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001159
Chris Lattnerfb42a182009-07-12 21:18:45 +00001160public:
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001161 explicit PragmaDiagnosticHandler(const char *NS)
1162 : PragmaHandler("diagnostic"), Namespace(NS) {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001163
Craig Topper9140dd22014-03-11 06:50:42 +00001164 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1165 Token &DiagToken) override {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001166 SourceLocation DiagLoc = DiagToken.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001167 Token Tok;
1168 PP.LexUnexpandedToken(Tok);
1169 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001170 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001171 return;
1172 }
1173 IdentifierInfo *II = Tok.getIdentifierInfo();
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001174 PPCallbacks *Callbacks = PP.getPPCallbacks();
Mike Stump11289f42009-09-09 15:08:12 +00001175
Alp Toker46df1c02014-06-12 10:15:20 +00001176 if (II->isStr("pop")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001177 if (!PP.getDiagnostics().popMappings(DiagLoc))
Douglas Gregor3cc26482010-08-30 15:15:34 +00001178 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001179 else if (Callbacks)
1180 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
Douglas Gregor3cc26482010-08-30 15:15:34 +00001181 return;
1182 } else if (II->isStr("push")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001183 PP.getDiagnostics().pushMappings(DiagLoc);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001184 if (Callbacks)
1185 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
Chris Lattnerfb42a182009-07-12 21:18:45 +00001186 return;
Alp Toker46df1c02014-06-12 10:15:20 +00001187 }
1188
1189 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1190 .Case("ignored", diag::Severity::Ignored)
1191 .Case("warning", diag::Severity::Warning)
1192 .Case("error", diag::Severity::Error)
1193 .Case("fatal", diag::Severity::Fatal)
1194 .Default(diag::Severity());
1195
1196 if (SV == diag::Severity()) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001197 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001198 return;
1199 }
Mike Stump11289f42009-09-09 15:08:12 +00001200
Chris Lattner504af112009-04-19 23:16:58 +00001201 PP.LexUnexpandedToken(Tok);
Andy Gibbs58905d22012-11-17 19:15:38 +00001202 SourceLocation StringLoc = Tok.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001203
Andy Gibbs58905d22012-11-17 19:15:38 +00001204 std::string WarningName;
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001205 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1206 /*MacroExpansion=*/false))
Chris Lattner504af112009-04-19 23:16:58 +00001207 return;
Mike Stump11289f42009-09-09 15:08:12 +00001208
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001209 if (Tok.isNot(tok::eod)) {
Chris Lattner504af112009-04-19 23:16:58 +00001210 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1211 return;
1212 }
Mike Stump11289f42009-09-09 15:08:12 +00001213
Chris Lattner504af112009-04-19 23:16:58 +00001214 if (WarningName.size() < 3 || WarningName[0] != '-' ||
Richard Smith3be1cb22014-08-07 00:24:21 +00001215 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001216 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
Chris Lattner504af112009-04-19 23:16:58 +00001217 return;
1218 }
Mike Stump11289f42009-09-09 15:08:12 +00001219
Sunil Srivastava5239de72016-02-13 01:44:05 +00001220 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1221 : diag::Flavor::Remark;
Benjamin Kramer2193e232016-02-13 13:42:41 +00001222 StringRef Group = StringRef(WarningName).substr(2);
Sunil Srivastava5239de72016-02-13 01:44:05 +00001223 bool unknownDiag = false;
1224 if (Group == "everything") {
1225 // Special handling for pragma clang diagnostic ... "-Weverything".
1226 // There is no formal group named "everything", so there has to be a
1227 // special case for it.
1228 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1229 } else
1230 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1231 DiagLoc);
1232 if (unknownDiag)
Andy Gibbs58905d22012-11-17 19:15:38 +00001233 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1234 << WarningName;
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001235 else if (Callbacks)
Alp Toker46df1c02014-06-12 10:15:20 +00001236 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
Chris Lattner504af112009-04-19 23:16:58 +00001237 }
1238};
Mike Stump11289f42009-09-09 15:08:12 +00001239
Mike Rice58df1af2018-09-11 17:10:44 +00001240/// "\#pragma hdrstop [<header-name-string>]"
1241struct PragmaHdrstopHandler : public PragmaHandler {
1242 PragmaHdrstopHandler() : PragmaHandler("hdrstop") {}
1243 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1244 Token &DepToken) override {
1245 PP.HandlePragmaHdrstop(DepToken);
1246 }
1247};
1248
Reid Kleckner881dff32013-09-13 22:00:30 +00001249/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1250/// diagnostics, so we don't really implement this pragma. We parse it and
1251/// ignore it to avoid -Wunknown-pragma warnings.
1252struct PragmaWarningHandler : public PragmaHandler {
1253 PragmaWarningHandler() : PragmaHandler("warning") {}
1254
Craig Topper9140dd22014-03-11 06:50:42 +00001255 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1256 Token &Tok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001257 // Parse things like:
1258 // warning(push, 1)
1259 // warning(pop)
John Thompson4762b232013-11-16 00:16:03 +00001260 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
Reid Kleckner881dff32013-09-13 22:00:30 +00001261 SourceLocation DiagLoc = Tok.getLocation();
1262 PPCallbacks *Callbacks = PP.getPPCallbacks();
1263
1264 PP.Lex(Tok);
1265 if (Tok.isNot(tok::l_paren)) {
1266 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1267 return;
1268 }
1269
1270 PP.Lex(Tok);
1271 IdentifierInfo *II = Tok.getIdentifierInfo();
Reid Kleckner881dff32013-09-13 22:00:30 +00001272
Alexander Musman6b080fc2015-05-25 11:21:20 +00001273 if (II && II->isStr("push")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001274 // #pragma warning( push[ ,n ] )
Reid Kleckner4d185102013-10-02 15:19:23 +00001275 int Level = -1;
Reid Kleckner881dff32013-09-13 22:00:30 +00001276 PP.Lex(Tok);
1277 if (Tok.is(tok::comma)) {
1278 PP.Lex(Tok);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001279 uint64_t Value;
1280 if (Tok.is(tok::numeric_constant) &&
1281 PP.parseSimpleIntegerLiteral(Tok, Value))
1282 Level = int(Value);
Reid Kleckner4d185102013-10-02 15:19:23 +00001283 if (Level < 0 || Level > 4) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001284 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1285 return;
1286 }
1287 }
1288 if (Callbacks)
1289 Callbacks->PragmaWarningPush(DiagLoc, Level);
Alexander Musman6b080fc2015-05-25 11:21:20 +00001290 } else if (II && II->isStr("pop")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001291 // #pragma warning( pop )
1292 PP.Lex(Tok);
1293 if (Callbacks)
1294 Callbacks->PragmaWarningPop(DiagLoc);
1295 } else {
1296 // #pragma warning( warning-specifier : warning-number-list
1297 // [; warning-specifier : warning-number-list...] )
1298 while (true) {
1299 II = Tok.getIdentifierInfo();
Alexander Musman6b080fc2015-05-25 11:21:20 +00001300 if (!II && !Tok.is(tok::numeric_constant)) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001301 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1302 return;
1303 }
1304
1305 // Figure out which warning specifier this is.
Alexander Musman6b080fc2015-05-25 11:21:20 +00001306 bool SpecifierValid;
1307 StringRef Specifier;
1308 llvm::SmallString<1> SpecifierBuf;
1309 if (II) {
1310 Specifier = II->getName();
1311 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1312 .Cases("default", "disable", "error", "once",
1313 "suppress", true)
1314 .Default(false);
1315 // If we read a correct specifier, snatch next token (that should be
1316 // ":", checked later).
1317 if (SpecifierValid)
1318 PP.Lex(Tok);
1319 } else {
1320 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1321 uint64_t Value;
1322 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1323 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1324 SpecifierValid = (Value >= 1) && (Value <= 4);
1325 } else
1326 SpecifierValid = false;
1327 // Next token already snatched by parseSimpleIntegerLiteral.
1328 }
1329
Reid Kleckner881dff32013-09-13 22:00:30 +00001330 if (!SpecifierValid) {
1331 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1332 return;
1333 }
Reid Kleckner881dff32013-09-13 22:00:30 +00001334 if (Tok.isNot(tok::colon)) {
1335 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1336 return;
1337 }
1338
1339 // Collect the warning ids.
1340 SmallVector<int, 4> Ids;
1341 PP.Lex(Tok);
1342 while (Tok.is(tok::numeric_constant)) {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001343 uint64_t Value;
1344 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001345 Value > std::numeric_limits<int>::max()) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001346 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1347 return;
1348 }
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001349 Ids.push_back(int(Value));
Reid Kleckner881dff32013-09-13 22:00:30 +00001350 }
1351 if (Callbacks)
1352 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1353
1354 // Parse the next specifier if there is a semicolon.
1355 if (Tok.isNot(tok::semi))
1356 break;
1357 PP.Lex(Tok);
1358 }
1359 }
1360
1361 if (Tok.isNot(tok::r_paren)) {
1362 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1363 return;
1364 }
1365
1366 PP.Lex(Tok);
1367 if (Tok.isNot(tok::eod))
1368 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1369 }
1370};
1371
James Dennett18a6d792012-06-17 03:26:26 +00001372/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
Aaron Ballman611306e2012-03-02 22:51:54 +00001373struct PragmaIncludeAliasHandler : public PragmaHandler {
1374 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001375
Craig Topper9140dd22014-03-11 06:50:42 +00001376 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1377 Token &IncludeAliasTok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001378 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
Aaron Ballman611306e2012-03-02 22:51:54 +00001379 }
1380};
1381
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001382/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1383/// extension. The syntax is:
1384/// \code
1385/// #pragma message(string)
1386/// \endcode
1387/// OR, in GCC mode:
1388/// \code
1389/// #pragma message string
1390/// \endcode
1391/// string is a string, which is fully macro expanded, and permits string
1392/// concatenation, embedded escape characters, etc... See MSDN for more details.
1393/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1394/// form as \#pragma message.
Chris Lattner30c924b2010-06-26 17:11:39 +00001395struct PragmaMessageHandler : public PragmaHandler {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001396private:
1397 const PPCallbacks::PragmaMessageKind Kind;
1398 const StringRef Namespace;
1399
1400 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1401 bool PragmaNameOnly = false) {
1402 switch (Kind) {
1403 case PPCallbacks::PMK_Message:
1404 return PragmaNameOnly ? "message" : "pragma message";
1405 case PPCallbacks::PMK_Warning:
1406 return PragmaNameOnly ? "warning" : "pragma warning";
1407 case PPCallbacks::PMK_Error:
1408 return PragmaNameOnly ? "error" : "pragma error";
1409 }
1410 llvm_unreachable("Unknown PragmaMessageKind!");
1411 }
1412
1413public:
1414 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1415 StringRef Namespace = StringRef())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001416 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
1417 Namespace(Namespace) {}
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001418
Craig Topper9140dd22014-03-11 06:50:42 +00001419 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1420 Token &Tok) override {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001421 SourceLocation MessageLoc = Tok.getLocation();
1422 PP.Lex(Tok);
1423 bool ExpectClosingParen = false;
1424 switch (Tok.getKind()) {
1425 case tok::l_paren:
1426 // We have a MSVC style pragma message.
1427 ExpectClosingParen = true;
1428 // Read the string.
1429 PP.Lex(Tok);
1430 break;
1431 case tok::string_literal:
1432 // We have a GCC style pragma message, and we just read the string.
1433 break;
1434 default:
1435 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1436 return;
1437 }
1438
1439 std::string MessageString;
1440 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1441 /*MacroExpansion=*/true))
1442 return;
1443
1444 if (ExpectClosingParen) {
1445 if (Tok.isNot(tok::r_paren)) {
1446 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1447 return;
1448 }
1449 PP.Lex(Tok); // eat the r_paren.
1450 }
1451
1452 if (Tok.isNot(tok::eod)) {
1453 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1454 return;
1455 }
1456
1457 // Output the message.
1458 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1459 ? diag::err_pragma_message
1460 : diag::warn_pragma_message) << MessageString;
1461
1462 // If the pragma is lexically sound, notify any interested PPCallbacks.
1463 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1464 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
Chris Lattner30c924b2010-06-26 17:11:39 +00001465 }
1466};
1467
Richard Smithc51c38b2017-04-29 00:34:47 +00001468/// Handle the clang \#pragma module import extension. The syntax is:
1469/// \code
1470/// #pragma clang module import some.module.name
1471/// \endcode
1472struct PragmaModuleImportHandler : public PragmaHandler {
1473 PragmaModuleImportHandler() : PragmaHandler("import") {}
1474
1475 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
Richard Smithd1386302017-05-04 00:29:54 +00001476 Token &Tok) override {
1477 SourceLocation ImportLoc = Tok.getLocation();
1478
1479 // Read the module name.
1480 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1481 ModuleName;
1482 if (LexModuleName(PP, Tok, ModuleName))
1483 return;
1484
1485 if (Tok.isNot(tok::eod))
1486 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1487
1488 // If we have a non-empty module path, load the named module.
1489 Module *Imported =
1490 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1491 /*IsIncludeDirective=*/false);
1492 if (!Imported)
1493 return;
1494
1495 PP.makeModuleVisible(Imported, ImportLoc);
1496 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1497 tok::annot_module_include, Imported);
1498 if (auto *CB = PP.getPPCallbacks())
1499 CB->moduleImport(ImportLoc, ModuleName, Imported);
1500 }
1501};
1502
1503/// Handle the clang \#pragma module begin extension. The syntax is:
1504/// \code
1505/// #pragma clang module begin some.module.name
1506/// ...
1507/// #pragma clang module end
1508/// \endcode
1509struct PragmaModuleBeginHandler : public PragmaHandler {
1510 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1511
1512 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1513 Token &Tok) override {
1514 SourceLocation BeginLoc = Tok.getLocation();
1515
1516 // Read the module name.
1517 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1518 ModuleName;
1519 if (LexModuleName(PP, Tok, ModuleName))
1520 return;
1521
1522 if (Tok.isNot(tok::eod))
1523 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1524
1525 // We can only enter submodules of the current module.
1526 StringRef Current = PP.getLangOpts().CurrentModule;
1527 if (ModuleName.front().first->getName() != Current) {
1528 PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1529 << ModuleName.front().first << (ModuleName.size() > 1)
1530 << Current.empty() << Current;
1531 return;
1532 }
1533
1534 // Find the module we're entering. We require that a module map for it
1535 // be loaded or implicitly loadable.
1536 // FIXME: We could create the submodule here. We'd need to know whether
1537 // it's supposed to be explicit, but not much else.
Richard Smith9565c75b2017-06-19 23:09:36 +00001538 Module *M = PP.getHeaderSearchInfo().lookupModule(Current);
Richard Smithd1386302017-05-04 00:29:54 +00001539 if (!M) {
1540 PP.Diag(ModuleName.front().second,
1541 diag::err_pp_module_begin_no_module_map) << Current;
1542 return;
1543 }
1544 for (unsigned I = 1; I != ModuleName.size(); ++I) {
1545 auto *NewM = M->findSubmodule(ModuleName[I].first->getName());
1546 if (!NewM) {
1547 PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1548 << M->getFullModuleName() << ModuleName[I].first;
1549 return;
1550 }
1551 M = NewM;
1552 }
1553
Richard Smith51d09c52017-05-30 05:22:59 +00001554 // If the module isn't available, it doesn't make sense to enter it.
Richard Smith27e5aa02017-06-05 18:57:56 +00001555 if (Preprocessor::checkModuleIsAvailable(
1556 PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
Richard Smith51d09c52017-05-30 05:22:59 +00001557 PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1558 << M->getTopLevelModuleName();
1559 return;
1560 }
1561
Richard Smithd1386302017-05-04 00:29:54 +00001562 // Enter the scope of the submodule.
1563 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1564 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1565 tok::annot_module_begin, M);
1566 }
1567};
1568
1569/// Handle the clang \#pragma module end extension.
1570struct PragmaModuleEndHandler : public PragmaHandler {
1571 PragmaModuleEndHandler() : PragmaHandler("end") {}
1572
1573 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1574 Token &Tok) override {
1575 SourceLocation Loc = Tok.getLocation();
1576
1577 PP.LexUnexpandedToken(Tok);
1578 if (Tok.isNot(tok::eod))
1579 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1580
1581 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1582 if (M)
1583 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1584 else
1585 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
Richard Smithc51c38b2017-04-29 00:34:47 +00001586 }
1587};
1588
Richard Smith5d2ed482017-06-09 19:22:32 +00001589/// Handle the clang \#pragma module build extension.
1590struct PragmaModuleBuildHandler : public PragmaHandler {
1591 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1592
1593 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1594 Token &Tok) override {
1595 PP.HandlePragmaModuleBuild(Tok);
1596 }
1597};
1598
1599/// Handle the clang \#pragma module load extension.
1600struct PragmaModuleLoadHandler : public PragmaHandler {
1601 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1602
1603 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1604 Token &Tok) override {
1605 SourceLocation Loc = Tok.getLocation();
1606
1607 // Read the module name.
1608 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1609 ModuleName;
1610 if (LexModuleName(PP, Tok, ModuleName))
1611 return;
1612
1613 if (Tok.isNot(tok::eod))
1614 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1615
1616 // Load the module, don't make it visible.
1617 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1618 /*IsIncludeDirective=*/false);
1619 }
1620};
1621
James Dennett18a6d792012-06-17 03:26:26 +00001622/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001623/// macro on the top of the stack.
1624struct PragmaPushMacroHandler : public PragmaHandler {
1625 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001626
Craig Topper9140dd22014-03-11 06:50:42 +00001627 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1628 Token &PushMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001629 PP.HandlePragmaPushMacro(PushMacroTok);
1630 }
1631};
1632
James Dennett18a6d792012-06-17 03:26:26 +00001633/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001634/// macro to the value on the top of the stack.
1635struct PragmaPopMacroHandler : public PragmaHandler {
1636 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001637
Craig Topper9140dd22014-03-11 06:50:42 +00001638 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1639 Token &PopMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001640 PP.HandlePragmaPopMacro(PopMacroTok);
1641 }
1642};
1643
Fangrui Song6907ce22018-07-30 19:24:48 +00001644/// PragmaARCCFCodeAuditedHandler -
James Dennett18a6d792012-06-17 03:26:26 +00001645/// \#pragma clang arc_cf_code_audited begin/end
John McCall32f5fe12011-09-30 05:12:12 +00001646struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1647 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001648
Craig Topper9140dd22014-03-11 06:50:42 +00001649 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1650 Token &NameTok) override {
John McCall32f5fe12011-09-30 05:12:12 +00001651 SourceLocation Loc = NameTok.getLocation();
1652 bool IsBegin;
1653
1654 Token Tok;
1655
1656 // Lex the 'begin' or 'end'.
1657 PP.LexUnexpandedToken(Tok);
1658 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1659 if (BeginEnd && BeginEnd->isStr("begin")) {
1660 IsBegin = true;
1661 } else if (BeginEnd && BeginEnd->isStr("end")) {
1662 IsBegin = false;
1663 } else {
1664 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1665 return;
1666 }
1667
1668 // Verify that this is followed by EOD.
1669 PP.LexUnexpandedToken(Tok);
1670 if (Tok.isNot(tok::eod))
1671 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1672
1673 // The start location of the active audit.
1674 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1675
1676 // The start location we want after processing this.
1677 SourceLocation NewLoc;
1678
1679 if (IsBegin) {
1680 // Complain about attempts to re-enter an audit.
1681 if (BeginLoc.isValid()) {
1682 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1683 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1684 }
1685 NewLoc = Loc;
1686 } else {
1687 // Complain about attempts to leave an audit that doesn't exist.
1688 if (!BeginLoc.isValid()) {
1689 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1690 return;
1691 }
1692 NewLoc = SourceLocation();
1693 }
1694
1695 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1696 }
1697};
1698
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001699/// PragmaAssumeNonNullHandler -
1700/// \#pragma clang assume_nonnull begin/end
1701struct PragmaAssumeNonNullHandler : public PragmaHandler {
1702 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001703
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001704 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1705 Token &NameTok) override {
1706 SourceLocation Loc = NameTok.getLocation();
1707 bool IsBegin;
1708
1709 Token Tok;
1710
1711 // Lex the 'begin' or 'end'.
1712 PP.LexUnexpandedToken(Tok);
1713 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1714 if (BeginEnd && BeginEnd->isStr("begin")) {
1715 IsBegin = true;
1716 } else if (BeginEnd && BeginEnd->isStr("end")) {
1717 IsBegin = false;
1718 } else {
1719 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1720 return;
1721 }
1722
1723 // Verify that this is followed by EOD.
1724 PP.LexUnexpandedToken(Tok);
1725 if (Tok.isNot(tok::eod))
1726 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1727
1728 // The start location of the active audit.
1729 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1730
1731 // The start location we want after processing this.
1732 SourceLocation NewLoc;
Eli Friedman16fee082017-09-27 23:29:37 +00001733 PPCallbacks *Callbacks = PP.getPPCallbacks();
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001734
1735 if (IsBegin) {
1736 // Complain about attempts to re-enter an audit.
1737 if (BeginLoc.isValid()) {
1738 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1739 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1740 }
1741 NewLoc = Loc;
Eli Friedman16fee082017-09-27 23:29:37 +00001742 if (Callbacks)
1743 Callbacks->PragmaAssumeNonNullBegin(NewLoc);
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001744 } else {
1745 // Complain about attempts to leave an audit that doesn't exist.
1746 if (!BeginLoc.isValid()) {
1747 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1748 return;
1749 }
1750 NewLoc = SourceLocation();
Eli Friedman16fee082017-09-27 23:29:37 +00001751 if (Callbacks)
1752 Callbacks->PragmaAssumeNonNullEnd(NewLoc);
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001753 }
1754
1755 PP.setPragmaAssumeNonNullLoc(NewLoc);
1756 }
1757};
1758
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001759/// Handle "\#pragma region [...]"
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001760///
1761/// The syntax is
1762/// \code
1763/// #pragma region [optional name]
1764/// #pragma endregion [optional comment]
1765/// \endcode
1766///
1767/// \note This is
1768/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1769/// pragma, just skipped by compiler.
1770struct PragmaRegionHandler : public PragmaHandler {
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001771 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
Aaron Ballman406ea512012-11-30 19:52:30 +00001772
Craig Topper9140dd22014-03-11 06:50:42 +00001773 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1774 Token &NameTok) override {
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001775 // #pragma region: endregion matches can be verified
1776 // __pragma(region): no sense, but ignored by msvc
1777 // _Pragma is not valid for MSVC, but there isn't any point
1778 // to handle a _Pragma differently.
1779 }
1780};
Aaron Ballman406ea512012-11-30 19:52:30 +00001781
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001782} // namespace
Chris Lattnerb694ba72006-07-02 22:41:36 +00001783
1784/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
James Dennett18a6d792012-06-17 03:26:26 +00001785/// \#pragma GCC poison/system_header/dependency and \#pragma once.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001786void Preprocessor::RegisterBuiltinPragmas() {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001787 AddPragmaHandler(new PragmaOnceHandler());
1788 AddPragmaHandler(new PragmaMarkHandler());
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001789 AddPragmaHandler(new PragmaPushMacroHandler());
1790 AddPragmaHandler(new PragmaPopMacroHandler());
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001791 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
Mike Stump11289f42009-09-09 15:08:12 +00001792
Chris Lattnerb61448d2009-05-12 18:21:11 +00001793 // #pragma GCC ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001794 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1795 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1796 AddPragmaHandler("GCC", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001797 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001798 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1799 "GCC"));
1800 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1801 "GCC"));
Chris Lattnerb61448d2009-05-12 18:21:11 +00001802 // #pragma clang ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001803 AddPragmaHandler("clang", new PragmaPoisonHandler());
1804 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001805 AddPragmaHandler("clang", new PragmaDebugHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001806 AddPragmaHandler("clang", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001807 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
John McCall32f5fe12011-09-30 05:12:12 +00001808 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001809 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
Chris Lattnerb61448d2009-05-12 18:21:11 +00001810
Richard Smithc51c38b2017-04-29 00:34:47 +00001811 // #pragma clang module ...
1812 auto *ModuleHandler = new PragmaNamespace("module");
1813 AddPragmaHandler("clang", ModuleHandler);
1814 ModuleHandler->AddPragma(new PragmaModuleImportHandler());
Richard Smithd1386302017-05-04 00:29:54 +00001815 ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
1816 ModuleHandler->AddPragma(new PragmaModuleEndHandler());
Richard Smith5d2ed482017-06-09 19:22:32 +00001817 ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
1818 ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
Fangrui Song6907ce22018-07-30 19:24:48 +00001819
Matt Davis1edb9052018-01-27 00:25:29 +00001820 // Add region pragmas.
1821 AddPragmaHandler(new PragmaRegionHandler("region"));
1822 AddPragmaHandler(new PragmaRegionHandler("endregion"));
Richard Smithc51c38b2017-04-29 00:34:47 +00001823
Chris Lattner2ff698d2009-01-16 08:21:25 +00001824 // MS extensions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001825 if (LangOpts.MicrosoftExt) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001826 AddPragmaHandler(new PragmaWarningHandler());
Aaron Ballman611306e2012-03-02 22:51:54 +00001827 AddPragmaHandler(new PragmaIncludeAliasHandler());
Mike Rice58df1af2018-09-11 17:10:44 +00001828 AddPragmaHandler(new PragmaHdrstopHandler());
Chris Lattner30c924b2010-06-26 17:11:39 +00001829 }
John Brawn8e62db32016-04-04 14:22:58 +00001830
1831 // Pragmas added by plugins
1832 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1833 ie = PragmaHandlerRegistry::end();
1834 it != ie; ++it) {
1835 AddPragmaHandler(it->instantiate().release());
1836 }
Chris Lattnerb694ba72006-07-02 22:41:36 +00001837}
Lubos Lunak576a0412014-05-01 12:54:03 +00001838
1839/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1840/// warn about those pragmas being unknown.
1841void Preprocessor::IgnorePragmas() {
1842 AddPragmaHandler(new EmptyPragmaHandler());
1843 // Also ignore all pragmas in all namespaces created
1844 // in Preprocessor::RegisterBuiltinPragmas().
1845 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1846 AddPragmaHandler("clang", new EmptyPragmaHandler());
Lubos Lunak576a0412014-05-01 12:54:03 +00001847}