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