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