1 //===--- Pragma.cpp - Pragma registration and handling --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PragmaHandler/PragmaTable interfaces and implements
11 // pragma related methods of the Preprocessor class.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Lex/Pragma.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/LiteralSupport.h"
21 #include "clang/Lex/MacroInfo.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "llvm/Support/CrashRecoveryContext.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include <algorithm>
26 using namespace clang;
27 
28 // Out-of-line destructor to provide a home for the class.
29 PragmaHandler::~PragmaHandler() {
30 }
31 
32 //===----------------------------------------------------------------------===//
33 // EmptyPragmaHandler Implementation.
34 //===----------------------------------------------------------------------===//
35 
36 EmptyPragmaHandler::EmptyPragmaHandler() {}
37 
38 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
39                                       PragmaIntroducerKind Introducer,
40                                       Token &FirstToken) {}
41 
42 //===----------------------------------------------------------------------===//
43 // PragmaNamespace Implementation.
44 //===----------------------------------------------------------------------===//
45 
46 PragmaNamespace::~PragmaNamespace() {
47   for (llvm::StringMap<PragmaHandler*>::iterator
48          I = Handlers.begin(), E = Handlers.end(); I != E; ++I)
49     delete I->second;
50 }
51 
52 /// FindHandler - Check to see if there is already a handler for the
53 /// specified name.  If not, return the handler for the null identifier if it
54 /// exists, otherwise return null.  If IgnoreNull is true (the default) then
55 /// the null handler isn't returned on failure to match.
56 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
57                                             bool IgnoreNull) const {
58   if (PragmaHandler *Handler = Handlers.lookup(Name))
59     return Handler;
60   return IgnoreNull ? 0 : Handlers.lookup(StringRef());
61 }
62 
63 void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
64   assert(!Handlers.lookup(Handler->getName()) &&
65          "A handler with this name is already registered in this namespace");
66   llvm::StringMapEntry<PragmaHandler *> &Entry =
67     Handlers.GetOrCreateValue(Handler->getName());
68   Entry.setValue(Handler);
69 }
70 
71 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
72   assert(Handlers.lookup(Handler->getName()) &&
73          "Handler not registered in this namespace");
74   Handlers.erase(Handler->getName());
75 }
76 
77 void PragmaNamespace::HandlePragma(Preprocessor &PP,
78                                    PragmaIntroducerKind Introducer,
79                                    Token &Tok) {
80   // Read the 'namespace' that the directive is in, e.g. STDC.  Do not macro
81   // expand it, the user can have a STDC #define, that should not affect this.
82   PP.LexUnexpandedToken(Tok);
83 
84   // Get the handler for this token.  If there is no handler, ignore the pragma.
85   PragmaHandler *Handler
86     = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
87                                           : StringRef(),
88                   /*IgnoreNull=*/false);
89   if (Handler == 0) {
90     PP.Diag(Tok, diag::warn_pragma_ignored);
91     return;
92   }
93 
94   // Otherwise, pass it down.
95   Handler->HandlePragma(PP, Introducer, Tok);
96 }
97 
98 //===----------------------------------------------------------------------===//
99 // Preprocessor Pragma Directive Handling.
100 //===----------------------------------------------------------------------===//
101 
102 /// HandlePragmaDirective - The "\#pragma" directive has been parsed.  Lex the
103 /// rest of the pragma, passing it to the registered pragma handlers.
104 void Preprocessor::HandlePragmaDirective(unsigned Introducer) {
105   if (!PragmasEnabled)
106     return;
107 
108   ++NumPragma;
109 
110   // Invoke the first level of pragma handlers which reads the namespace id.
111   Token Tok;
112   PragmaHandlers->HandlePragma(*this, PragmaIntroducerKind(Introducer), Tok);
113 
114   // If the pragma handler didn't read the rest of the line, consume it now.
115   if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
116    || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
117     DiscardUntilEndOfDirective();
118 }
119 
120 namespace {
121 /// \brief Helper class for \see Preprocessor::Handle_Pragma.
122 class LexingFor_PragmaRAII {
123   Preprocessor &PP;
124   bool InMacroArgPreExpansion;
125   bool Failed;
126   Token &OutTok;
127   Token PragmaTok;
128 
129 public:
130   LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
131                        Token &Tok)
132     : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
133       Failed(false), OutTok(Tok) {
134     if (InMacroArgPreExpansion) {
135       PragmaTok = OutTok;
136       PP.EnableBacktrackAtThisPos();
137     }
138   }
139 
140   ~LexingFor_PragmaRAII() {
141     if (InMacroArgPreExpansion) {
142       if (Failed) {
143         PP.CommitBacktrackedTokens();
144       } else {
145         PP.Backtrack();
146         OutTok = PragmaTok;
147       }
148     }
149   }
150 
151   void failed() {
152     Failed = true;
153   }
154 };
155 }
156 
157 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
158 /// return the first token after the directive.  The _Pragma token has just
159 /// been read into 'Tok'.
160 void Preprocessor::Handle_Pragma(Token &Tok) {
161 
162   // This works differently if we are pre-expanding a macro argument.
163   // In that case we don't actually "activate" the pragma now, we only lex it
164   // until we are sure it is lexically correct and then we backtrack so that
165   // we activate the pragma whenever we encounter the tokens again in the token
166   // stream. This ensures that we will activate it in the correct location
167   // or that we will ignore it if it never enters the token stream, e.g:
168   //
169   //     #define EMPTY(x)
170   //     #define INACTIVE(x) EMPTY(x)
171   //     INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
172 
173   LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
174 
175   // Remember the pragma token location.
176   SourceLocation PragmaLoc = Tok.getLocation();
177 
178   // Read the '('.
179   Lex(Tok);
180   if (Tok.isNot(tok::l_paren)) {
181     Diag(PragmaLoc, diag::err__Pragma_malformed);
182     return _PragmaLexing.failed();
183   }
184 
185   // Read the '"..."'.
186   Lex(Tok);
187   if (!tok::isStringLiteral(Tok.getKind())) {
188     Diag(PragmaLoc, diag::err__Pragma_malformed);
189     // Skip this token, and the ')', if present.
190     if (Tok.isNot(tok::r_paren))
191       Lex(Tok);
192     if (Tok.is(tok::r_paren))
193       Lex(Tok);
194     return _PragmaLexing.failed();
195   }
196 
197   if (Tok.hasUDSuffix()) {
198     Diag(Tok, diag::err_invalid_string_udl);
199     // Skip this token, and the ')', if present.
200     Lex(Tok);
201     if (Tok.is(tok::r_paren))
202       Lex(Tok);
203     return _PragmaLexing.failed();
204   }
205 
206   // Remember the string.
207   Token StrTok = Tok;
208 
209   // Read the ')'.
210   Lex(Tok);
211   if (Tok.isNot(tok::r_paren)) {
212     Diag(PragmaLoc, diag::err__Pragma_malformed);
213     return _PragmaLexing.failed();
214   }
215 
216   if (InMacroArgPreExpansion)
217     return;
218 
219   SourceLocation RParenLoc = Tok.getLocation();
220   std::string StrVal = getSpelling(StrTok);
221 
222   // The _Pragma is lexically sound.  Destringize according to C11 6.10.9.1:
223   // "The string literal is destringized by deleting any encoding prefix,
224   // deleting the leading and trailing double-quotes, replacing each escape
225   // sequence \" by a double-quote, and replacing each escape sequence \\ by a
226   // single backslash."
227   if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
228       (StrVal[0] == 'u' && StrVal[1] != '8'))
229     StrVal.erase(StrVal.begin());
230   else if (StrVal[0] == 'u')
231     StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
232 
233   if (StrVal[0] == 'R') {
234     // FIXME: C++11 does not specify how to handle raw-string-literals here.
235     // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
236     assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
237            "Invalid raw string token!");
238 
239     // Measure the length of the d-char-sequence.
240     unsigned NumDChars = 0;
241     while (StrVal[2 + NumDChars] != '(') {
242       assert(NumDChars < (StrVal.size() - 5) / 2 &&
243              "Invalid raw string token!");
244       ++NumDChars;
245     }
246     assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
247 
248     // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
249     // parens below.
250     StrVal.erase(0, 2 + NumDChars);
251     StrVal.erase(StrVal.size() - 1 - NumDChars);
252   } else {
253     assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
254            "Invalid string token!");
255 
256     // Remove escaped quotes and escapes.
257     for (unsigned i = 1, e = StrVal.size(); i < e-2; ++i) {
258       if (StrVal[i] == '\\' &&
259           (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
260         // \\ -> '\' and \" -> '"'.
261         StrVal.erase(StrVal.begin()+i);
262         --e;
263       }
264     }
265   }
266 
267   // Remove the front quote, replacing it with a space, so that the pragma
268   // contents appear to have a space before them.
269   StrVal[0] = ' ';
270 
271   // Replace the terminating quote with a \n.
272   StrVal[StrVal.size()-1] = '\n';
273 
274   // Plop the string (including the newline and trailing null) into a buffer
275   // where we can lex it.
276   Token TmpTok;
277   TmpTok.startToken();
278   CreateString(StrVal, TmpTok);
279   SourceLocation TokLoc = TmpTok.getLocation();
280 
281   // Make and enter a lexer object so that we lex and expand the tokens just
282   // like any others.
283   Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
284                                         StrVal.size(), *this);
285 
286   EnterSourceFileWithLexer(TL, 0);
287 
288   // With everything set up, lex this as a #pragma directive.
289   HandlePragmaDirective(PIK__Pragma);
290 
291   // Finally, return whatever came after the pragma directive.
292   return Lex(Tok);
293 }
294 
295 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
296 /// is not enclosed within a string literal.
297 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
298   // Remember the pragma token location.
299   SourceLocation PragmaLoc = Tok.getLocation();
300 
301   // Read the '('.
302   Lex(Tok);
303   if (Tok.isNot(tok::l_paren)) {
304     Diag(PragmaLoc, diag::err__Pragma_malformed);
305     return;
306   }
307 
308   // Get the tokens enclosed within the __pragma(), as well as the final ')'.
309   SmallVector<Token, 32> PragmaToks;
310   int NumParens = 0;
311   Lex(Tok);
312   while (Tok.isNot(tok::eof)) {
313     PragmaToks.push_back(Tok);
314     if (Tok.is(tok::l_paren))
315       NumParens++;
316     else if (Tok.is(tok::r_paren) && NumParens-- == 0)
317       break;
318     Lex(Tok);
319   }
320 
321   if (Tok.is(tok::eof)) {
322     Diag(PragmaLoc, diag::err_unterminated___pragma);
323     return;
324   }
325 
326   PragmaToks.front().setFlag(Token::LeadingSpace);
327 
328   // Replace the ')' with an EOD to mark the end of the pragma.
329   PragmaToks.back().setKind(tok::eod);
330 
331   Token *TokArray = new Token[PragmaToks.size()];
332   std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
333 
334   // Push the tokens onto the stack.
335   EnterTokenStream(TokArray, PragmaToks.size(), true, true);
336 
337   // With everything set up, lex this as a #pragma directive.
338   HandlePragmaDirective(PIK___pragma);
339 
340   // Finally, return whatever came after the pragma directive.
341   return Lex(Tok);
342 }
343 
344 /// HandlePragmaOnce - Handle \#pragma once.  OnceTok is the 'once'.
345 ///
346 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
347   if (isInPrimaryFile()) {
348     Diag(OnceTok, diag::pp_pragma_once_in_main_file);
349     return;
350   }
351 
352   // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
353   // Mark the file as a once-only file now.
354   HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
355 }
356 
357 void Preprocessor::HandlePragmaMark() {
358   assert(CurPPLexer && "No current lexer?");
359   if (CurLexer)
360     CurLexer->ReadToEndOfLine();
361   else
362     CurPTHLexer->DiscardToEndOfLine();
363 }
364 
365 
366 /// HandlePragmaPoison - Handle \#pragma GCC poison.  PoisonTok is the 'poison'.
367 ///
368 void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
369   Token Tok;
370 
371   while (1) {
372     // Read the next token to poison.  While doing this, pretend that we are
373     // skipping while reading the identifier to poison.
374     // This avoids errors on code like:
375     //   #pragma GCC poison X
376     //   #pragma GCC poison X
377     if (CurPPLexer) CurPPLexer->LexingRawMode = true;
378     LexUnexpandedToken(Tok);
379     if (CurPPLexer) CurPPLexer->LexingRawMode = false;
380 
381     // If we reached the end of line, we're done.
382     if (Tok.is(tok::eod)) return;
383 
384     // Can only poison identifiers.
385     if (Tok.isNot(tok::raw_identifier)) {
386       Diag(Tok, diag::err_pp_invalid_poison);
387       return;
388     }
389 
390     // Look up the identifier info for the token.  We disabled identifier lookup
391     // by saying we're skipping contents, so we need to do this manually.
392     IdentifierInfo *II = LookUpIdentifierInfo(Tok);
393 
394     // Already poisoned.
395     if (II->isPoisoned()) continue;
396 
397     // If this is a macro identifier, emit a warning.
398     if (II->hasMacroDefinition())
399       Diag(Tok, diag::pp_poisoning_existing_macro);
400 
401     // Finally, poison it!
402     II->setIsPoisoned();
403     if (II->isFromAST())
404       II->setChangedSinceDeserialization();
405   }
406 }
407 
408 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header.  We know
409 /// that the whole directive has been parsed.
410 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
411   if (isInPrimaryFile()) {
412     Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
413     return;
414   }
415 
416   // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
417   PreprocessorLexer *TheLexer = getCurrentFileLexer();
418 
419   // Mark the file as a system header.
420   HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
421 
422 
423   PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
424   if (PLoc.isInvalid())
425     return;
426 
427   unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
428 
429   // Notify the client, if desired, that we are in a new source file.
430   if (Callbacks)
431     Callbacks->FileChanged(SysHeaderTok.getLocation(),
432                            PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
433 
434   // Emit a line marker.  This will change any source locations from this point
435   // forward to realize they are in a system header.
436   // Create a line note with this information.
437   SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1,
438                         FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
439                         /*IsSystem=*/true, /*IsExternC=*/false);
440 }
441 
442 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
443 ///
444 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
445   Token FilenameTok;
446   CurPPLexer->LexIncludeFilename(FilenameTok);
447 
448   // If the token kind is EOD, the error has already been diagnosed.
449   if (FilenameTok.is(tok::eod))
450     return;
451 
452   // Reserve a buffer to get the spelling.
453   SmallString<128> FilenameBuffer;
454   bool Invalid = false;
455   StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
456   if (Invalid)
457     return;
458 
459   bool isAngled =
460     GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
461   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
462   // error.
463   if (Filename.empty())
464     return;
465 
466   // Search include directories for this file.
467   const DirectoryLookup *CurDir;
468   const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir, NULL, NULL,
469                                      NULL);
470   if (File == 0) {
471     if (!SuppressIncludeNotFoundError)
472       Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
473     return;
474   }
475 
476   const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
477 
478   // If this file is older than the file it depends on, emit a diagnostic.
479   if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
480     // Lex tokens at the end of the message and include them in the message.
481     std::string Message;
482     Lex(DependencyTok);
483     while (DependencyTok.isNot(tok::eod)) {
484       Message += getSpelling(DependencyTok) + " ";
485       Lex(DependencyTok);
486     }
487 
488     // Remove the trailing ' ' if present.
489     if (!Message.empty())
490       Message.erase(Message.end()-1);
491     Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
492   }
493 }
494 
495 /// \brief Handle the microsoft \#pragma comment extension.
496 ///
497 /// The syntax is:
498 /// \code
499 ///   #pragma comment(linker, "foo")
500 /// \endcode
501 /// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
502 /// "foo" is a string, which is fully macro expanded, and permits string
503 /// concatenation, embedded escape characters etc.  See MSDN for more details.
504 void Preprocessor::HandlePragmaComment(Token &Tok) {
505   SourceLocation CommentLoc = Tok.getLocation();
506   Lex(Tok);
507   if (Tok.isNot(tok::l_paren)) {
508     Diag(CommentLoc, diag::err_pragma_comment_malformed);
509     return;
510   }
511 
512   // Read the identifier.
513   Lex(Tok);
514   if (Tok.isNot(tok::identifier)) {
515     Diag(CommentLoc, diag::err_pragma_comment_malformed);
516     return;
517   }
518 
519   // Verify that this is one of the 5 whitelisted options.
520   // FIXME: warn that 'exestr' is deprecated.
521   const IdentifierInfo *II = Tok.getIdentifierInfo();
522   if (!II->isStr("compiler") && !II->isStr("exestr") && !II->isStr("lib") &&
523       !II->isStr("linker") && !II->isStr("user")) {
524     Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
525     return;
526   }
527 
528   // Read the optional string if present.
529   Lex(Tok);
530   std::string ArgumentString;
531   if (Tok.is(tok::comma) && !LexStringLiteral(Tok, ArgumentString,
532                                               "pragma comment",
533                                               /*MacroExpansion=*/true))
534     return;
535 
536   // FIXME: If the kind is "compiler" warn if the string is present (it is
537   // ignored).
538   // FIXME: 'lib' requires a comment string.
539   // FIXME: 'linker' requires a comment string, and has a specific list of
540   // things that are allowable.
541 
542   if (Tok.isNot(tok::r_paren)) {
543     Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
544     return;
545   }
546   Lex(Tok);  // eat the r_paren.
547 
548   if (Tok.isNot(tok::eod)) {
549     Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
550     return;
551   }
552 
553   // If the pragma is lexically sound, notify any interested PPCallbacks.
554   if (Callbacks)
555     Callbacks->PragmaComment(CommentLoc, II, ArgumentString);
556 }
557 
558 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
559 /// Return the IdentifierInfo* associated with the macro to push or pop.
560 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
561   // Remember the pragma token location.
562   Token PragmaTok = Tok;
563 
564   // Read the '('.
565   Lex(Tok);
566   if (Tok.isNot(tok::l_paren)) {
567     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
568       << getSpelling(PragmaTok);
569     return 0;
570   }
571 
572   // Read the macro name string.
573   Lex(Tok);
574   if (Tok.isNot(tok::string_literal)) {
575     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
576       << getSpelling(PragmaTok);
577     return 0;
578   }
579 
580   if (Tok.hasUDSuffix()) {
581     Diag(Tok, diag::err_invalid_string_udl);
582     return 0;
583   }
584 
585   // Remember the macro string.
586   std::string StrVal = getSpelling(Tok);
587 
588   // Read the ')'.
589   Lex(Tok);
590   if (Tok.isNot(tok::r_paren)) {
591     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
592       << getSpelling(PragmaTok);
593     return 0;
594   }
595 
596   assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
597          "Invalid string token!");
598 
599   // Create a Token from the string.
600   Token MacroTok;
601   MacroTok.startToken();
602   MacroTok.setKind(tok::raw_identifier);
603   CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
604 
605   // Get the IdentifierInfo of MacroToPushTok.
606   return LookUpIdentifierInfo(MacroTok);
607 }
608 
609 /// \brief Handle \#pragma push_macro.
610 ///
611 /// The syntax is:
612 /// \code
613 ///   #pragma push_macro("macro")
614 /// \endcode
615 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
616   // Parse the pragma directive and get the macro IdentifierInfo*.
617   IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
618   if (!IdentInfo) return;
619 
620   // Get the MacroInfo associated with IdentInfo.
621   MacroInfo *MI = getMacroInfo(IdentInfo);
622 
623   if (MI) {
624     // Allow the original MacroInfo to be redefined later.
625     MI->setIsAllowRedefinitionsWithoutWarning(true);
626   }
627 
628   // Push the cloned MacroInfo so we can retrieve it later.
629   PragmaPushMacroInfo[IdentInfo].push_back(MI);
630 }
631 
632 /// \brief Handle \#pragma pop_macro.
633 ///
634 /// The syntax is:
635 /// \code
636 ///   #pragma pop_macro("macro")
637 /// \endcode
638 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
639   SourceLocation MessageLoc = PopMacroTok.getLocation();
640 
641   // Parse the pragma directive and get the macro IdentifierInfo*.
642   IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
643   if (!IdentInfo) return;
644 
645   // Find the vector<MacroInfo*> associated with the macro.
646   llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
647     PragmaPushMacroInfo.find(IdentInfo);
648   if (iter != PragmaPushMacroInfo.end()) {
649     // Forget the MacroInfo currently associated with IdentInfo.
650     if (MacroDirective *CurrentMD = getMacroDirective(IdentInfo)) {
651       MacroInfo *MI = CurrentMD->getMacroInfo();
652       if (MI->isWarnIfUnused())
653         WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
654       appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
655     }
656 
657     // Get the MacroInfo we want to reinstall.
658     MacroInfo *MacroToReInstall = iter->second.back();
659 
660     if (MacroToReInstall) {
661       // Reinstall the previously pushed macro.
662       appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc,
663                               /*isImported=*/false);
664     }
665 
666     // Pop PragmaPushMacroInfo stack.
667     iter->second.pop_back();
668     if (iter->second.size() == 0)
669       PragmaPushMacroInfo.erase(iter);
670   } else {
671     Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
672       << IdentInfo->getName();
673   }
674 }
675 
676 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
677   // We will either get a quoted filename or a bracketed filename, and we
678   // have to track which we got.  The first filename is the source name,
679   // and the second name is the mapped filename.  If the first is quoted,
680   // the second must be as well (cannot mix and match quotes and brackets).
681 
682   // Get the open paren
683   Lex(Tok);
684   if (Tok.isNot(tok::l_paren)) {
685     Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
686     return;
687   }
688 
689   // We expect either a quoted string literal, or a bracketed name
690   Token SourceFilenameTok;
691   CurPPLexer->LexIncludeFilename(SourceFilenameTok);
692   if (SourceFilenameTok.is(tok::eod)) {
693     // The diagnostic has already been handled
694     return;
695   }
696 
697   StringRef SourceFileName;
698   SmallString<128> FileNameBuffer;
699   if (SourceFilenameTok.is(tok::string_literal) ||
700       SourceFilenameTok.is(tok::angle_string_literal)) {
701     SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
702   } else if (SourceFilenameTok.is(tok::less)) {
703     // This could be a path instead of just a name
704     FileNameBuffer.push_back('<');
705     SourceLocation End;
706     if (ConcatenateIncludeName(FileNameBuffer, End))
707       return; // Diagnostic already emitted
708     SourceFileName = FileNameBuffer.str();
709   } else {
710     Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
711     return;
712   }
713   FileNameBuffer.clear();
714 
715   // Now we expect a comma, followed by another include name
716   Lex(Tok);
717   if (Tok.isNot(tok::comma)) {
718     Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
719     return;
720   }
721 
722   Token ReplaceFilenameTok;
723   CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
724   if (ReplaceFilenameTok.is(tok::eod)) {
725     // The diagnostic has already been handled
726     return;
727   }
728 
729   StringRef ReplaceFileName;
730   if (ReplaceFilenameTok.is(tok::string_literal) ||
731       ReplaceFilenameTok.is(tok::angle_string_literal)) {
732     ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
733   } else if (ReplaceFilenameTok.is(tok::less)) {
734     // This could be a path instead of just a name
735     FileNameBuffer.push_back('<');
736     SourceLocation End;
737     if (ConcatenateIncludeName(FileNameBuffer, End))
738       return; // Diagnostic already emitted
739     ReplaceFileName = FileNameBuffer.str();
740   } else {
741     Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
742     return;
743   }
744 
745   // Finally, we expect the closing paren
746   Lex(Tok);
747   if (Tok.isNot(tok::r_paren)) {
748     Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
749     return;
750   }
751 
752   // Now that we have the source and target filenames, we need to make sure
753   // they're both of the same type (angled vs non-angled)
754   StringRef OriginalSource = SourceFileName;
755 
756   bool SourceIsAngled =
757     GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
758                                 SourceFileName);
759   bool ReplaceIsAngled =
760     GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
761                                 ReplaceFileName);
762   if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
763       (SourceIsAngled != ReplaceIsAngled)) {
764     unsigned int DiagID;
765     if (SourceIsAngled)
766       DiagID = diag::warn_pragma_include_alias_mismatch_angle;
767     else
768       DiagID = diag::warn_pragma_include_alias_mismatch_quote;
769 
770     Diag(SourceFilenameTok.getLocation(), DiagID)
771       << SourceFileName
772       << ReplaceFileName;
773 
774     return;
775   }
776 
777   // Now we can let the include handler know about this mapping
778   getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
779 }
780 
781 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
782 /// If 'Namespace' is non-null, then it is a token required to exist on the
783 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
784 void Preprocessor::AddPragmaHandler(StringRef Namespace,
785                                     PragmaHandler *Handler) {
786   PragmaNamespace *InsertNS = PragmaHandlers;
787 
788   // If this is specified to be in a namespace, step down into it.
789   if (!Namespace.empty()) {
790     // If there is already a pragma handler with the name of this namespace,
791     // we either have an error (directive with the same name as a namespace) or
792     // we already have the namespace to insert into.
793     if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
794       InsertNS = Existing->getIfNamespace();
795       assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
796              " handler with the same name!");
797     } else {
798       // Otherwise, this namespace doesn't exist yet, create and insert the
799       // handler for it.
800       InsertNS = new PragmaNamespace(Namespace);
801       PragmaHandlers->AddPragma(InsertNS);
802     }
803   }
804 
805   // Check to make sure we don't already have a pragma for this identifier.
806   assert(!InsertNS->FindHandler(Handler->getName()) &&
807          "Pragma handler already exists for this identifier!");
808   InsertNS->AddPragma(Handler);
809 }
810 
811 /// RemovePragmaHandler - Remove the specific pragma handler from the
812 /// preprocessor. If \arg Namespace is non-null, then it should be the
813 /// namespace that \arg Handler was added to. It is an error to remove
814 /// a handler that has not been registered.
815 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
816                                        PragmaHandler *Handler) {
817   PragmaNamespace *NS = PragmaHandlers;
818 
819   // If this is specified to be in a namespace, step down into it.
820   if (!Namespace.empty()) {
821     PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
822     assert(Existing && "Namespace containing handler does not exist!");
823 
824     NS = Existing->getIfNamespace();
825     assert(NS && "Invalid namespace, registered as a regular pragma handler!");
826   }
827 
828   NS->RemovePragmaHandler(Handler);
829 
830   // If this is a non-default namespace and it is now empty, remove
831   // it.
832   if (NS != PragmaHandlers && NS->IsEmpty()) {
833     PragmaHandlers->RemovePragmaHandler(NS);
834     delete NS;
835   }
836 }
837 
838 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
839   Token Tok;
840   LexUnexpandedToken(Tok);
841 
842   if (Tok.isNot(tok::identifier)) {
843     Diag(Tok, diag::ext_on_off_switch_syntax);
844     return true;
845   }
846   IdentifierInfo *II = Tok.getIdentifierInfo();
847   if (II->isStr("ON"))
848     Result = tok::OOS_ON;
849   else if (II->isStr("OFF"))
850     Result = tok::OOS_OFF;
851   else if (II->isStr("DEFAULT"))
852     Result = tok::OOS_DEFAULT;
853   else {
854     Diag(Tok, diag::ext_on_off_switch_syntax);
855     return true;
856   }
857 
858   // Verify that this is followed by EOD.
859   LexUnexpandedToken(Tok);
860   if (Tok.isNot(tok::eod))
861     Diag(Tok, diag::ext_pragma_syntax_eod);
862   return false;
863 }
864 
865 namespace {
866 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
867 struct PragmaOnceHandler : public PragmaHandler {
868   PragmaOnceHandler() : PragmaHandler("once") {}
869   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
870                             Token &OnceTok) {
871     PP.CheckEndOfDirective("pragma once");
872     PP.HandlePragmaOnce(OnceTok);
873   }
874 };
875 
876 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
877 /// rest of the line is not lexed.
878 struct PragmaMarkHandler : public PragmaHandler {
879   PragmaMarkHandler() : PragmaHandler("mark") {}
880   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
881                             Token &MarkTok) {
882     PP.HandlePragmaMark();
883   }
884 };
885 
886 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
887 struct PragmaPoisonHandler : public PragmaHandler {
888   PragmaPoisonHandler() : PragmaHandler("poison") {}
889   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
890                             Token &PoisonTok) {
891     PP.HandlePragmaPoison(PoisonTok);
892   }
893 };
894 
895 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
896 /// as a system header, which silences warnings in it.
897 struct PragmaSystemHeaderHandler : public PragmaHandler {
898   PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
899   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
900                             Token &SHToken) {
901     PP.HandlePragmaSystemHeader(SHToken);
902     PP.CheckEndOfDirective("pragma");
903   }
904 };
905 struct PragmaDependencyHandler : public PragmaHandler {
906   PragmaDependencyHandler() : PragmaHandler("dependency") {}
907   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
908                             Token &DepToken) {
909     PP.HandlePragmaDependency(DepToken);
910   }
911 };
912 
913 struct PragmaDebugHandler : public PragmaHandler {
914   PragmaDebugHandler() : PragmaHandler("__debug") {}
915   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
916                             Token &DepToken) {
917     Token Tok;
918     PP.LexUnexpandedToken(Tok);
919     if (Tok.isNot(tok::identifier)) {
920       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
921       return;
922     }
923     IdentifierInfo *II = Tok.getIdentifierInfo();
924 
925     if (II->isStr("assert")) {
926       llvm_unreachable("This is an assertion!");
927     } else if (II->isStr("crash")) {
928       LLVM_BUILTIN_TRAP;
929     } else if (II->isStr("parser_crash")) {
930       Token Crasher;
931       Crasher.setKind(tok::annot_pragma_parser_crash);
932       PP.EnterToken(Crasher);
933     } else if (II->isStr("llvm_fatal_error")) {
934       llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
935     } else if (II->isStr("llvm_unreachable")) {
936       llvm_unreachable("#pragma clang __debug llvm_unreachable");
937     } else if (II->isStr("overflow_stack")) {
938       DebugOverflowStack();
939     } else if (II->isStr("handle_crash")) {
940       llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
941       if (CRC)
942         CRC->HandleCrash();
943     } else if (II->isStr("captured")) {
944       HandleCaptured(PP);
945     } else {
946       PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
947         << II->getName();
948     }
949 
950     PPCallbacks *Callbacks = PP.getPPCallbacks();
951     if (Callbacks)
952       Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
953   }
954 
955   void HandleCaptured(Preprocessor &PP) {
956     // Skip if emitting preprocessed output.
957     if (PP.isPreprocessedOutput())
958       return;
959 
960     Token Tok;
961     PP.LexUnexpandedToken(Tok);
962 
963     if (Tok.isNot(tok::eod)) {
964       PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
965         << "pragma clang __debug captured";
966       return;
967     }
968 
969     SourceLocation NameLoc = Tok.getLocation();
970     Token *Toks = PP.getPreprocessorAllocator().Allocate<Token>(1);
971     Toks->startToken();
972     Toks->setKind(tok::annot_pragma_captured);
973     Toks->setLocation(NameLoc);
974 
975     PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
976                         /*OwnsTokens=*/false);
977   }
978 
979 // Disable MSVC warning about runtime stack overflow.
980 #ifdef _MSC_VER
981     #pragma warning(disable : 4717)
982 #endif
983   void DebugOverflowStack() {
984     DebugOverflowStack();
985   }
986 #ifdef _MSC_VER
987     #pragma warning(default : 4717)
988 #endif
989 
990 };
991 
992 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
993 struct PragmaDiagnosticHandler : public PragmaHandler {
994 private:
995   const char *Namespace;
996 public:
997   explicit PragmaDiagnosticHandler(const char *NS) :
998     PragmaHandler("diagnostic"), Namespace(NS) {}
999   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1000                             Token &DiagToken) {
1001     SourceLocation DiagLoc = DiagToken.getLocation();
1002     Token Tok;
1003     PP.LexUnexpandedToken(Tok);
1004     if (Tok.isNot(tok::identifier)) {
1005       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1006       return;
1007     }
1008     IdentifierInfo *II = Tok.getIdentifierInfo();
1009     PPCallbacks *Callbacks = PP.getPPCallbacks();
1010 
1011     diag::Mapping Map;
1012     if (II->isStr("warning"))
1013       Map = diag::MAP_WARNING;
1014     else if (II->isStr("error"))
1015       Map = diag::MAP_ERROR;
1016     else if (II->isStr("ignored"))
1017       Map = diag::MAP_IGNORE;
1018     else if (II->isStr("fatal"))
1019       Map = diag::MAP_FATAL;
1020     else if (II->isStr("pop")) {
1021       if (!PP.getDiagnostics().popMappings(DiagLoc))
1022         PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1023       else if (Callbacks)
1024         Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
1025       return;
1026     } else if (II->isStr("push")) {
1027       PP.getDiagnostics().pushMappings(DiagLoc);
1028       if (Callbacks)
1029         Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
1030       return;
1031     } else {
1032       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1033       return;
1034     }
1035 
1036     PP.LexUnexpandedToken(Tok);
1037     SourceLocation StringLoc = Tok.getLocation();
1038 
1039     std::string WarningName;
1040     if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1041                                    /*MacroExpansion=*/false))
1042       return;
1043 
1044     if (Tok.isNot(tok::eod)) {
1045       PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1046       return;
1047     }
1048 
1049     if (WarningName.size() < 3 || WarningName[0] != '-' ||
1050         WarningName[1] != 'W') {
1051       PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
1052       return;
1053     }
1054 
1055     if (PP.getDiagnostics().setDiagnosticGroupMapping(WarningName.substr(2),
1056                                                       Map, DiagLoc))
1057       PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1058         << WarningName;
1059     else if (Callbacks)
1060       Callbacks->PragmaDiagnostic(DiagLoc, Namespace, Map, WarningName);
1061   }
1062 };
1063 
1064 /// PragmaCommentHandler - "\#pragma comment ...".
1065 struct PragmaCommentHandler : public PragmaHandler {
1066   PragmaCommentHandler() : PragmaHandler("comment") {}
1067   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1068                             Token &CommentTok) {
1069     PP.HandlePragmaComment(CommentTok);
1070   }
1071 };
1072 
1073 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1074 struct PragmaIncludeAliasHandler : public PragmaHandler {
1075   PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1076   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1077                             Token &IncludeAliasTok) {
1078       PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1079   }
1080 };
1081 
1082 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1083 /// extension.  The syntax is:
1084 /// \code
1085 ///   #pragma message(string)
1086 /// \endcode
1087 /// OR, in GCC mode:
1088 /// \code
1089 ///   #pragma message string
1090 /// \endcode
1091 /// string is a string, which is fully macro expanded, and permits string
1092 /// concatenation, embedded escape characters, etc... See MSDN for more details.
1093 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1094 /// form as \#pragma message.
1095 struct PragmaMessageHandler : public PragmaHandler {
1096 private:
1097   const PPCallbacks::PragmaMessageKind Kind;
1098   const StringRef Namespace;
1099 
1100   static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1101                                 bool PragmaNameOnly = false) {
1102     switch (Kind) {
1103       case PPCallbacks::PMK_Message:
1104         return PragmaNameOnly ? "message" : "pragma message";
1105       case PPCallbacks::PMK_Warning:
1106         return PragmaNameOnly ? "warning" : "pragma warning";
1107       case PPCallbacks::PMK_Error:
1108         return PragmaNameOnly ? "error" : "pragma error";
1109     }
1110     llvm_unreachable("Unknown PragmaMessageKind!");
1111   }
1112 
1113 public:
1114   PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1115                        StringRef Namespace = StringRef())
1116     : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1117 
1118   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1119                             Token &Tok) {
1120     SourceLocation MessageLoc = Tok.getLocation();
1121     PP.Lex(Tok);
1122     bool ExpectClosingParen = false;
1123     switch (Tok.getKind()) {
1124     case tok::l_paren:
1125       // We have a MSVC style pragma message.
1126       ExpectClosingParen = true;
1127       // Read the string.
1128       PP.Lex(Tok);
1129       break;
1130     case tok::string_literal:
1131       // We have a GCC style pragma message, and we just read the string.
1132       break;
1133     default:
1134       PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1135       return;
1136     }
1137 
1138     std::string MessageString;
1139     if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1140                                    /*MacroExpansion=*/true))
1141       return;
1142 
1143     if (ExpectClosingParen) {
1144       if (Tok.isNot(tok::r_paren)) {
1145         PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1146         return;
1147       }
1148       PP.Lex(Tok);  // eat the r_paren.
1149     }
1150 
1151     if (Tok.isNot(tok::eod)) {
1152       PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1153       return;
1154     }
1155 
1156     // Output the message.
1157     PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1158                           ? diag::err_pragma_message
1159                           : diag::warn_pragma_message) << MessageString;
1160 
1161     // If the pragma is lexically sound, notify any interested PPCallbacks.
1162     if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1163       Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1164   }
1165 };
1166 
1167 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1168 /// macro on the top of the stack.
1169 struct PragmaPushMacroHandler : public PragmaHandler {
1170   PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1171   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1172                             Token &PushMacroTok) {
1173     PP.HandlePragmaPushMacro(PushMacroTok);
1174   }
1175 };
1176 
1177 
1178 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1179 /// macro to the value on the top of the stack.
1180 struct PragmaPopMacroHandler : public PragmaHandler {
1181   PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1182   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1183                             Token &PopMacroTok) {
1184     PP.HandlePragmaPopMacro(PopMacroTok);
1185   }
1186 };
1187 
1188 // Pragma STDC implementations.
1189 
1190 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
1191 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
1192   PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
1193   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1194                             Token &Tok) {
1195     tok::OnOffSwitch OOS;
1196     if (PP.LexOnOffSwitch(OOS))
1197      return;
1198     if (OOS == tok::OOS_ON)
1199       PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
1200   }
1201 };
1202 
1203 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
1204 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
1205   PragmaSTDC_CX_LIMITED_RANGEHandler()
1206     : PragmaHandler("CX_LIMITED_RANGE") {}
1207   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1208                             Token &Tok) {
1209     tok::OnOffSwitch OOS;
1210     PP.LexOnOffSwitch(OOS);
1211   }
1212 };
1213 
1214 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
1215 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
1216   PragmaSTDC_UnknownHandler() {}
1217   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1218                             Token &UnknownTok) {
1219     // C99 6.10.6p2, unknown forms are not allowed.
1220     PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1221   }
1222 };
1223 
1224 /// PragmaARCCFCodeAuditedHandler -
1225 ///   \#pragma clang arc_cf_code_audited begin/end
1226 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1227   PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1228   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1229                             Token &NameTok) {
1230     SourceLocation Loc = NameTok.getLocation();
1231     bool IsBegin;
1232 
1233     Token Tok;
1234 
1235     // Lex the 'begin' or 'end'.
1236     PP.LexUnexpandedToken(Tok);
1237     const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1238     if (BeginEnd && BeginEnd->isStr("begin")) {
1239       IsBegin = true;
1240     } else if (BeginEnd && BeginEnd->isStr("end")) {
1241       IsBegin = false;
1242     } else {
1243       PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1244       return;
1245     }
1246 
1247     // Verify that this is followed by EOD.
1248     PP.LexUnexpandedToken(Tok);
1249     if (Tok.isNot(tok::eod))
1250       PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1251 
1252     // The start location of the active audit.
1253     SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1254 
1255     // The start location we want after processing this.
1256     SourceLocation NewLoc;
1257 
1258     if (IsBegin) {
1259       // Complain about attempts to re-enter an audit.
1260       if (BeginLoc.isValid()) {
1261         PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1262         PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1263       }
1264       NewLoc = Loc;
1265     } else {
1266       // Complain about attempts to leave an audit that doesn't exist.
1267       if (!BeginLoc.isValid()) {
1268         PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1269         return;
1270       }
1271       NewLoc = SourceLocation();
1272     }
1273 
1274     PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1275   }
1276 };
1277 
1278   /// \brief Handle "\#pragma region [...]"
1279   ///
1280   /// The syntax is
1281   /// \code
1282   ///   #pragma region [optional name]
1283   ///   #pragma endregion [optional comment]
1284   /// \endcode
1285   ///
1286   /// \note This is
1287   /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1288   /// pragma, just skipped by compiler.
1289   struct PragmaRegionHandler : public PragmaHandler {
1290     PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
1291 
1292     virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1293                               Token &NameTok) {
1294       // #pragma region: endregion matches can be verified
1295       // __pragma(region): no sense, but ignored by msvc
1296       // _Pragma is not valid for MSVC, but there isn't any point
1297       // to handle a _Pragma differently.
1298     }
1299   };
1300 
1301 }  // end anonymous namespace
1302 
1303 
1304 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1305 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1306 void Preprocessor::RegisterBuiltinPragmas() {
1307   AddPragmaHandler(new PragmaOnceHandler());
1308   AddPragmaHandler(new PragmaMarkHandler());
1309   AddPragmaHandler(new PragmaPushMacroHandler());
1310   AddPragmaHandler(new PragmaPopMacroHandler());
1311   AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
1312 
1313   // #pragma GCC ...
1314   AddPragmaHandler("GCC", new PragmaPoisonHandler());
1315   AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1316   AddPragmaHandler("GCC", new PragmaDependencyHandler());
1317   AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1318   AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1319                                                    "GCC"));
1320   AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1321                                                    "GCC"));
1322   // #pragma clang ...
1323   AddPragmaHandler("clang", new PragmaPoisonHandler());
1324   AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1325   AddPragmaHandler("clang", new PragmaDebugHandler());
1326   AddPragmaHandler("clang", new PragmaDependencyHandler());
1327   AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1328   AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1329 
1330   AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1331   AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1332   AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1333 
1334   // MS extensions.
1335   if (LangOpts.MicrosoftExt) {
1336     AddPragmaHandler(new PragmaCommentHandler());
1337     AddPragmaHandler(new PragmaIncludeAliasHandler());
1338     AddPragmaHandler(new PragmaRegionHandler("region"));
1339     AddPragmaHandler(new PragmaRegionHandler("endregion"));
1340   }
1341 }
1342