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