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