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