xref: /llvm-project/clang/lib/Frontend/PrintPreprocessedOutput.cpp (revision e77a01d79a48e15c94c89e4aa4bd27424a96b49b)
1 //===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This code simply runs the preprocessor on the input file and prints out the
10 // result.  This is the traditional behavior of the -E option.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/CharInfo.h"
15 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Frontend/PreprocessorOutputOptions.h"
18 #include "clang/Frontend/Utils.h"
19 #include "clang/Lex/MacroInfo.h"
20 #include "clang/Lex/PPCallbacks.h"
21 #include "clang/Lex/Pragma.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Lex/TokenConcatenation.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <cstdio>
30 using namespace clang;
31 
32 /// PrintMacroDefinition - Print a macro definition in a form that will be
33 /// properly accepted back as a definition.
34 static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
35                                  Preprocessor &PP, raw_ostream *OS) {
36   *OS << "#define " << II.getName();
37 
38   if (MI.isFunctionLike()) {
39     *OS << '(';
40     if (!MI.param_empty()) {
41       MacroInfo::param_iterator AI = MI.param_begin(), E = MI.param_end();
42       for (; AI+1 != E; ++AI) {
43         *OS << (*AI)->getName();
44         *OS << ',';
45       }
46 
47       // Last argument.
48       if ((*AI)->getName() == "__VA_ARGS__")
49         *OS << "...";
50       else
51         *OS << (*AI)->getName();
52     }
53 
54     if (MI.isGNUVarargs())
55       *OS << "...";  // #define foo(x...)
56 
57     *OS << ')';
58   }
59 
60   // GCC always emits a space, even if the macro body is empty.  However, do not
61   // want to emit two spaces if the first token has a leading space.
62   if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
63     *OS << ' ';
64 
65   SmallString<128> SpellingBuffer;
66   for (const auto &T : MI.tokens()) {
67     if (T.hasLeadingSpace())
68       *OS << ' ';
69 
70     *OS << PP.getSpelling(T, SpellingBuffer);
71   }
72 }
73 
74 //===----------------------------------------------------------------------===//
75 // Preprocessed token printer
76 //===----------------------------------------------------------------------===//
77 
78 namespace {
79 class PrintPPOutputPPCallbacks : public PPCallbacks {
80   Preprocessor &PP;
81   SourceManager &SM;
82   TokenConcatenation ConcatInfo;
83 public:
84   raw_ostream *OS;
85 private:
86   unsigned CurLine;
87 
88   bool EmittedTokensOnThisLine;
89   bool EmittedDirectiveOnThisLine;
90   SrcMgr::CharacteristicKind FileType;
91   SmallString<512> CurFilename;
92   bool Initialized;
93   bool DisableLineMarkers;
94   bool DumpDefines;
95   bool DumpIncludeDirectives;
96   bool DumpEmbedDirectives;
97   bool UseLineDirectives;
98   bool IsFirstFileEntered;
99   bool MinimizeWhitespace;
100   bool DirectivesOnly;
101   bool KeepSystemIncludes;
102   raw_ostream *OrigOS;
103   std::unique_ptr<llvm::raw_null_ostream> NullOS;
104   unsigned NumToksToSkip;
105 
106   Token PrevTok;
107   Token PrevPrevTok;
108 
109 public:
110   PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream *os, bool lineMarkers,
111                            bool defines, bool DumpIncludeDirectives,
112                            bool DumpEmbedDirectives, bool UseLineDirectives,
113                            bool MinimizeWhitespace, bool DirectivesOnly,
114                            bool KeepSystemIncludes)
115       : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
116         DisableLineMarkers(lineMarkers), DumpDefines(defines),
117         DumpIncludeDirectives(DumpIncludeDirectives),
118         DumpEmbedDirectives(DumpEmbedDirectives),
119         UseLineDirectives(UseLineDirectives),
120         MinimizeWhitespace(MinimizeWhitespace), DirectivesOnly(DirectivesOnly),
121         KeepSystemIncludes(KeepSystemIncludes), OrigOS(os), NumToksToSkip(0) {
122     CurLine = 0;
123     CurFilename += "<uninit>";
124     EmittedTokensOnThisLine = false;
125     EmittedDirectiveOnThisLine = false;
126     FileType = SrcMgr::C_User;
127     Initialized = false;
128     IsFirstFileEntered = false;
129     if (KeepSystemIncludes)
130       NullOS = std::make_unique<llvm::raw_null_ostream>();
131 
132     PrevTok.startToken();
133     PrevPrevTok.startToken();
134   }
135 
136   /// Returns true if #embed directives should be expanded into a comma-
137   /// delimited list of integer constants or not.
138   bool expandEmbedContents() const { return !DumpEmbedDirectives; }
139 
140   bool isMinimizeWhitespace() const { return MinimizeWhitespace; }
141 
142   void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
143   bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
144 
145   void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
146   bool hasEmittedDirectiveOnThisLine() const {
147     return EmittedDirectiveOnThisLine;
148   }
149 
150   /// Ensure that the output stream position is at the beginning of a new line
151   /// and inserts one if it does not. It is intended to ensure that directives
152   /// inserted by the directives not from the input source (such as #line) are
153   /// in the first column. To insert newlines that represent the input, use
154   /// MoveToLine(/*...*/, /*RequireStartOfLine=*/true).
155   void startNewLineIfNeeded();
156 
157   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
158                    SrcMgr::CharacteristicKind FileType,
159                    FileID PrevFID) override;
160   void EmbedDirective(SourceLocation HashLoc, StringRef FileName, bool IsAngled,
161                       OptionalFileEntryRef File,
162                       const LexEmbedParametersResult &Params) override;
163   void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
164                           StringRef FileName, bool IsAngled,
165                           CharSourceRange FilenameRange,
166                           OptionalFileEntryRef File, StringRef SearchPath,
167                           StringRef RelativePath, const Module *SuggestedModule,
168                           bool ModuleImported,
169                           SrcMgr::CharacteristicKind FileType) override;
170   void Ident(SourceLocation Loc, StringRef str) override;
171   void PragmaMessage(SourceLocation Loc, StringRef Namespace,
172                      PragmaMessageKind Kind, StringRef Str) override;
173   void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
174   void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
175   void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
176   void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
177                         diag::Severity Map, StringRef Str) override;
178   void PragmaWarning(SourceLocation Loc, PragmaWarningSpecifier WarningSpec,
179                      ArrayRef<int> Ids) override;
180   void PragmaWarningPush(SourceLocation Loc, int Level) override;
181   void PragmaWarningPop(SourceLocation Loc) override;
182   void PragmaExecCharsetPush(SourceLocation Loc, StringRef Str) override;
183   void PragmaExecCharsetPop(SourceLocation Loc) override;
184   void PragmaAssumeNonNullBegin(SourceLocation Loc) override;
185   void PragmaAssumeNonNullEnd(SourceLocation Loc) override;
186 
187   /// Insert whitespace before emitting the next token.
188   ///
189   /// @param Tok             Next token to be emitted.
190   /// @param RequireSpace    Ensure at least one whitespace is emitted. Useful
191   ///                        if non-tokens have been emitted to the stream.
192   /// @param RequireSameLine Never emit newlines. Useful when semantics depend
193   ///                        on being on the same line, such as directives.
194   void HandleWhitespaceBeforeTok(const Token &Tok, bool RequireSpace,
195                                  bool RequireSameLine);
196 
197   /// Move to the line of the provided source location. This will
198   /// return true if a newline was inserted or if
199   /// the requested location is the first token on the first line.
200   /// In these cases the next output will be the first column on the line and
201   /// make it possible to insert indention. The newline was inserted
202   /// implicitly when at the beginning of the file.
203   ///
204   /// @param Tok                 Token where to move to.
205   /// @param RequireStartOfLine  Whether the next line depends on being in the
206   ///                            first column, such as a directive.
207   ///
208   /// @return Whether column adjustments are necessary.
209   bool MoveToLine(const Token &Tok, bool RequireStartOfLine) {
210     PresumedLoc PLoc = SM.getPresumedLoc(Tok.getLocation());
211     unsigned TargetLine = PLoc.isValid() ? PLoc.getLine() : CurLine;
212     bool IsFirstInFile =
213         Tok.isAtStartOfLine() && PLoc.isValid() && PLoc.getLine() == 1;
214     return MoveToLine(TargetLine, RequireStartOfLine) || IsFirstInFile;
215   }
216 
217   /// Move to the line of the provided source location. Returns true if a new
218   /// line was inserted.
219   bool MoveToLine(SourceLocation Loc, bool RequireStartOfLine) {
220     PresumedLoc PLoc = SM.getPresumedLoc(Loc);
221     unsigned TargetLine = PLoc.isValid() ? PLoc.getLine() : CurLine;
222     return MoveToLine(TargetLine, RequireStartOfLine);
223   }
224   bool MoveToLine(unsigned LineNo, bool RequireStartOfLine);
225 
226   bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
227                    const Token &Tok) {
228     return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
229   }
230   void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
231                      unsigned ExtraLen=0);
232   bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
233   void HandleNewlinesInToken(const char *TokStr, unsigned Len);
234 
235   /// MacroDefined - This hook is called whenever a macro definition is seen.
236   void MacroDefined(const Token &MacroNameTok,
237                     const MacroDirective *MD) override;
238 
239   /// MacroUndefined - This hook is called whenever a macro #undef is seen.
240   void MacroUndefined(const Token &MacroNameTok,
241                       const MacroDefinition &MD,
242                       const MacroDirective *Undef) override;
243 
244   void BeginModule(const Module *M);
245   void EndModule(const Module *M);
246 
247   unsigned GetNumToksToSkip() const { return NumToksToSkip; }
248   void ResetSkipToks() { NumToksToSkip = 0; }
249 };
250 }  // end anonymous namespace
251 
252 void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
253                                              const char *Extra,
254                                              unsigned ExtraLen) {
255   startNewLineIfNeeded();
256 
257   // Emit #line directives or GNU line markers depending on what mode we're in.
258   if (UseLineDirectives) {
259     *OS << "#line" << ' ' << LineNo << ' ' << '"';
260     OS->write_escaped(CurFilename);
261     *OS << '"';
262   } else {
263     *OS << '#' << ' ' << LineNo << ' ' << '"';
264     OS->write_escaped(CurFilename);
265     *OS << '"';
266 
267     if (ExtraLen)
268       OS->write(Extra, ExtraLen);
269 
270     if (FileType == SrcMgr::C_System)
271       OS->write(" 3", 2);
272     else if (FileType == SrcMgr::C_ExternCSystem)
273       OS->write(" 3 4", 4);
274   }
275   *OS << '\n';
276 }
277 
278 /// MoveToLine - Move the output to the source line specified by the location
279 /// object.  We can do this by emitting some number of \n's, or be emitting a
280 /// #line directive.  This returns false if already at the specified line, true
281 /// if some newlines were emitted.
282 bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo,
283                                           bool RequireStartOfLine) {
284   // If it is required to start a new line or finish the current, insert
285   // vertical whitespace now and take it into account when moving to the
286   // expected line.
287   bool StartedNewLine = false;
288   if ((RequireStartOfLine && EmittedTokensOnThisLine) ||
289       EmittedDirectiveOnThisLine) {
290     *OS << '\n';
291     StartedNewLine = true;
292     CurLine += 1;
293     EmittedTokensOnThisLine = false;
294     EmittedDirectiveOnThisLine = false;
295   }
296 
297   // If this line is "close enough" to the original line, just print newlines,
298   // otherwise print a #line directive.
299   if (CurLine == LineNo) {
300     // Nothing to do if we are already on the correct line.
301   } else if (MinimizeWhitespace && DisableLineMarkers) {
302     // With -E -P -fminimize-whitespace, don't emit anything if not necessary.
303   } else if (!StartedNewLine && LineNo - CurLine == 1) {
304     // Printing a single line has priority over printing a #line directive, even
305     // when minimizing whitespace which otherwise would print #line directives
306     // for every single line.
307     *OS << '\n';
308     StartedNewLine = true;
309   } else if (!DisableLineMarkers) {
310     if (LineNo - CurLine <= 8) {
311       const char *NewLines = "\n\n\n\n\n\n\n\n";
312       OS->write(NewLines, LineNo - CurLine);
313     } else {
314       // Emit a #line or line marker.
315       WriteLineInfo(LineNo, nullptr, 0);
316     }
317     StartedNewLine = true;
318   } else if (EmittedTokensOnThisLine) {
319     // If we are not on the correct line and don't need to be line-correct,
320     // at least ensure we start on a new line.
321     *OS << '\n';
322     StartedNewLine = true;
323   }
324 
325   if (StartedNewLine) {
326     EmittedTokensOnThisLine = false;
327     EmittedDirectiveOnThisLine = false;
328   }
329 
330   CurLine = LineNo;
331   return StartedNewLine;
332 }
333 
334 void PrintPPOutputPPCallbacks::startNewLineIfNeeded() {
335   if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
336     *OS << '\n';
337     EmittedTokensOnThisLine = false;
338     EmittedDirectiveOnThisLine = false;
339   }
340 }
341 
342 /// FileChanged - Whenever the preprocessor enters or exits a #include file
343 /// it invokes this handler.  Update our conception of the current source
344 /// position.
345 void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
346                                            FileChangeReason Reason,
347                                        SrcMgr::CharacteristicKind NewFileType,
348                                        FileID PrevFID) {
349   // Unless we are exiting a #include, make sure to skip ahead to the line the
350   // #include directive was at.
351   SourceManager &SourceMgr = SM;
352 
353   PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
354   if (UserLoc.isInvalid())
355     return;
356 
357   unsigned NewLine = UserLoc.getLine();
358 
359   if (Reason == PPCallbacks::EnterFile) {
360     SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
361     if (IncludeLoc.isValid())
362       MoveToLine(IncludeLoc, /*RequireStartOfLine=*/false);
363   } else if (Reason == PPCallbacks::SystemHeaderPragma) {
364     // GCC emits the # directive for this directive on the line AFTER the
365     // directive and emits a bunch of spaces that aren't needed. This is because
366     // otherwise we will emit a line marker for THIS line, which requires an
367     // extra blank line after the directive to avoid making all following lines
368     // off by one. We can do better by simply incrementing NewLine here.
369     NewLine += 1;
370   }
371 
372   CurLine = NewLine;
373 
374   // In KeepSystemIncludes mode, redirect OS as needed.
375   if (KeepSystemIncludes && (isSystem(FileType) != isSystem(NewFileType)))
376     OS = isSystem(FileType) ? OrigOS : NullOS.get();
377 
378   CurFilename.clear();
379   CurFilename += UserLoc.getFilename();
380   FileType = NewFileType;
381 
382   if (DisableLineMarkers) {
383     if (!MinimizeWhitespace)
384       startNewLineIfNeeded();
385     return;
386   }
387 
388   if (!Initialized) {
389     WriteLineInfo(CurLine);
390     Initialized = true;
391   }
392 
393   // Do not emit an enter marker for the main file (which we expect is the first
394   // entered file). This matches gcc, and improves compatibility with some tools
395   // which track the # line markers as a way to determine when the preprocessed
396   // output is in the context of the main file.
397   if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
398     IsFirstFileEntered = true;
399     return;
400   }
401 
402   switch (Reason) {
403   case PPCallbacks::EnterFile:
404     WriteLineInfo(CurLine, " 1", 2);
405     break;
406   case PPCallbacks::ExitFile:
407     WriteLineInfo(CurLine, " 2", 2);
408     break;
409   case PPCallbacks::SystemHeaderPragma:
410   case PPCallbacks::RenameFile:
411     WriteLineInfo(CurLine);
412     break;
413   }
414 }
415 
416 void PrintPPOutputPPCallbacks::EmbedDirective(
417     SourceLocation HashLoc, StringRef FileName, bool IsAngled,
418     OptionalFileEntryRef File, const LexEmbedParametersResult &Params) {
419   if (!DumpEmbedDirectives)
420     return;
421 
422   // The EmbedDirective() callback is called before we produce the annotation
423   // token stream for the directive. We skip printing the annotation tokens
424   // within PrintPreprocessedTokens(), but we also need to skip the prefix,
425   // suffix, and if_empty tokens as those are inserted directly into the token
426   // stream and would otherwise be printed immediately after printing the
427   // #embed directive.
428   //
429   // FIXME: counting tokens to skip is a kludge but we have no way to know
430   // which tokens were inserted as part of the embed and which ones were
431   // explicitly written by the user.
432   MoveToLine(HashLoc, /*RequireStartOfLine=*/true);
433   *OS << "#embed " << (IsAngled ? '<' : '"') << FileName
434       << (IsAngled ? '>' : '"');
435 
436   auto PrintToks = [&](llvm::ArrayRef<Token> Toks) {
437     SmallString<128> SpellingBuffer;
438     for (const Token &T : Toks) {
439       if (T.hasLeadingSpace())
440         *OS << " ";
441       *OS << PP.getSpelling(T, SpellingBuffer);
442     }
443   };
444   bool SkipAnnotToks = true;
445   if (Params.MaybeIfEmptyParam) {
446     *OS << " if_empty(";
447     PrintToks(Params.MaybeIfEmptyParam->Tokens);
448     *OS << ")";
449     // If the file is empty, we can skip those tokens. If the file is not
450     // empty, we skip the annotation tokens.
451     if (File && !File->getSize()) {
452       NumToksToSkip += Params.MaybeIfEmptyParam->Tokens.size();
453       SkipAnnotToks = false;
454     }
455   }
456 
457   if (Params.MaybeLimitParam) {
458     *OS << " limit(" << Params.MaybeLimitParam->Limit << ")";
459   }
460   if (Params.MaybeOffsetParam) {
461     *OS << " clang::offset(" << Params.MaybeOffsetParam->Offset << ")";
462   }
463   if (Params.MaybePrefixParam) {
464     *OS << " prefix(";
465     PrintToks(Params.MaybePrefixParam->Tokens);
466     *OS << ")";
467     NumToksToSkip += Params.MaybePrefixParam->Tokens.size();
468   }
469   if (Params.MaybeSuffixParam) {
470     *OS << " suffix(";
471     PrintToks(Params.MaybeSuffixParam->Tokens);
472     *OS << ")";
473     NumToksToSkip += Params.MaybeSuffixParam->Tokens.size();
474   }
475 
476   // We may need to skip the annotation token.
477   if (SkipAnnotToks)
478     NumToksToSkip++;
479 
480   *OS << " /* clang -E -dE */";
481   setEmittedDirectiveOnThisLine();
482 }
483 
484 void PrintPPOutputPPCallbacks::InclusionDirective(
485     SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName,
486     bool IsAngled, CharSourceRange FilenameRange, OptionalFileEntryRef File,
487     StringRef SearchPath, StringRef RelativePath, const Module *SuggestedModule,
488     bool ModuleImported, SrcMgr::CharacteristicKind FileType) {
489   // In -dI mode, dump #include directives prior to dumping their content or
490   // interpretation. Similar for -fkeep-system-includes.
491   if (DumpIncludeDirectives || (KeepSystemIncludes && isSystem(FileType))) {
492     MoveToLine(HashLoc, /*RequireStartOfLine=*/true);
493     const std::string TokenText = PP.getSpelling(IncludeTok);
494     assert(!TokenText.empty());
495     *OS << "#" << TokenText << " "
496         << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
497         << " /* clang -E "
498         << (DumpIncludeDirectives ? "-dI" : "-fkeep-system-includes")
499         << " */";
500     setEmittedDirectiveOnThisLine();
501   }
502 
503   // When preprocessing, turn implicit imports into module import pragmas.
504   if (ModuleImported) {
505     switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
506     case tok::pp_include:
507     case tok::pp_import:
508     case tok::pp_include_next:
509       MoveToLine(HashLoc, /*RequireStartOfLine=*/true);
510       *OS << "#pragma clang module import "
511           << SuggestedModule->getFullModuleName(true)
512           << " /* clang -E: implicit import for "
513           << "#" << PP.getSpelling(IncludeTok) << " "
514           << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
515           << " */";
516       setEmittedDirectiveOnThisLine();
517       break;
518 
519     case tok::pp___include_macros:
520       // #__include_macros has no effect on a user of a preprocessed source
521       // file; the only effect is on preprocessing.
522       //
523       // FIXME: That's not *quite* true: it causes the module in question to
524       // be loaded, which can affect downstream diagnostics.
525       break;
526 
527     default:
528       llvm_unreachable("unknown include directive kind");
529       break;
530     }
531   }
532 }
533 
534 /// Handle entering the scope of a module during a module compilation.
535 void PrintPPOutputPPCallbacks::BeginModule(const Module *M) {
536   startNewLineIfNeeded();
537   *OS << "#pragma clang module begin " << M->getFullModuleName(true);
538   setEmittedDirectiveOnThisLine();
539 }
540 
541 /// Handle leaving the scope of a module during a module compilation.
542 void PrintPPOutputPPCallbacks::EndModule(const Module *M) {
543   startNewLineIfNeeded();
544   *OS << "#pragma clang module end /*" << M->getFullModuleName(true) << "*/";
545   setEmittedDirectiveOnThisLine();
546 }
547 
548 /// Ident - Handle #ident directives when read by the preprocessor.
549 ///
550 void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
551   MoveToLine(Loc, /*RequireStartOfLine=*/true);
552 
553   OS->write("#ident ", strlen("#ident "));
554   OS->write(S.begin(), S.size());
555   setEmittedTokensOnThisLine();
556 }
557 
558 /// MacroDefined - This hook is called whenever a macro definition is seen.
559 void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
560                                             const MacroDirective *MD) {
561   const MacroInfo *MI = MD->getMacroInfo();
562   // Print out macro definitions in -dD mode and when we have -fdirectives-only
563   // for C++20 header units.
564   if ((!DumpDefines && !DirectivesOnly) ||
565       // Ignore __FILE__ etc.
566       MI->isBuiltinMacro())
567     return;
568 
569   SourceLocation DefLoc = MI->getDefinitionLoc();
570   if (DirectivesOnly && !MI->isUsed()) {
571     SourceManager &SM = PP.getSourceManager();
572     if (SM.isWrittenInBuiltinFile(DefLoc) ||
573         SM.isWrittenInCommandLineFile(DefLoc))
574       return;
575   }
576   MoveToLine(DefLoc, /*RequireStartOfLine=*/true);
577   PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
578   setEmittedDirectiveOnThisLine();
579 }
580 
581 void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
582                                               const MacroDefinition &MD,
583                                               const MacroDirective *Undef) {
584   // Print out macro definitions in -dD mode and when we have -fdirectives-only
585   // for C++20 header units.
586   if (!DumpDefines && !DirectivesOnly)
587     return;
588 
589   MoveToLine(MacroNameTok.getLocation(), /*RequireStartOfLine=*/true);
590   *OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
591   setEmittedDirectiveOnThisLine();
592 }
593 
594 static void outputPrintable(raw_ostream *OS, StringRef Str) {
595   for (unsigned char Char : Str) {
596     if (isPrintable(Char) && Char != '\\' && Char != '"')
597       *OS << (char)Char;
598     else // Output anything hard as an octal escape.
599       *OS << '\\'
600           << (char)('0' + ((Char >> 6) & 7))
601           << (char)('0' + ((Char >> 3) & 7))
602           << (char)('0' + ((Char >> 0) & 7));
603   }
604 }
605 
606 void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
607                                              StringRef Namespace,
608                                              PragmaMessageKind Kind,
609                                              StringRef Str) {
610   MoveToLine(Loc, /*RequireStartOfLine=*/true);
611   *OS << "#pragma ";
612   if (!Namespace.empty())
613     *OS << Namespace << ' ';
614   switch (Kind) {
615     case PMK_Message:
616       *OS << "message(\"";
617       break;
618     case PMK_Warning:
619       *OS << "warning \"";
620       break;
621     case PMK_Error:
622       *OS << "error \"";
623       break;
624   }
625 
626   outputPrintable(OS, Str);
627   *OS << '"';
628   if (Kind == PMK_Message)
629     *OS << ')';
630   setEmittedDirectiveOnThisLine();
631 }
632 
633 void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
634                                            StringRef DebugType) {
635   MoveToLine(Loc, /*RequireStartOfLine=*/true);
636 
637   *OS << "#pragma clang __debug ";
638   *OS << DebugType;
639 
640   setEmittedDirectiveOnThisLine();
641 }
642 
643 void PrintPPOutputPPCallbacks::
644 PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
645   MoveToLine(Loc, /*RequireStartOfLine=*/true);
646   *OS << "#pragma " << Namespace << " diagnostic push";
647   setEmittedDirectiveOnThisLine();
648 }
649 
650 void PrintPPOutputPPCallbacks::
651 PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
652   MoveToLine(Loc, /*RequireStartOfLine=*/true);
653   *OS << "#pragma " << Namespace << " diagnostic pop";
654   setEmittedDirectiveOnThisLine();
655 }
656 
657 void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
658                                                 StringRef Namespace,
659                                                 diag::Severity Map,
660                                                 StringRef Str) {
661   MoveToLine(Loc, /*RequireStartOfLine=*/true);
662   *OS << "#pragma " << Namespace << " diagnostic ";
663   switch (Map) {
664   case diag::Severity::Remark:
665     *OS << "remark";
666     break;
667   case diag::Severity::Warning:
668     *OS << "warning";
669     break;
670   case diag::Severity::Error:
671     *OS << "error";
672     break;
673   case diag::Severity::Ignored:
674     *OS << "ignored";
675     break;
676   case diag::Severity::Fatal:
677     *OS << "fatal";
678     break;
679   }
680   *OS << " \"" << Str << '"';
681   setEmittedDirectiveOnThisLine();
682 }
683 
684 void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
685                                              PragmaWarningSpecifier WarningSpec,
686                                              ArrayRef<int> Ids) {
687   MoveToLine(Loc, /*RequireStartOfLine=*/true);
688 
689   *OS << "#pragma warning(";
690   switch(WarningSpec) {
691     case PWS_Default:  *OS << "default"; break;
692     case PWS_Disable:  *OS << "disable"; break;
693     case PWS_Error:    *OS << "error"; break;
694     case PWS_Once:     *OS << "once"; break;
695     case PWS_Suppress: *OS << "suppress"; break;
696     case PWS_Level1:   *OS << '1'; break;
697     case PWS_Level2:   *OS << '2'; break;
698     case PWS_Level3:   *OS << '3'; break;
699     case PWS_Level4:   *OS << '4'; break;
700   }
701   *OS << ':';
702 
703   for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
704     *OS << ' ' << *I;
705   *OS << ')';
706   setEmittedDirectiveOnThisLine();
707 }
708 
709 void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
710                                                  int Level) {
711   MoveToLine(Loc, /*RequireStartOfLine=*/true);
712   *OS << "#pragma warning(push";
713   if (Level >= 0)
714     *OS << ", " << Level;
715   *OS << ')';
716   setEmittedDirectiveOnThisLine();
717 }
718 
719 void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
720   MoveToLine(Loc, /*RequireStartOfLine=*/true);
721   *OS << "#pragma warning(pop)";
722   setEmittedDirectiveOnThisLine();
723 }
724 
725 void PrintPPOutputPPCallbacks::PragmaExecCharsetPush(SourceLocation Loc,
726                                                      StringRef Str) {
727   MoveToLine(Loc, /*RequireStartOfLine=*/true);
728   *OS << "#pragma character_execution_set(push";
729   if (!Str.empty())
730     *OS << ", " << Str;
731   *OS << ')';
732   setEmittedDirectiveOnThisLine();
733 }
734 
735 void PrintPPOutputPPCallbacks::PragmaExecCharsetPop(SourceLocation Loc) {
736   MoveToLine(Loc, /*RequireStartOfLine=*/true);
737   *OS << "#pragma character_execution_set(pop)";
738   setEmittedDirectiveOnThisLine();
739 }
740 
741 void PrintPPOutputPPCallbacks::
742 PragmaAssumeNonNullBegin(SourceLocation Loc) {
743   MoveToLine(Loc, /*RequireStartOfLine=*/true);
744   *OS << "#pragma clang assume_nonnull begin";
745   setEmittedDirectiveOnThisLine();
746 }
747 
748 void PrintPPOutputPPCallbacks::
749 PragmaAssumeNonNullEnd(SourceLocation Loc) {
750   MoveToLine(Loc, /*RequireStartOfLine=*/true);
751   *OS << "#pragma clang assume_nonnull end";
752   setEmittedDirectiveOnThisLine();
753 }
754 
755 void PrintPPOutputPPCallbacks::HandleWhitespaceBeforeTok(const Token &Tok,
756                                                          bool RequireSpace,
757                                                          bool RequireSameLine) {
758   // These tokens are not expanded to anything and don't need whitespace before
759   // them.
760   if (Tok.is(tok::eof) ||
761       (Tok.isAnnotation() && Tok.isNot(tok::annot_header_unit) &&
762        Tok.isNot(tok::annot_module_begin) && Tok.isNot(tok::annot_module_end) &&
763        Tok.isNot(tok::annot_module_name) &&
764        Tok.isNot(tok::annot_repl_input_end) && Tok.isNot(tok::annot_embed)))
765     return;
766 
767   // EmittedDirectiveOnThisLine takes priority over RequireSameLine.
768   if ((!RequireSameLine || EmittedDirectiveOnThisLine) &&
769       MoveToLine(Tok, /*RequireStartOfLine=*/EmittedDirectiveOnThisLine)) {
770     if (MinimizeWhitespace) {
771       // Avoid interpreting hash as a directive under -fpreprocessed.
772       if (Tok.is(tok::hash))
773         *OS << ' ';
774     } else {
775       // Print out space characters so that the first token on a line is
776       // indented for easy reading.
777       unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
778 
779       // The first token on a line can have a column number of 1, yet still
780       // expect leading white space, if a macro expansion in column 1 starts
781       // with an empty macro argument, or an empty nested macro expansion. In
782       // this case, move the token to column 2.
783       if (ColNo == 1 && Tok.hasLeadingSpace())
784         ColNo = 2;
785 
786       // This hack prevents stuff like:
787       // #define HASH #
788       // HASH define foo bar
789       // From having the # character end up at column 1, which makes it so it
790       // is not handled as a #define next time through the preprocessor if in
791       // -fpreprocessed mode.
792       if (ColNo <= 1 && Tok.is(tok::hash))
793         *OS << ' ';
794 
795       // Otherwise, indent the appropriate number of spaces.
796       for (; ColNo > 1; --ColNo)
797         *OS << ' ';
798     }
799   } else {
800     // Insert whitespace between the previous and next token if either
801     // - The caller requires it
802     // - The input had whitespace between them and we are not in
803     //   whitespace-minimization mode
804     // - The whitespace is necessary to keep the tokens apart and there is not
805     //   already a newline between them
806     if (RequireSpace || (!MinimizeWhitespace && Tok.hasLeadingSpace()) ||
807         ((EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) &&
808          AvoidConcat(PrevPrevTok, PrevTok, Tok)))
809       *OS << ' ';
810   }
811 
812   PrevPrevTok = PrevTok;
813   PrevTok = Tok;
814 }
815 
816 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
817                                                      unsigned Len) {
818   unsigned NumNewlines = 0;
819   for (; Len; --Len, ++TokStr) {
820     if (*TokStr != '\n' &&
821         *TokStr != '\r')
822       continue;
823 
824     ++NumNewlines;
825 
826     // If we have \n\r or \r\n, skip both and count as one line.
827     if (Len != 1 &&
828         (TokStr[1] == '\n' || TokStr[1] == '\r') &&
829         TokStr[0] != TokStr[1]) {
830       ++TokStr;
831       --Len;
832     }
833   }
834 
835   if (NumNewlines == 0) return;
836 
837   CurLine += NumNewlines;
838 }
839 
840 
841 namespace {
842 struct UnknownPragmaHandler : public PragmaHandler {
843   const char *Prefix;
844   PrintPPOutputPPCallbacks *Callbacks;
845 
846   // Set to true if tokens should be expanded
847   bool ShouldExpandTokens;
848 
849   UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
850                        bool RequireTokenExpansion)
851       : Prefix(prefix), Callbacks(callbacks),
852         ShouldExpandTokens(RequireTokenExpansion) {}
853   void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
854                     Token &PragmaTok) override {
855     // Figure out what line we went to and insert the appropriate number of
856     // newline characters.
857     Callbacks->MoveToLine(PragmaTok.getLocation(), /*RequireStartOfLine=*/true);
858     Callbacks->OS->write(Prefix, strlen(Prefix));
859     Callbacks->setEmittedTokensOnThisLine();
860 
861     if (ShouldExpandTokens) {
862       // The first token does not have expanded macros. Expand them, if
863       // required.
864       auto Toks = std::make_unique<Token[]>(1);
865       Toks[0] = PragmaTok;
866       PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
867                           /*DisableMacroExpansion=*/false,
868                           /*IsReinject=*/false);
869       PP.Lex(PragmaTok);
870     }
871 
872     // Read and print all of the pragma tokens.
873     bool IsFirst = true;
874     while (PragmaTok.isNot(tok::eod)) {
875       Callbacks->HandleWhitespaceBeforeTok(PragmaTok, /*RequireSpace=*/IsFirst,
876                                            /*RequireSameLine=*/true);
877       IsFirst = false;
878       std::string TokSpell = PP.getSpelling(PragmaTok);
879       Callbacks->OS->write(&TokSpell[0], TokSpell.size());
880       Callbacks->setEmittedTokensOnThisLine();
881 
882       if (ShouldExpandTokens)
883         PP.Lex(PragmaTok);
884       else
885         PP.LexUnexpandedToken(PragmaTok);
886     }
887     Callbacks->setEmittedDirectiveOnThisLine();
888   }
889 };
890 } // end anonymous namespace
891 
892 
893 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
894                                     PrintPPOutputPPCallbacks *Callbacks) {
895   bool DropComments = PP.getLangOpts().TraditionalCPP &&
896                       !PP.getCommentRetentionState();
897 
898   bool IsStartOfLine = false;
899   char Buffer[256];
900   while (true) {
901     // Two lines joined with line continuation ('\' as last character on the
902     // line) must be emitted as one line even though Tok.getLine() returns two
903     // different values. In this situation Tok.isAtStartOfLine() is false even
904     // though it may be the first token on the lexical line. When
905     // dropping/skipping a token that is at the start of a line, propagate the
906     // start-of-line-ness to the next token to not append it to the previous
907     // line.
908     IsStartOfLine = IsStartOfLine || Tok.isAtStartOfLine();
909 
910     Callbacks->HandleWhitespaceBeforeTok(Tok, /*RequireSpace=*/false,
911                                          /*RequireSameLine=*/!IsStartOfLine);
912 
913     if (DropComments && Tok.is(tok::comment)) {
914       // Skip comments. Normally the preprocessor does not generate
915       // tok::comment nodes at all when not keeping comments, but under
916       // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
917       PP.Lex(Tok);
918       continue;
919     } else if (Tok.is(tok::annot_repl_input_end)) {
920       PP.Lex(Tok);
921       continue;
922     } else if (Tok.is(tok::eod)) {
923       // Don't print end of directive tokens, since they are typically newlines
924       // that mess up our line tracking. These come from unknown pre-processor
925       // directives or hash-prefixed comments in standalone assembly files.
926       PP.Lex(Tok);
927       // FIXME: The token on the next line after #include should have
928       // Tok.isAtStartOfLine() set.
929       IsStartOfLine = true;
930       continue;
931     } else if (Tok.is(tok::annot_module_include)) {
932       // PrintPPOutputPPCallbacks::InclusionDirective handles producing
933       // appropriate output here. Ignore this token entirely.
934       PP.Lex(Tok);
935       IsStartOfLine = true;
936       continue;
937     } else if (Tok.is(tok::annot_module_begin)) {
938       // FIXME: We retrieve this token after the FileChanged callback, and
939       // retrieve the module_end token before the FileChanged callback, so
940       // we render this within the file and render the module end outside the
941       // file, but this is backwards from the token locations: the module_begin
942       // token is at the include location (outside the file) and the module_end
943       // token is at the EOF location (within the file).
944       Callbacks->BeginModule(
945           reinterpret_cast<Module *>(Tok.getAnnotationValue()));
946       PP.Lex(Tok);
947       IsStartOfLine = true;
948       continue;
949     } else if (Tok.is(tok::annot_module_end)) {
950       Callbacks->EndModule(
951           reinterpret_cast<Module *>(Tok.getAnnotationValue()));
952       PP.Lex(Tok);
953       IsStartOfLine = true;
954       continue;
955     } else if (Tok.is(tok::annot_module_name)) {
956       auto *Info = static_cast<ModuleNameInfo *>(Tok.getAnnotationValue());
957       *Callbacks->OS << Info->getFlatName();
958       PP.Lex(Tok);
959       continue;
960     } else if (Tok.is(tok::annot_header_unit)) {
961       // This is a header-name that has been (effectively) converted into a
962       // module-name.
963       // FIXME: The module name could contain non-identifier module name
964       // components. We don't have a good way to round-trip those.
965       Module *M = reinterpret_cast<Module *>(Tok.getAnnotationValue());
966       std::string Name = M->getFullModuleName();
967       Callbacks->OS->write(Name.data(), Name.size());
968       Callbacks->HandleNewlinesInToken(Name.data(), Name.size());
969     } else if (Tok.is(tok::annot_embed)) {
970       // Manually explode the binary data out to a stream of comma-delimited
971       // integer values. If the user passed -dE, that is handled by the
972       // EmbedDirective() callback. We should only get here if the user did not
973       // pass -dE.
974       assert(Callbacks->expandEmbedContents() &&
975              "did not expect an embed annotation");
976       auto *Data =
977           reinterpret_cast<EmbedAnnotationData *>(Tok.getAnnotationValue());
978 
979       // Loop over the contents and print them as a comma-delimited list of
980       // values.
981       bool PrintComma = false;
982       for (auto Iter = Data->BinaryData.begin(), End = Data->BinaryData.end();
983            Iter != End; ++Iter) {
984         if (PrintComma)
985           *Callbacks->OS << ", ";
986         *Callbacks->OS << static_cast<unsigned>(*Iter);
987         PrintComma = true;
988       }
989       IsStartOfLine = true;
990     } else if (Tok.isAnnotation()) {
991       // Ignore annotation tokens created by pragmas - the pragmas themselves
992       // will be reproduced in the preprocessed output.
993       PP.Lex(Tok);
994       continue;
995     } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
996       *Callbacks->OS << II->getName();
997     } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
998                Tok.getLiteralData()) {
999       Callbacks->OS->write(Tok.getLiteralData(), Tok.getLength());
1000     } else if (Tok.getLength() < std::size(Buffer)) {
1001       const char *TokPtr = Buffer;
1002       unsigned Len = PP.getSpelling(Tok, TokPtr);
1003       Callbacks->OS->write(TokPtr, Len);
1004 
1005       // Tokens that can contain embedded newlines need to adjust our current
1006       // line number.
1007       // FIXME: The token may end with a newline in which case
1008       // setEmittedDirectiveOnThisLine/setEmittedTokensOnThisLine afterwards is
1009       // wrong.
1010       if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
1011         Callbacks->HandleNewlinesInToken(TokPtr, Len);
1012       if (Tok.is(tok::comment) && Len >= 2 && TokPtr[0] == '/' &&
1013           TokPtr[1] == '/') {
1014         // It's a line comment;
1015         // Ensure that we don't concatenate anything behind it.
1016         Callbacks->setEmittedDirectiveOnThisLine();
1017       }
1018     } else {
1019       std::string S = PP.getSpelling(Tok);
1020       Callbacks->OS->write(S.data(), S.size());
1021 
1022       // Tokens that can contain embedded newlines need to adjust our current
1023       // line number.
1024       if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
1025         Callbacks->HandleNewlinesInToken(S.data(), S.size());
1026       if (Tok.is(tok::comment) && S.size() >= 2 && S[0] == '/' && S[1] == '/') {
1027         // It's a line comment;
1028         // Ensure that we don't concatenate anything behind it.
1029         Callbacks->setEmittedDirectiveOnThisLine();
1030       }
1031     }
1032     Callbacks->setEmittedTokensOnThisLine();
1033     IsStartOfLine = false;
1034 
1035     if (Tok.is(tok::eof)) break;
1036 
1037     PP.Lex(Tok);
1038     // If lexing that token causes us to need to skip future tokens, do so now.
1039     for (unsigned I = 0, Skip = Callbacks->GetNumToksToSkip(); I < Skip; ++I)
1040       PP.Lex(Tok);
1041     Callbacks->ResetSkipToks();
1042   }
1043 }
1044 
1045 typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
1046 static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
1047   return LHS->first->getName().compare(RHS->first->getName());
1048 }
1049 
1050 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
1051   // Ignore unknown pragmas.
1052   PP.IgnorePragmas();
1053 
1054   // -dM mode just scans and ignores all tokens in the files, then dumps out
1055   // the macro table at the end.
1056   PP.EnterMainSourceFile();
1057 
1058   Token Tok;
1059   do PP.Lex(Tok);
1060   while (Tok.isNot(tok::eof));
1061 
1062   SmallVector<id_macro_pair, 128> MacrosByID;
1063   for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
1064        I != E; ++I) {
1065     auto *MD = I->second.getLatest();
1066     if (MD && MD->isDefined())
1067       MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
1068   }
1069   llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
1070 
1071   for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
1072     MacroInfo &MI = *MacrosByID[i].second;
1073     // Ignore computed macros like __LINE__ and friends.
1074     if (MI.isBuiltinMacro()) continue;
1075 
1076     PrintMacroDefinition(*MacrosByID[i].first, MI, PP, OS);
1077     *OS << '\n';
1078   }
1079 }
1080 
1081 /// DoPrintPreprocessedInput - This implements -E mode.
1082 ///
1083 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
1084                                      const PreprocessorOutputOptions &Opts) {
1085   // Show macros with no output is handled specially.
1086   if (!Opts.ShowCPP) {
1087     assert(Opts.ShowMacros && "Not yet implemented!");
1088     DoPrintMacros(PP, OS);
1089     return;
1090   }
1091 
1092   // Inform the preprocessor whether we want it to retain comments or not, due
1093   // to -C or -CC.
1094   PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
1095 
1096   PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
1097       PP, OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
1098       Opts.ShowIncludeDirectives, Opts.ShowEmbedDirectives,
1099       Opts.UseLineDirectives, Opts.MinimizeWhitespace, Opts.DirectivesOnly,
1100       Opts.KeepSystemIncludes);
1101 
1102   // Expand macros in pragmas with -fms-extensions.  The assumption is that
1103   // the majority of pragmas in such a file will be Microsoft pragmas.
1104   // Remember the handlers we will add so that we can remove them later.
1105   std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
1106       new UnknownPragmaHandler(
1107           "#pragma", Callbacks,
1108           /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
1109 
1110   std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
1111       "#pragma GCC", Callbacks,
1112       /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
1113 
1114   std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
1115       "#pragma clang", Callbacks,
1116       /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
1117 
1118   PP.AddPragmaHandler(MicrosoftExtHandler.get());
1119   PP.AddPragmaHandler("GCC", GCCHandler.get());
1120   PP.AddPragmaHandler("clang", ClangHandler.get());
1121 
1122   // The tokens after pragma omp need to be expanded.
1123   //
1124   //  OpenMP [2.1, Directive format]
1125   //  Preprocessing tokens following the #pragma omp are subject to macro
1126   //  replacement.
1127   std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
1128       new UnknownPragmaHandler("#pragma omp", Callbacks,
1129                                /*RequireTokenExpansion=*/true));
1130   PP.AddPragmaHandler("omp", OpenMPHandler.get());
1131 
1132   PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
1133 
1134   // After we have configured the preprocessor, enter the main file.
1135   PP.EnterMainSourceFile();
1136   if (Opts.DirectivesOnly)
1137     PP.SetMacroExpansionOnlyInDirectives();
1138 
1139   // Consume all of the tokens that come from the predefines buffer.  Those
1140   // should not be emitted into the output and are guaranteed to be at the
1141   // start.
1142   const SourceManager &SourceMgr = PP.getSourceManager();
1143   Token Tok;
1144   do {
1145     PP.Lex(Tok);
1146     if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
1147       break;
1148 
1149     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1150     if (PLoc.isInvalid())
1151       break;
1152 
1153     if (strcmp(PLoc.getFilename(), "<built-in>"))
1154       break;
1155   } while (true);
1156 
1157   // Read all the preprocessed tokens, printing them out to the stream.
1158   PrintPreprocessedTokens(PP, Tok, Callbacks);
1159   *OS << '\n';
1160 
1161   // Remove the handlers we just added to leave the preprocessor in a sane state
1162   // so that it can be reused (for example by a clang::Parser instance).
1163   PP.RemovePragmaHandler(MicrosoftExtHandler.get());
1164   PP.RemovePragmaHandler("GCC", GCCHandler.get());
1165   PP.RemovePragmaHandler("clang", ClangHandler.get());
1166   PP.RemovePragmaHandler("omp", OpenMPHandler.get());
1167 }
1168