PrintPreprocessedOutput.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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/Diagnostic.h"
  16. #include "clang/Basic/SourceManager.h"
  17. #include "clang/Frontend/PreprocessorOutputOptions.h"
  18. #include "clang/Lex/MacroInfo.h"
  19. #include "clang/Lex/PPCallbacks.h"
  20. #include "clang/Lex/Pragma.h"
  21. #include "clang/Lex/Preprocessor.h"
  22. #include "clang/Lex/TokenConcatenation.h"
  23. #include "llvm/ADT/SmallString.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/Config/config.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <cstdio>
  29. using namespace clang;
  30. /// PrintMacroDefinition - Print a macro definition in a form that will be
  31. /// properly accepted back as a definition.
  32. static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
  33. Preprocessor &PP, llvm::raw_ostream &OS) {
  34. OS << "#define " << II.getName();
  35. if (MI.isFunctionLike()) {
  36. OS << '(';
  37. if (!MI.arg_empty()) {
  38. MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
  39. for (; AI+1 != E; ++AI) {
  40. OS << (*AI)->getName();
  41. OS << ',';
  42. }
  43. // Last argument.
  44. if ((*AI)->getName() == "__VA_ARGS__")
  45. OS << "...";
  46. else
  47. OS << (*AI)->getName();
  48. }
  49. if (MI.isGNUVarargs())
  50. OS << "..."; // #define foo(x...)
  51. OS << ')';
  52. }
  53. // GCC always emits a space, even if the macro body is empty. However, do not
  54. // want to emit two spaces if the first token has a leading space.
  55. if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
  56. OS << ' ';
  57. llvm::SmallString<128> SpellingBuffer;
  58. for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
  59. I != E; ++I) {
  60. if (I->hasLeadingSpace())
  61. OS << ' ';
  62. OS << PP.getSpelling(*I, 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. llvm::raw_ostream &OS;
  75. private:
  76. unsigned CurLine;
  77. /// The current include nesting level, used by header include dumping (-H).
  78. unsigned CurrentIncludeDepth;
  79. bool EmittedTokensOnThisLine;
  80. bool EmittedMacroOnThisLine;
  81. SrcMgr::CharacteristicKind FileType;
  82. llvm::SmallString<512> CurFilename;
  83. bool Initialized;
  84. bool DisableLineMarkers;
  85. bool DumpDefines;
  86. bool DumpHeaderIncludes;
  87. bool UseLineDirective;
  88. bool HasProcessedPredefines;
  89. public:
  90. PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::raw_ostream &os,
  91. bool lineMarkers, bool defines, bool headers)
  92. : PP(pp), SM(PP.getSourceManager()),
  93. ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
  94. DumpDefines(defines), DumpHeaderIncludes(headers) {
  95. CurLine = CurrentIncludeDepth = 0;
  96. CurFilename += "<uninit>";
  97. EmittedTokensOnThisLine = false;
  98. EmittedMacroOnThisLine = false;
  99. FileType = SrcMgr::C_User;
  100. Initialized = false;
  101. HasProcessedPredefines = false;
  102. // If we're in microsoft mode, use normal #line instead of line markers.
  103. UseLineDirective = PP.getLangOptions().Microsoft;
  104. }
  105. void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
  106. bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
  107. bool StartNewLineIfNeeded();
  108. virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  109. SrcMgr::CharacteristicKind FileType);
  110. virtual void Ident(SourceLocation Loc, const std::string &str);
  111. virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
  112. const std::string &Str);
  113. virtual void PragmaMessage(SourceLocation Loc, llvm::StringRef Str);
  114. bool HandleFirstTokOnLine(Token &Tok);
  115. bool MoveToLine(SourceLocation Loc) {
  116. return MoveToLine(SM.getPresumedLoc(Loc).getLine());
  117. }
  118. bool MoveToLine(unsigned LineNo);
  119. bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
  120. const Token &Tok) {
  121. return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
  122. }
  123. void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
  124. bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
  125. void HandleNewlinesInToken(const char *TokStr, unsigned Len);
  126. /// MacroDefined - This hook is called whenever a macro definition is seen.
  127. void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI);
  128. /// MacroUndefined - This hook is called whenever a macro #undef is seen.
  129. void MacroUndefined(SourceLocation Loc, const IdentifierInfo *II,
  130. const MacroInfo *MI);
  131. };
  132. } // end anonymous namespace
  133. void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
  134. const char *Extra,
  135. unsigned ExtraLen) {
  136. if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
  137. OS << '\n';
  138. EmittedTokensOnThisLine = false;
  139. EmittedMacroOnThisLine = false;
  140. }
  141. // Emit #line directives or GNU line markers depending on what mode we're in.
  142. if (UseLineDirective) {
  143. OS << "#line" << ' ' << LineNo << ' ' << '"';
  144. OS.write(&CurFilename[0], CurFilename.size());
  145. OS << '"';
  146. } else {
  147. OS << '#' << ' ' << LineNo << ' ' << '"';
  148. OS.write(&CurFilename[0], CurFilename.size());
  149. OS << '"';
  150. if (ExtraLen)
  151. OS.write(Extra, ExtraLen);
  152. if (FileType == SrcMgr::C_System)
  153. OS.write(" 3", 2);
  154. else if (FileType == SrcMgr::C_ExternCSystem)
  155. OS.write(" 3 4", 4);
  156. }
  157. OS << '\n';
  158. }
  159. /// MoveToLine - Move the output to the source line specified by the location
  160. /// object. We can do this by emitting some number of \n's, or be emitting a
  161. /// #line directive. This returns false if already at the specified line, true
  162. /// if some newlines were emitted.
  163. bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
  164. // If this line is "close enough" to the original line, just print newlines,
  165. // otherwise print a #line directive.
  166. if (LineNo-CurLine <= 8) {
  167. if (LineNo-CurLine == 1)
  168. OS << '\n';
  169. else if (LineNo == CurLine)
  170. return false; // Spelling line moved, but instantiation line didn't.
  171. else {
  172. const char *NewLines = "\n\n\n\n\n\n\n\n";
  173. OS.write(NewLines, LineNo-CurLine);
  174. }
  175. } else if (!DisableLineMarkers) {
  176. // Emit a #line or line marker.
  177. WriteLineInfo(LineNo, 0, 0);
  178. } else {
  179. // Okay, we're in -P mode, which turns off line markers. However, we still
  180. // need to emit a newline between tokens on different lines.
  181. if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
  182. OS << '\n';
  183. EmittedTokensOnThisLine = false;
  184. EmittedMacroOnThisLine = false;
  185. }
  186. }
  187. CurLine = LineNo;
  188. return true;
  189. }
  190. bool PrintPPOutputPPCallbacks::StartNewLineIfNeeded() {
  191. if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
  192. OS << '\n';
  193. EmittedTokensOnThisLine = false;
  194. EmittedMacroOnThisLine = false;
  195. ++CurLine;
  196. return true;
  197. }
  198. return false;
  199. }
  200. /// FileChanged - Whenever the preprocessor enters or exits a #include file
  201. /// it invokes this handler. Update our conception of the current source
  202. /// position.
  203. void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
  204. FileChangeReason Reason,
  205. SrcMgr::CharacteristicKind NewFileType) {
  206. // Unless we are exiting a #include, make sure to skip ahead to the line the
  207. // #include directive was at.
  208. SourceManager &SourceMgr = SM;
  209. PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
  210. unsigned NewLine = UserLoc.getLine();
  211. if (Reason == PPCallbacks::EnterFile) {
  212. SourceLocation IncludeLoc = SourceMgr.getPresumedLoc(Loc).getIncludeLoc();
  213. if (IncludeLoc.isValid())
  214. MoveToLine(IncludeLoc);
  215. } else if (Reason == PPCallbacks::SystemHeaderPragma) {
  216. MoveToLine(NewLine);
  217. // TODO GCC emits the # directive for this directive on the line AFTER the
  218. // directive and emits a bunch of spaces that aren't needed. Emulate this
  219. // strange behavior.
  220. }
  221. // Adjust the current include depth.
  222. if (Reason == PPCallbacks::EnterFile) {
  223. ++CurrentIncludeDepth;
  224. } else {
  225. if (CurrentIncludeDepth)
  226. --CurrentIncludeDepth;
  227. // We track when we are done with the predefines by watching for the first
  228. // place where we drop back to a nesting depth of 0.
  229. if (CurrentIncludeDepth == 0 && !HasProcessedPredefines)
  230. HasProcessedPredefines = true;
  231. }
  232. CurLine = NewLine;
  233. CurFilename.clear();
  234. CurFilename += UserLoc.getFilename();
  235. Lexer::Stringify(CurFilename);
  236. FileType = NewFileType;
  237. // Dump the header include information, if enabled and we are past the
  238. // predefines buffer.
  239. if (DumpHeaderIncludes && HasProcessedPredefines &&
  240. Reason == PPCallbacks::EnterFile) {
  241. // Write to a temporary string to avoid unnecessary flushing on errs().
  242. llvm::SmallString<256> Msg;
  243. llvm::raw_svector_ostream OS(Msg);
  244. for (unsigned i = 0; i != CurrentIncludeDepth; ++i)
  245. OS << '.';
  246. OS << ' ' << CurFilename << '\n';
  247. llvm::errs() << OS.str();
  248. }
  249. if (DisableLineMarkers) return;
  250. if (!Initialized) {
  251. WriteLineInfo(CurLine);
  252. Initialized = true;
  253. }
  254. switch (Reason) {
  255. case PPCallbacks::EnterFile:
  256. WriteLineInfo(CurLine, " 1", 2);
  257. break;
  258. case PPCallbacks::ExitFile:
  259. WriteLineInfo(CurLine, " 2", 2);
  260. break;
  261. case PPCallbacks::SystemHeaderPragma:
  262. case PPCallbacks::RenameFile:
  263. WriteLineInfo(CurLine);
  264. break;
  265. }
  266. }
  267. /// Ident - Handle #ident directives when read by the preprocessor.
  268. ///
  269. void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
  270. MoveToLine(Loc);
  271. OS.write("#ident ", strlen("#ident "));
  272. OS.write(&S[0], S.size());
  273. EmittedTokensOnThisLine = true;
  274. }
  275. /// MacroDefined - This hook is called whenever a macro definition is seen.
  276. void PrintPPOutputPPCallbacks::MacroDefined(const IdentifierInfo *II,
  277. const MacroInfo *MI) {
  278. // Only print out macro definitions in -dD mode.
  279. if (!DumpDefines ||
  280. // Ignore __FILE__ etc.
  281. MI->isBuiltinMacro()) return;
  282. MoveToLine(MI->getDefinitionLoc());
  283. PrintMacroDefinition(*II, *MI, PP, OS);
  284. EmittedMacroOnThisLine = true;
  285. }
  286. void PrintPPOutputPPCallbacks::MacroUndefined(SourceLocation Loc,
  287. const IdentifierInfo *II,
  288. const MacroInfo *MI) {
  289. // Only print out macro definitions in -dD mode.
  290. if (!DumpDefines) return;
  291. MoveToLine(Loc);
  292. OS << "#undef " << II->getName();
  293. EmittedMacroOnThisLine = true;
  294. }
  295. void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
  296. const IdentifierInfo *Kind,
  297. const std::string &Str) {
  298. MoveToLine(Loc);
  299. OS << "#pragma comment(" << Kind->getName();
  300. if (!Str.empty()) {
  301. OS << ", \"";
  302. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  303. unsigned char Char = Str[i];
  304. if (isprint(Char) && Char != '\\' && Char != '"')
  305. OS << (char)Char;
  306. else // Output anything hard as an octal escape.
  307. OS << '\\'
  308. << (char)('0'+ ((Char >> 6) & 7))
  309. << (char)('0'+ ((Char >> 3) & 7))
  310. << (char)('0'+ ((Char >> 0) & 7));
  311. }
  312. OS << '"';
  313. }
  314. OS << ')';
  315. EmittedTokensOnThisLine = true;
  316. }
  317. void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
  318. llvm::StringRef Str) {
  319. MoveToLine(Loc);
  320. OS << "#pragma message(";
  321. OS << '"';
  322. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  323. unsigned char Char = Str[i];
  324. if (isprint(Char) && Char != '\\' && Char != '"')
  325. OS << (char)Char;
  326. else // Output anything hard as an octal escape.
  327. OS << '\\'
  328. << (char)('0'+ ((Char >> 6) & 7))
  329. << (char)('0'+ ((Char >> 3) & 7))
  330. << (char)('0'+ ((Char >> 0) & 7));
  331. }
  332. OS << '"';
  333. OS << ')';
  334. EmittedTokensOnThisLine = true;
  335. }
  336. /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
  337. /// is called for the first token on each new line. If this really is the start
  338. /// of a new logical line, handle it and return true, otherwise return false.
  339. /// This may not be the start of a logical line because the "start of line"
  340. /// marker is set for spelling lines, not instantiation ones.
  341. bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
  342. // Figure out what line we went to and insert the appropriate number of
  343. // newline characters.
  344. if (!MoveToLine(Tok.getLocation()))
  345. return false;
  346. // Print out space characters so that the first token on a line is
  347. // indented for easy reading.
  348. unsigned ColNo = SM.getInstantiationColumnNumber(Tok.getLocation());
  349. // This hack prevents stuff like:
  350. // #define HASH #
  351. // HASH define foo bar
  352. // From having the # character end up at column 1, which makes it so it
  353. // is not handled as a #define next time through the preprocessor if in
  354. // -fpreprocessed mode.
  355. if (ColNo <= 1 && Tok.is(tok::hash))
  356. OS << ' ';
  357. // Otherwise, indent the appropriate number of spaces.
  358. for (; ColNo > 1; --ColNo)
  359. OS << ' ';
  360. return true;
  361. }
  362. void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
  363. unsigned Len) {
  364. unsigned NumNewlines = 0;
  365. for (; Len; --Len, ++TokStr) {
  366. if (*TokStr != '\n' &&
  367. *TokStr != '\r')
  368. continue;
  369. ++NumNewlines;
  370. // If we have \n\r or \r\n, skip both and count as one line.
  371. if (Len != 1 &&
  372. (TokStr[1] == '\n' || TokStr[1] == '\r') &&
  373. TokStr[0] != TokStr[1])
  374. ++TokStr, --Len;
  375. }
  376. if (NumNewlines == 0) return;
  377. CurLine += NumNewlines;
  378. }
  379. namespace {
  380. struct UnknownPragmaHandler : public PragmaHandler {
  381. const char *Prefix;
  382. PrintPPOutputPPCallbacks *Callbacks;
  383. UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
  384. : Prefix(prefix), Callbacks(callbacks) {}
  385. virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
  386. Token &PragmaTok) {
  387. // Figure out what line we went to and insert the appropriate number of
  388. // newline characters.
  389. Callbacks->StartNewLineIfNeeded();
  390. Callbacks->MoveToLine(PragmaTok.getLocation());
  391. Callbacks->OS.write(Prefix, strlen(Prefix));
  392. Callbacks->SetEmittedTokensOnThisLine();
  393. // Read and print all of the pragma tokens.
  394. while (PragmaTok.isNot(tok::eom)) {
  395. if (PragmaTok.hasLeadingSpace())
  396. Callbacks->OS << ' ';
  397. std::string TokSpell = PP.getSpelling(PragmaTok);
  398. Callbacks->OS.write(&TokSpell[0], TokSpell.size());
  399. PP.LexUnexpandedToken(PragmaTok);
  400. }
  401. Callbacks->StartNewLineIfNeeded();
  402. }
  403. };
  404. } // end anonymous namespace
  405. static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
  406. PrintPPOutputPPCallbacks *Callbacks,
  407. llvm::raw_ostream &OS) {
  408. char Buffer[256];
  409. Token PrevPrevTok, PrevTok;
  410. PrevPrevTok.startToken();
  411. PrevTok.startToken();
  412. while (1) {
  413. // If this token is at the start of a line, emit newlines if needed.
  414. if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
  415. // done.
  416. } else if (Tok.hasLeadingSpace() ||
  417. // If we haven't emitted a token on this line yet, PrevTok isn't
  418. // useful to look at and no concatenation could happen anyway.
  419. (Callbacks->hasEmittedTokensOnThisLine() &&
  420. // Don't print "-" next to "-", it would form "--".
  421. Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
  422. OS << ' ';
  423. }
  424. if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
  425. OS << II->getName();
  426. } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
  427. Tok.getLiteralData()) {
  428. OS.write(Tok.getLiteralData(), Tok.getLength());
  429. } else if (Tok.getLength() < 256) {
  430. const char *TokPtr = Buffer;
  431. unsigned Len = PP.getSpelling(Tok, TokPtr);
  432. OS.write(TokPtr, Len);
  433. // Tokens that can contain embedded newlines need to adjust our current
  434. // line number.
  435. if (Tok.getKind() == tok::comment)
  436. Callbacks->HandleNewlinesInToken(TokPtr, Len);
  437. } else {
  438. std::string S = PP.getSpelling(Tok);
  439. OS.write(&S[0], S.size());
  440. // Tokens that can contain embedded newlines need to adjust our current
  441. // line number.
  442. if (Tok.getKind() == tok::comment)
  443. Callbacks->HandleNewlinesInToken(&S[0], S.size());
  444. }
  445. Callbacks->SetEmittedTokensOnThisLine();
  446. if (Tok.is(tok::eof)) break;
  447. PrevPrevTok = PrevTok;
  448. PrevTok = Tok;
  449. PP.Lex(Tok);
  450. }
  451. }
  452. typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
  453. static int MacroIDCompare(const void* a, const void* b) {
  454. const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
  455. const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
  456. return LHS->first->getName().compare(RHS->first->getName());
  457. }
  458. static void DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) {
  459. // Ignore unknown pragmas.
  460. PP.AddPragmaHandler(new EmptyPragmaHandler());
  461. // -dM mode just scans and ignores all tokens in the files, then dumps out
  462. // the macro table at the end.
  463. PP.EnterMainSourceFile();
  464. Token Tok;
  465. do PP.Lex(Tok);
  466. while (Tok.isNot(tok::eof));
  467. llvm::SmallVector<id_macro_pair, 128>
  468. MacrosByID(PP.macro_begin(), PP.macro_end());
  469. llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
  470. for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
  471. MacroInfo &MI = *MacrosByID[i].second;
  472. // Ignore computed macros like __LINE__ and friends.
  473. if (MI.isBuiltinMacro()) continue;
  474. PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
  475. *OS << '\n';
  476. }
  477. }
  478. /// DoPrintPreprocessedInput - This implements -E mode.
  479. ///
  480. void clang::DoPrintPreprocessedInput(Preprocessor &PP, llvm::raw_ostream *OS,
  481. const PreprocessorOutputOptions &Opts) {
  482. // Show macros with no output is handled specially.
  483. if (!Opts.ShowCPP) {
  484. assert(Opts.ShowMacros && "Not yet implemented!");
  485. DoPrintMacros(PP, OS);
  486. return;
  487. }
  488. // Inform the preprocessor whether we want it to retain comments or not, due
  489. // to -C or -CC.
  490. PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
  491. PrintPPOutputPPCallbacks *Callbacks =
  492. new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
  493. Opts.ShowMacros, Opts.ShowHeaderIncludes);
  494. PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
  495. PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",
  496. Callbacks));
  497. PP.addPPCallbacks(Callbacks);
  498. // After we have configured the preprocessor, enter the main file.
  499. PP.EnterMainSourceFile();
  500. // Consume all of the tokens that come from the predefines buffer. Those
  501. // should not be emitted into the output and are guaranteed to be at the
  502. // start.
  503. const SourceManager &SourceMgr = PP.getSourceManager();
  504. Token Tok;
  505. do PP.Lex(Tok);
  506. while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
  507. !strcmp(SourceMgr.getPresumedLoc(Tok.getLocation()).getFilename(),
  508. "<built-in>"));
  509. // Read all the preprocessed tokens, printing them out to the stream.
  510. PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
  511. *OS << '\n';
  512. }