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