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