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