Clang Project

clang_source_code/lib/Frontend/HeaderIncludeGen.cpp
1//===-- HeaderIncludeGen.cpp - Generate Header Includes -------------------===//
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#include "clang/Frontend/DependencyOutputOptions.h"
10#include "clang/Frontend/Utils.h"
11#include "clang/Basic/SourceManager.h"
12#include "clang/Frontend/FrontendDiagnostic.h"
13#include "clang/Lex/Preprocessor.h"
14#include "llvm/ADT/SmallString.h"
15#include "llvm/Support/raw_ostream.h"
16using namespace clang;
17
18namespace {
19class HeaderIncludesCallback : public PPCallbacks {
20  SourceManager &SM;
21  raw_ostream *OutputFile;
22  const DependencyOutputOptions &DepOpts;
23  unsigned CurrentIncludeDepth;
24  bool HasProcessedPredefines;
25  bool OwnsOutputFile;
26  bool ShowAllHeaders;
27  bool ShowDepth;
28  bool MSStyle;
29
30public:
31  HeaderIncludesCallback(const Preprocessor *PPbool ShowAllHeaders_,
32                         raw_ostream *OutputFile_,
33                         const DependencyOutputOptions &DepOpts,
34                         bool OwnsOutputFile_bool ShowDepth_bool MSStyle_)
35      : SM(PP->getSourceManager()), OutputFile(OutputFile_), DepOpts(DepOpts),
36        CurrentIncludeDepth(0), HasProcessedPredefines(false),
37        OwnsOutputFile(OwnsOutputFile_), ShowAllHeaders(ShowAllHeaders_),
38        ShowDepth(ShowDepth_), MSStyle(MSStyle_) {}
39
40  ~HeaderIncludesCallback() override {
41    if (OwnsOutputFile)
42      delete OutputFile;
43  }
44
45  void FileChanged(SourceLocation LocFileChangeReason Reason,
46                   SrcMgr::CharacteristicKind FileType,
47                   FileID PrevFID) override;
48};
49}
50
51static void PrintHeaderInfo(raw_ostream *OutputFileStringRef Filename,
52                            bool ShowDepthunsigned CurrentIncludeDepth,
53                            bool MSStyle) {
54  // Write to a temporary string to avoid unnecessary flushing on errs().
55  SmallString<512Pathname(Filename);
56  if (!MSStyle)
57    Lexer::Stringify(Pathname);
58
59  SmallString<256Msg;
60  if (MSStyle)
61    Msg += "Note: including file:";
62
63  if (ShowDepth) {
64    // The main source file is at depth 1, so skip one dot.
65    for (unsigned i = 1; i != CurrentIncludeDepth; ++i)
66      Msg += MSStyle ? ' ' : '.';
67
68    if (!MSStyle)
69      Msg += ' ';
70  }
71  Msg += Pathname;
72  Msg += '\n';
73
74  *OutputFile << Msg;
75  OutputFile->flush();
76}
77
78void clang::AttachHeaderIncludeGen(Preprocessor &PP,
79                                   const DependencyOutputOptions &DepOpts,
80                                   bool ShowAllHeadersStringRef OutputPath,
81                                   bool ShowDepthbool MSStyle) {
82  raw_ostream *OutputFile = &llvm::errs();
83  bool OwnsOutputFile = false;
84
85  // Choose output stream, when printing in cl.exe /showIncludes style.
86  if (MSStyle) {
87    switch (DepOpts.ShowIncludesDest) {
88    default:
89      llvm_unreachable("Invalid destination for /showIncludes output!");
90    case ShowIncludesDestination::Stderr:
91      OutputFile = &llvm::errs();
92      break;
93    case ShowIncludesDestination::Stdout:
94      OutputFile = &llvm::outs();
95      break;
96    }
97  }
98
99  // Open the output file, if used.
100  if (!OutputPath.empty()) {
101    std::error_code EC;
102    llvm::raw_fd_ostream *OS = new llvm::raw_fd_ostream(
103        OutputPath.str(), EC, llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
104    if (EC) {
105      PP.getDiagnostics().Report(clang::diag::warn_fe_cc_print_header_failure)
106          << EC.message();
107      delete OS;
108    } else {
109      OS->SetUnbuffered();
110      OutputFile = OS;
111      OwnsOutputFile = true;
112    }
113  }
114
115  // Print header info for extra headers, pretending they were discovered by
116  // the regular preprocessor. The primary use case is to support proper
117  // generation of Make / Ninja file dependencies for implicit includes, such
118  // as sanitizer blacklists. It's only important for cl.exe compatibility,
119  // the GNU way to generate rules is -M / -MM / -MD / -MMD.
120  for (const auto &Header : DepOpts.ExtraDeps)
121    PrintHeaderInfo(OutputFileHeaderShowDepth2MSStyle);
122  PP.addPPCallbacks(llvm::make_unique<HeaderIncludesCallback>(
123      &PP, ShowAllHeaders, OutputFile, DepOpts, OwnsOutputFile, ShowDepth,
124      MSStyle));
125}
126
127void HeaderIncludesCallback::FileChanged(SourceLocation Loc,
128                                         FileChangeReason Reason,
129                                       SrcMgr::CharacteristicKind NewFileType,
130                                       FileID PrevFID) {
131  // Unless we are exiting a #include, make sure to skip ahead to the line the
132  // #include directive was at.
133  PresumedLoc UserLoc = SM.getPresumedLoc(Loc);
134  if (UserLoc.isInvalid())
135    return;
136
137  // Adjust the current include depth.
138  if (Reason == PPCallbacks::EnterFile) {
139    ++CurrentIncludeDepth;
140  } else if (Reason == PPCallbacks::ExitFile) {
141    if (CurrentIncludeDepth)
142      --CurrentIncludeDepth;
143
144    // We track when we are done with the predefines by watching for the first
145    // place where we drop back to a nesting depth of 1.
146    if (CurrentIncludeDepth == 1 && !HasProcessedPredefines) {
147      if (!DepOpts.ShowIncludesPretendHeader.empty()) {
148        PrintHeaderInfo(OutputFileDepOpts.ShowIncludesPretendHeader,
149                        ShowDepth2MSStyle);
150      }
151      HasProcessedPredefines = true;
152    }
153
154    return;
155  } else
156    return;
157
158  // Show the header if we are (a) past the predefines, or (b) showing all
159  // headers and in the predefines at a depth past the initial file and command
160  // line buffers.
161  bool ShowHeader = (HasProcessedPredefines ||
162                     (ShowAllHeaders && CurrentIncludeDepth > 2));
163  unsigned IncludeDepth = CurrentIncludeDepth;
164  if (!HasProcessedPredefines)
165    --IncludeDepth// Ignore indent from <built-in>.
166  else if (!DepOpts.ShowIncludesPretendHeader.empty())
167    ++IncludeDepth// Pretend inclusion by ShowIncludesPretendHeader.
168
169  // Dump the header include information we are past the predefines buffer or
170  // are showing all headers and this isn't the magic implicit <command line>
171  // header.
172  // FIXME: Identify headers in a more robust way than comparing their name to
173  // "<command line>" and "<built-in>" in a bunch of places.
174  if (ShowHeader && Reason == PPCallbacks::EnterFile &&
175      UserLoc.getFilename() != StringRef("<command line>")) {
176    PrintHeaderInfo(OutputFileUserLoc.getFilename(), ShowDepthIncludeDepth,
177                    MSStyle);
178  }
179}
180