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