Pragma.cpp 50 KB

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