PrintPreprocessedOutput.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. //===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
  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 code simply runs the preprocessor on the input file and prints out the
  11. // result. This is the traditional behavior of the -E option.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Frontend/Utils.h"
  15. #include "clang/Basic/CharInfo.h"
  16. #include "clang/Basic/Diagnostic.h"
  17. #include "clang/Basic/SourceManager.h"
  18. #include "clang/Frontend/PreprocessorOutputOptions.h"
  19. #include "clang/Lex/MacroInfo.h"
  20. #include "clang/Lex/PPCallbacks.h"
  21. #include "clang/Lex/Pragma.h"
  22. #include "clang/Lex/Preprocessor.h"
  23. #include "clang/Lex/TokenConcatenation.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/ADT/SmallString.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include <cstdio>
  30. using namespace clang;
  31. /// PrintMacroDefinition - Print a macro definition in a form that will be
  32. /// properly accepted back as a definition.
  33. static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
  34. Preprocessor &PP, raw_ostream &OS) {
  35. OS << "#define " << II.getName();
  36. if (MI.isFunctionLike()) {
  37. OS << '(';
  38. if (!MI.arg_empty()) {
  39. MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
  40. for (; AI+1 != E; ++AI) {
  41. OS << (*AI)->getName();
  42. OS << ',';
  43. }
  44. // Last argument.
  45. if ((*AI)->getName() == "__VA_ARGS__")
  46. OS << "...";
  47. else
  48. OS << (*AI)->getName();
  49. }
  50. if (MI.isGNUVarargs())
  51. OS << "..."; // #define foo(x...)
  52. OS << ')';
  53. }
  54. // GCC always emits a space, even if the macro body is empty. However, do not
  55. // want to emit two spaces if the first token has a leading space.
  56. if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
  57. OS << ' ';
  58. SmallString<128> SpellingBuffer;
  59. for (const auto &T : MI.tokens()) {
  60. if (T.hasLeadingSpace())
  61. OS << ' ';
  62. OS << PP.getSpelling(T, SpellingBuffer);
  63. }
  64. }
  65. //===----------------------------------------------------------------------===//
  66. // Preprocessed token printer
  67. //===----------------------------------------------------------------------===//
  68. namespace {
  69. class PrintPPOutputPPCallbacks : public PPCallbacks {
  70. Preprocessor &PP;
  71. SourceManager &SM;
  72. TokenConcatenation ConcatInfo;
  73. public:
  74. raw_ostream &OS;
  75. private:
  76. unsigned CurLine;
  77. bool EmittedTokensOnThisLine;
  78. bool EmittedDirectiveOnThisLine;
  79. SrcMgr::CharacteristicKind FileType;
  80. SmallString<512> CurFilename;
  81. bool Initialized;
  82. bool DisableLineMarkers;
  83. bool DumpDefines;
  84. bool UseLineDirectives;
  85. bool IsFirstFileEntered;
  86. public:
  87. PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os, bool lineMarkers,
  88. bool defines, bool UseLineDirectives)
  89. : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
  90. DisableLineMarkers(lineMarkers), DumpDefines(defines),
  91. UseLineDirectives(UseLineDirectives) {
  92. CurLine = 0;
  93. CurFilename += "<uninit>";
  94. EmittedTokensOnThisLine = false;
  95. EmittedDirectiveOnThisLine = false;
  96. FileType = SrcMgr::C_User;
  97. Initialized = false;
  98. IsFirstFileEntered = false;
  99. }
  100. void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
  101. bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
  102. void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
  103. bool hasEmittedDirectiveOnThisLine() const {
  104. return EmittedDirectiveOnThisLine;
  105. }
  106. bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
  107. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  108. SrcMgr::CharacteristicKind FileType,
  109. FileID PrevFID) override;
  110. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  111. StringRef FileName, bool IsAngled,
  112. CharSourceRange FilenameRange, const FileEntry *File,
  113. StringRef SearchPath, StringRef RelativePath,
  114. const Module *Imported) override;
  115. void Ident(SourceLocation Loc, StringRef str) override;
  116. void PragmaMessage(SourceLocation Loc, StringRef Namespace,
  117. PragmaMessageKind Kind, StringRef Str) override;
  118. void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
  119. void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
  120. void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
  121. void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
  122. diag::Severity Map, StringRef Str) override;
  123. void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
  124. ArrayRef<int> Ids) override;
  125. void PragmaWarningPush(SourceLocation Loc, int Level) override;
  126. void PragmaWarningPop(SourceLocation Loc) override;
  127. bool HandleFirstTokOnLine(Token &Tok);
  128. /// Move to the line of the provided source location. This will
  129. /// return true if the output stream required adjustment or if
  130. /// the requested location is on the first line.
  131. bool MoveToLine(SourceLocation Loc) {
  132. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  133. if (PLoc.isInvalid())
  134. return false;
  135. return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
  136. }
  137. bool MoveToLine(unsigned LineNo);
  138. bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
  139. const Token &Tok) {
  140. return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
  141. }
  142. void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
  143. unsigned ExtraLen=0);
  144. bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
  145. void HandleNewlinesInToken(const char *TokStr, unsigned Len);
  146. /// MacroDefined - This hook is called whenever a macro definition is seen.
  147. void MacroDefined(const Token &MacroNameTok,
  148. const MacroDirective *MD) override;
  149. /// MacroUndefined - This hook is called whenever a macro #undef is seen.
  150. void MacroUndefined(const Token &MacroNameTok,
  151. const MacroDefinition &MD) override;
  152. };
  153. } // end anonymous namespace
  154. void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
  155. const char *Extra,
  156. unsigned ExtraLen) {
  157. startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
  158. // Emit #line directives or GNU line markers depending on what mode we're in.
  159. if (UseLineDirectives) {
  160. OS << "#line" << ' ' << LineNo << ' ' << '"';
  161. OS.write_escaped(CurFilename);
  162. OS << '"';
  163. } else {
  164. OS << '#' << ' ' << LineNo << ' ' << '"';
  165. OS.write_escaped(CurFilename);
  166. OS << '"';
  167. if (ExtraLen)
  168. OS.write(Extra, ExtraLen);
  169. if (FileType == SrcMgr::C_System)
  170. OS.write(" 3", 2);
  171. else if (FileType == SrcMgr::C_ExternCSystem)
  172. OS.write(" 3 4", 4);
  173. }
  174. OS << '\n';
  175. }
  176. /// MoveToLine - Move the output to the source line specified by the location
  177. /// object. We can do this by emitting some number of \n's, or be emitting a
  178. /// #line directive. This returns false if already at the specified line, true
  179. /// if some newlines were emitted.
  180. bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
  181. // If this line is "close enough" to the original line, just print newlines,
  182. // otherwise print a #line directive.
  183. if (LineNo-CurLine <= 8) {
  184. if (LineNo-CurLine == 1)
  185. OS << '\n';
  186. else if (LineNo == CurLine)
  187. return false; // Spelling line moved, but expansion line didn't.
  188. else {
  189. const char *NewLines = "\n\n\n\n\n\n\n\n";
  190. OS.write(NewLines, LineNo-CurLine);
  191. }
  192. } else if (!DisableLineMarkers) {
  193. // Emit a #line or line marker.
  194. WriteLineInfo(LineNo, nullptr, 0);
  195. } else {
  196. // Okay, we're in -P mode, which turns off line markers. However, we still
  197. // need to emit a newline between tokens on different lines.
  198. startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
  199. }
  200. CurLine = LineNo;
  201. return true;
  202. }
  203. bool
  204. PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
  205. if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
  206. OS << '\n';
  207. EmittedTokensOnThisLine = false;
  208. EmittedDirectiveOnThisLine = false;
  209. if (ShouldUpdateCurrentLine)
  210. ++CurLine;
  211. return true;
  212. }
  213. return false;
  214. }
  215. /// FileChanged - Whenever the preprocessor enters or exits a #include file
  216. /// it invokes this handler. Update our conception of the current source
  217. /// position.
  218. void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
  219. FileChangeReason Reason,
  220. SrcMgr::CharacteristicKind NewFileType,
  221. FileID PrevFID) {
  222. // Unless we are exiting a #include, make sure to skip ahead to the line the
  223. // #include directive was at.
  224. SourceManager &SourceMgr = SM;
  225. PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
  226. if (UserLoc.isInvalid())
  227. return;
  228. unsigned NewLine = UserLoc.getLine();
  229. if (Reason == PPCallbacks::EnterFile) {
  230. SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
  231. if (IncludeLoc.isValid())
  232. MoveToLine(IncludeLoc);
  233. } else if (Reason == PPCallbacks::SystemHeaderPragma) {
  234. // GCC emits the # directive for this directive on the line AFTER the
  235. // directive and emits a bunch of spaces that aren't needed. This is because
  236. // otherwise we will emit a line marker for THIS line, which requires an
  237. // extra blank line after the directive to avoid making all following lines
  238. // off by one. We can do better by simply incrementing NewLine here.
  239. NewLine += 1;
  240. }
  241. // HLSL Change Starts - do not report the same location multiple times
  242. if (PP.getLangOpts().HLSL && CurLine == NewLine &&
  243. CurFilename == UserLoc.getFilename()) {
  244. assert(FileType == NewFileType && "else same file has different file type");
  245. return;
  246. }
  247. if (PP.getLangOpts().HLSL) {
  248. if (0 == strcmp(UserLoc.getFilename(), "<built-in>")) {
  249. assert(NewLine == 1 && "else built-in is generating preprocessor output");
  250. return;
  251. }
  252. }
  253. // HLSL Change Ends
  254. CurLine = NewLine;
  255. CurFilename.clear();
  256. CurFilename += UserLoc.getFilename();
  257. FileType = NewFileType;
  258. if (DisableLineMarkers) {
  259. startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
  260. return;
  261. }
  262. if (!Initialized) {
  263. WriteLineInfo(CurLine);
  264. Initialized = true;
  265. }
  266. // Do not emit an enter marker for the main file (which we expect is the first
  267. // entered file). This matches gcc, and improves compatibility with some tools
  268. // which track the # line markers as a way to determine when the preprocessed
  269. // output is in the context of the main file.
  270. if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
  271. IsFirstFileEntered = true;
  272. return;
  273. }
  274. switch (Reason) {
  275. case PPCallbacks::EnterFile:
  276. WriteLineInfo(CurLine, " 1", 2);
  277. break;
  278. case PPCallbacks::ExitFile:
  279. WriteLineInfo(CurLine, " 2", 2);
  280. break;
  281. case PPCallbacks::SystemHeaderPragma:
  282. case PPCallbacks::RenameFile:
  283. WriteLineInfo(CurLine);
  284. break;
  285. }
  286. }
  287. void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
  288. const Token &IncludeTok,
  289. StringRef FileName,
  290. bool IsAngled,
  291. CharSourceRange FilenameRange,
  292. const FileEntry *File,
  293. StringRef SearchPath,
  294. StringRef RelativePath,
  295. const Module *Imported) {
  296. // When preprocessing, turn implicit imports into @imports.
  297. // FIXME: This is a stop-gap until a more comprehensive "preprocessing with
  298. // modules" solution is introduced.
  299. if (Imported) {
  300. startNewLineIfNeeded();
  301. MoveToLine(HashLoc);
  302. OS << "@import " << Imported->getFullModuleName() << ";"
  303. << " /* clang -E: implicit import for \"" << File->getName() << "\" */";
  304. // Since we want a newline after the @import, but not a #<line>, start a new
  305. // line immediately.
  306. EmittedTokensOnThisLine = true;
  307. startNewLineIfNeeded();
  308. }
  309. }
  310. /// Ident - Handle #ident directives when read by the preprocessor.
  311. ///
  312. void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
  313. MoveToLine(Loc);
  314. OS.write("#ident ", strlen("#ident "));
  315. OS.write(S.begin(), S.size());
  316. EmittedTokensOnThisLine = true;
  317. }
  318. /// MacroDefined - This hook is called whenever a macro definition is seen.
  319. void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
  320. const MacroDirective *MD) {
  321. const MacroInfo *MI = MD->getMacroInfo();
  322. // Only print out macro definitions in -dD mode.
  323. if (!DumpDefines ||
  324. // Ignore __FILE__ etc.
  325. MI->isBuiltinMacro()) return;
  326. MoveToLine(MI->getDefinitionLoc());
  327. PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
  328. setEmittedDirectiveOnThisLine();
  329. }
  330. void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
  331. const MacroDefinition &MD) {
  332. // Only print out macro definitions in -dD mode.
  333. if (!DumpDefines) return;
  334. MoveToLine(MacroNameTok.getLocation());
  335. OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
  336. setEmittedDirectiveOnThisLine();
  337. }
  338. static void outputPrintable(llvm::raw_ostream& OS,
  339. const std::string &Str) {
  340. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  341. unsigned char Char = Str[i];
  342. if (isPrintable(Char) && Char != '\\' && Char != '"')
  343. OS << (char)Char;
  344. else // Output anything hard as an octal escape.
  345. OS << '\\'
  346. << (char)('0'+ ((Char >> 6) & 7))
  347. << (char)('0'+ ((Char >> 3) & 7))
  348. << (char)('0'+ ((Char >> 0) & 7));
  349. }
  350. }
  351. void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
  352. StringRef Namespace,
  353. PragmaMessageKind Kind,
  354. StringRef Str) {
  355. startNewLineIfNeeded();
  356. MoveToLine(Loc);
  357. OS << "#pragma ";
  358. if (!Namespace.empty())
  359. OS << Namespace << ' ';
  360. switch (Kind) {
  361. case PMK_Message:
  362. OS << "message(\"";
  363. break;
  364. case PMK_Warning:
  365. OS << "warning \"";
  366. break;
  367. case PMK_Error:
  368. OS << "error \"";
  369. break;
  370. }
  371. outputPrintable(OS, Str);
  372. OS << '"';
  373. if (Kind == PMK_Message)
  374. OS << ')';
  375. setEmittedDirectiveOnThisLine();
  376. }
  377. void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
  378. StringRef DebugType) {
  379. startNewLineIfNeeded();
  380. MoveToLine(Loc);
  381. OS << "#pragma clang __debug ";
  382. OS << DebugType;
  383. setEmittedDirectiveOnThisLine();
  384. }
  385. void PrintPPOutputPPCallbacks::
  386. PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
  387. startNewLineIfNeeded();
  388. MoveToLine(Loc);
  389. OS << "#pragma " << Namespace << " diagnostic push";
  390. setEmittedDirectiveOnThisLine();
  391. }
  392. void PrintPPOutputPPCallbacks::
  393. PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
  394. startNewLineIfNeeded();
  395. MoveToLine(Loc);
  396. OS << "#pragma " << Namespace << " diagnostic pop";
  397. setEmittedDirectiveOnThisLine();
  398. }
  399. void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
  400. StringRef Namespace,
  401. diag::Severity Map,
  402. StringRef Str) {
  403. startNewLineIfNeeded();
  404. MoveToLine(Loc);
  405. OS << "#pragma " << Namespace << " diagnostic ";
  406. switch (Map) {
  407. case diag::Severity::Remark:
  408. OS << "remark";
  409. break;
  410. case diag::Severity::Warning:
  411. OS << "warning";
  412. break;
  413. case diag::Severity::Error:
  414. OS << "error";
  415. break;
  416. case diag::Severity::Ignored:
  417. OS << "ignored";
  418. break;
  419. case diag::Severity::Fatal:
  420. OS << "fatal";
  421. break;
  422. }
  423. OS << " \"" << Str << '"';
  424. setEmittedDirectiveOnThisLine();
  425. }
  426. void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
  427. StringRef WarningSpec,
  428. ArrayRef<int> Ids) {
  429. startNewLineIfNeeded();
  430. MoveToLine(Loc);
  431. OS << "#pragma warning(" << WarningSpec << ':';
  432. for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
  433. OS << ' ' << *I;
  434. OS << ')';
  435. setEmittedDirectiveOnThisLine();
  436. }
  437. void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
  438. int Level) {
  439. startNewLineIfNeeded();
  440. MoveToLine(Loc);
  441. OS << "#pragma warning(push";
  442. if (Level >= 0)
  443. OS << ", " << Level;
  444. OS << ')';
  445. setEmittedDirectiveOnThisLine();
  446. }
  447. void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
  448. startNewLineIfNeeded();
  449. MoveToLine(Loc);
  450. OS << "#pragma warning(pop)";
  451. setEmittedDirectiveOnThisLine();
  452. }
  453. /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
  454. /// is called for the first token on each new line. If this really is the start
  455. /// of a new logical line, handle it and return true, otherwise return false.
  456. /// This may not be the start of a logical line because the "start of line"
  457. /// marker is set for spelling lines, not expansion ones.
  458. bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
  459. // Figure out what line we went to and insert the appropriate number of
  460. // newline characters.
  461. if (!MoveToLine(Tok.getLocation()))
  462. return false;
  463. // Print out space characters so that the first token on a line is
  464. // indented for easy reading.
  465. unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
  466. // The first token on a line can have a column number of 1, yet still expect
  467. // leading white space, if a macro expansion in column 1 starts with an empty
  468. // macro argument, or an empty nested macro expansion. In this case, move the
  469. // token to column 2.
  470. if (ColNo == 1 && Tok.hasLeadingSpace())
  471. ColNo = 2;
  472. // This hack prevents stuff like:
  473. // #define HASH #
  474. // HASH define foo bar
  475. // From having the # character end up at column 1, which makes it so it
  476. // is not handled as a #define next time through the preprocessor if in
  477. // -fpreprocessed mode.
  478. if (ColNo <= 1 && Tok.is(tok::hash))
  479. OS << ' ';
  480. // Otherwise, indent the appropriate number of spaces.
  481. for (; ColNo > 1; --ColNo)
  482. OS << ' ';
  483. return true;
  484. }
  485. void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
  486. unsigned Len) {
  487. unsigned NumNewlines = 0;
  488. for (; Len; --Len, ++TokStr) {
  489. if (*TokStr != '\n' &&
  490. *TokStr != '\r')
  491. continue;
  492. ++NumNewlines;
  493. // If we have \n\r or \r\n, skip both and count as one line.
  494. if (Len != 1 &&
  495. (TokStr[1] == '\n' || TokStr[1] == '\r') &&
  496. TokStr[0] != TokStr[1])
  497. ++TokStr, --Len;
  498. }
  499. if (NumNewlines == 0) return;
  500. CurLine += NumNewlines;
  501. }
  502. namespace {
  503. struct UnknownPragmaHandler : public PragmaHandler {
  504. const char *Prefix;
  505. PrintPPOutputPPCallbacks *Callbacks;
  506. // Set to true if tokens should be expanded
  507. bool ShouldExpandTokens;
  508. UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
  509. bool RequireTokenExpansion)
  510. : Prefix(prefix), Callbacks(callbacks),
  511. ShouldExpandTokens(RequireTokenExpansion) {}
  512. void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
  513. Token &PragmaTok) override {
  514. // Figure out what line we went to and insert the appropriate number of
  515. // newline characters.
  516. Callbacks->startNewLineIfNeeded();
  517. Callbacks->MoveToLine(PragmaTok.getLocation());
  518. Callbacks->OS.write(Prefix, strlen(Prefix));
  519. Token PrevToken;
  520. Token PrevPrevToken;
  521. PrevToken.startToken();
  522. PrevPrevToken.startToken();
  523. // Read and print all of the pragma tokens.
  524. while (PragmaTok.isNot(tok::eod)) {
  525. if (PragmaTok.hasLeadingSpace() ||
  526. Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
  527. Callbacks->OS << ' ';
  528. std::string TokSpell = PP.getSpelling(PragmaTok);
  529. Callbacks->OS.write(&TokSpell[0], TokSpell.size());
  530. PrevPrevToken = PrevToken;
  531. PrevToken = PragmaTok;
  532. if (ShouldExpandTokens)
  533. PP.Lex(PragmaTok);
  534. else
  535. PP.LexUnexpandedToken(PragmaTok);
  536. }
  537. Callbacks->setEmittedDirectiveOnThisLine();
  538. }
  539. };
  540. } // end anonymous namespace
  541. static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
  542. PrintPPOutputPPCallbacks *Callbacks,
  543. raw_ostream &OS) {
  544. bool DropComments = PP.getLangOpts().TraditionalCPP &&
  545. !PP.getCommentRetentionState();
  546. char Buffer[256];
  547. Token PrevPrevTok, PrevTok;
  548. PrevPrevTok.startToken();
  549. PrevTok.startToken();
  550. while (1) {
  551. if (Callbacks->hasEmittedDirectiveOnThisLine()) {
  552. Callbacks->startNewLineIfNeeded();
  553. Callbacks->MoveToLine(Tok.getLocation());
  554. }
  555. // If this token is at the start of a line, emit newlines if needed.
  556. if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
  557. // done.
  558. } else if (Tok.hasLeadingSpace() ||
  559. // If we haven't emitted a token on this line yet, PrevTok isn't
  560. // useful to look at and no concatenation could happen anyway.
  561. (Callbacks->hasEmittedTokensOnThisLine() &&
  562. // Don't print "-" next to "-", it would form "--".
  563. Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
  564. OS << ' ';
  565. }
  566. if (DropComments && Tok.is(tok::comment)) {
  567. // Skip comments. Normally the preprocessor does not generate
  568. // tok::comment nodes at all when not keeping comments, but under
  569. // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
  570. SourceLocation StartLoc = Tok.getLocation();
  571. Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
  572. } else if (Tok.is(tok::annot_module_include) ||
  573. Tok.is(tok::annot_module_begin) ||
  574. Tok.is(tok::annot_module_end)) {
  575. // PrintPPOutputPPCallbacks::InclusionDirective handles producing
  576. // appropriate output here. Ignore this token entirely.
  577. PP.Lex(Tok);
  578. continue;
  579. } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
  580. OS << II->getName();
  581. } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
  582. Tok.getLiteralData()) {
  583. OS.write(Tok.getLiteralData(), Tok.getLength());
  584. } else if (Tok.getLength() < 256) {
  585. const char *TokPtr = Buffer;
  586. unsigned Len = PP.getSpelling(Tok, TokPtr);
  587. OS.write(TokPtr, Len);
  588. // Tokens that can contain embedded newlines need to adjust our current
  589. // line number.
  590. if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
  591. Callbacks->HandleNewlinesInToken(TokPtr, Len);
  592. } else {
  593. std::string S = PP.getSpelling(Tok);
  594. OS.write(&S[0], S.size());
  595. // Tokens that can contain embedded newlines need to adjust our current
  596. // line number.
  597. if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
  598. Callbacks->HandleNewlinesInToken(&S[0], S.size());
  599. }
  600. Callbacks->setEmittedTokensOnThisLine();
  601. if (Tok.is(tok::eof)) break;
  602. PrevPrevTok = PrevTok;
  603. PrevTok = Tok;
  604. PP.Lex(Tok);
  605. }
  606. }
  607. typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
  608. // HLSL Change: changed calling convention to __cdecl
  609. static int __cdecl MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
  610. return LHS->first->getName().compare(RHS->first->getName());
  611. }
  612. static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
  613. // Ignore unknown pragmas.
  614. PP.IgnorePragmas();
  615. // -dM mode just scans and ignores all tokens in the files, then dumps out
  616. // the macro table at the end.
  617. PP.EnterMainSourceFile();
  618. Token Tok;
  619. do PP.Lex(Tok);
  620. while (Tok.isNot(tok::eof));
  621. SmallVector<id_macro_pair, 128> MacrosByID;
  622. for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
  623. I != E; ++I) {
  624. auto *MD = I->second.getLatest();
  625. if (MD && MD->isDefined())
  626. MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
  627. }
  628. llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
  629. for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
  630. MacroInfo &MI = *MacrosByID[i].second;
  631. // Ignore computed macros like __LINE__ and friends.
  632. if (MI.isBuiltinMacro()) continue;
  633. PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
  634. *OS << '\n';
  635. }
  636. }
  637. /// DoPrintPreprocessedInput - This implements -E mode.
  638. ///
  639. void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
  640. const PreprocessorOutputOptions &Opts) {
  641. // Show macros with no output is handled specially.
  642. if (!Opts.ShowCPP) {
  643. assert(Opts.ShowMacros && "Not yet implemented!");
  644. DoPrintMacros(PP, OS);
  645. return;
  646. }
  647. // Inform the preprocessor whether we want it to retain comments or not, due
  648. // to -C or -CC.
  649. PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
  650. PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
  651. PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros, Opts.UseLineDirectives);
  652. // Expand macros in pragmas with -fms-extensions. The assumption is that
  653. // the majority of pragmas in such a file will be Microsoft pragmas.
  654. PP.AddPragmaHandler(new UnknownPragmaHandler(
  655. "#pragma", Callbacks,
  656. /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
  657. PP.AddPragmaHandler(
  658. "GCC", new UnknownPragmaHandler(
  659. "#pragma GCC", Callbacks,
  660. /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
  661. PP.AddPragmaHandler(
  662. "clang", new UnknownPragmaHandler(
  663. "#pragma clang", Callbacks,
  664. /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
  665. // The tokens after pragma omp need to be expanded.
  666. //
  667. // OpenMP [2.1, Directive format]
  668. // Preprocessing tokens following the #pragma omp are subject to macro
  669. // replacement.
  670. PP.AddPragmaHandler("omp",
  671. new UnknownPragmaHandler("#pragma omp", Callbacks,
  672. /*RequireTokenExpansion=*/true));
  673. PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
  674. // After we have configured the preprocessor, enter the main file.
  675. PP.EnterMainSourceFile();
  676. // Consume all of the tokens that come from the predefines buffer. Those
  677. // should not be emitted into the output and are guaranteed to be at the
  678. // start.
  679. const SourceManager &SourceMgr = PP.getSourceManager();
  680. Token Tok;
  681. do {
  682. PP.Lex(Tok);
  683. if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
  684. break;
  685. PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
  686. if (PLoc.isInvalid())
  687. break;
  688. if (strcmp(PLoc.getFilename(), "<built-in>"))
  689. break;
  690. } while (true);
  691. // Read all the preprocessed tokens, printing them out to the stream.
  692. PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
  693. *OS << '\n';
  694. }