Pragma.cpp 51 KB

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