#include "clang/Frontend/Utils.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/DependencyOutputOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Lex/DirectoryLookup.h"
#include "clang/Lex/ModuleMap.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Serialization/ASTReader.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace {
struct DepCollectorPPCallbacks : public PPCallbacks {
DependencyCollector &DepCollector;
Preprocessor &PP;
DepCollectorPPCallbacks(DependencyCollector &L, Preprocessor &PP)
: DepCollector(L), PP(PP) {}
void LexedFileChanged(FileID FID, LexedFileChangeReason Reason,
SrcMgr::CharacteristicKind FileType, FileID PrevFID,
SourceLocation Loc) override {
if (Reason != PPCallbacks::LexedFileChangeReason::EnterFile)
return;
if (Optional<StringRef> Filename =
PP.getSourceManager().getNonBuiltinFilenameForID(FID))
DepCollector.maybeAddDependency(
llvm::sys::path::remove_leading_dotslash(*Filename),
false, isSystem(FileType), false,
false);
}
void FileSkipped(const FileEntryRef &SkippedFile, const Token &FilenameTok,
SrcMgr::CharacteristicKind FileType) override {
StringRef Filename =
llvm::sys::path::remove_leading_dotslash(SkippedFile.getName());
DepCollector.maybeAddDependency(Filename, false,
isSystem(FileType),
false,
false);
}
void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
StringRef FileName, bool IsAngled,
CharSourceRange FilenameRange,
Optional<FileEntryRef> File, StringRef SearchPath,
StringRef RelativePath, const Module *Imported,
SrcMgr::CharacteristicKind FileType) override {
if (!File)
DepCollector.maybeAddDependency(FileName, false,
false, false,
true);
}
void HasInclude(SourceLocation Loc, StringRef SpelledFilename, bool IsAngled,
Optional<FileEntryRef> File,
SrcMgr::CharacteristicKind FileType) override {
if (!File)
return;
StringRef Filename =
llvm::sys::path::remove_leading_dotslash(File->getName());
DepCollector.maybeAddDependency(Filename, false,
isSystem(FileType),
false,
false);
}
void EndOfMainFile() override {
DepCollector.finishedMainFile(PP.getDiagnostics());
}
};
struct DepCollectorMMCallbacks : public ModuleMapCallbacks {
DependencyCollector &DepCollector;
DepCollectorMMCallbacks(DependencyCollector &DC) : DepCollector(DC) {}
void moduleMapFileRead(SourceLocation Loc, const FileEntry &Entry,
bool IsSystem) override {
StringRef Filename = Entry.getName();
DepCollector.maybeAddDependency(Filename, false,
IsSystem,
false,
false);
}
};
struct DepCollectorASTListener : public ASTReaderListener {
DependencyCollector &DepCollector;
DepCollectorASTListener(DependencyCollector &L) : DepCollector(L) { }
bool needsInputFileVisitation() override { return true; }
bool needsSystemInputFileVisitation() override {
return DepCollector.needSystemDependencies();
}
void visitModuleFile(StringRef Filename,
serialization::ModuleKind Kind) override {
DepCollector.maybeAddDependency(Filename, true,
false, true,
false);
}
bool visitInputFile(StringRef Filename, bool IsSystem,
bool IsOverridden, bool IsExplicitModule) override {
if (IsOverridden || IsExplicitModule)
return true;
DepCollector.maybeAddDependency(Filename, true, IsSystem,
false, false);
return true;
}
};
}
void DependencyCollector::maybeAddDependency(StringRef Filename,
bool FromModule, bool IsSystem,
bool IsModuleFile,
bool IsMissing) {
if (sawDependency(Filename, FromModule, IsSystem, IsModuleFile, IsMissing))
addDependency(Filename);
}
bool DependencyCollector::addDependency(StringRef Filename) {
StringRef SearchPath;
#ifdef _WIN32
llvm::SmallString<256> TmpPath = Filename;
llvm::sys::path::native(TmpPath);
std::transform(TmpPath.begin(), TmpPath.end(), TmpPath.begin(), ::tolower);
SearchPath = TmpPath.str();
#else
SearchPath = Filename;
#endif
if (Seen.insert(SearchPath).second) {
Dependencies.push_back(std::string(Filename));
return true;
}
return false;
}
static bool isSpecialFilename(StringRef Filename) {
return llvm::StringSwitch<bool>(Filename)
.Case("<built-in>", true)
.Case("<stdin>", true)
.Default(false);
}
bool DependencyCollector::sawDependency(StringRef Filename, bool FromModule,
bool IsSystem, bool IsModuleFile,
bool IsMissing) {
return !isSpecialFilename(Filename) &&
(needSystemDependencies() || !IsSystem);
}
DependencyCollector::~DependencyCollector() { }
void DependencyCollector::attachToPreprocessor(Preprocessor &PP) {
PP.addPPCallbacks(std::make_unique<DepCollectorPPCallbacks>(*this, PP));
PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
std::make_unique<DepCollectorMMCallbacks>(*this));
}
void DependencyCollector::attachToASTReader(ASTReader &R) {
R.addListener(std::make_unique<DepCollectorASTListener>(*this));
}
DependencyFileGenerator::DependencyFileGenerator(
const DependencyOutputOptions &Opts)
: OutputFile(Opts.OutputFile), Targets(Opts.Targets),
IncludeSystemHeaders(Opts.IncludeSystemHeaders),
PhonyTarget(Opts.UsePhonyTargets),
AddMissingHeaderDeps(Opts.AddMissingHeaderDeps), SeenMissingHeader(false),
IncludeModuleFiles(Opts.IncludeModuleFiles),
OutputFormat(Opts.OutputFormat), InputFileIndex(0) {
for (const auto &ExtraDep : Opts.ExtraDeps) {
if (addDependency(ExtraDep.first))
++InputFileIndex;
}
}
void DependencyFileGenerator::attachToPreprocessor(Preprocessor &PP) {
if (AddMissingHeaderDeps)
PP.SetSuppressIncludeNotFoundError(true);
DependencyCollector::attachToPreprocessor(PP);
}
bool DependencyFileGenerator::sawDependency(StringRef Filename, bool FromModule,
bool IsSystem, bool IsModuleFile,
bool IsMissing) {
if (IsMissing) {
if (AddMissingHeaderDeps)
return true;
SeenMissingHeader = true;
return false;
}
if (IsModuleFile && !IncludeModuleFiles)
return false;
if (isSpecialFilename(Filename))
return false;
if (IncludeSystemHeaders)
return true;
return !IsSystem;
}
void DependencyFileGenerator::finishedMainFile(DiagnosticsEngine &Diags) {
outputDependencyFile(Diags);
}
static void PrintFilename(raw_ostream &OS, StringRef Filename,
DependencyOutputFormat OutputFormat) {
llvm::SmallString<256> NativePath;
llvm::sys::path::native(Filename.str(), NativePath);
if (OutputFormat == DependencyOutputFormat::NMake) {
if (NativePath.find_first_of(" #${}^!") != StringRef::npos)
OS << '\"' << NativePath << '\"';
else
OS << NativePath;
return;
}
assert(OutputFormat == DependencyOutputFormat::Make);
for (unsigned i = 0, e = NativePath.size(); i != e; ++i) {
if (NativePath[i] == '#') OS << '\\';
else if (NativePath[i] == ' ') { OS << '\\';
unsigned j = i;
while (j > 0 && NativePath[--j] == '\\')
OS << '\\';
} else if (NativePath[i] == '$') OS << '$';
OS << NativePath[i];
}
}
void DependencyFileGenerator::outputDependencyFile(DiagnosticsEngine &Diags) {
if (SeenMissingHeader) {
llvm::sys::fs::remove(OutputFile);
return;
}
std::error_code EC;
llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::OF_TextWithCRLF);
if (EC) {
Diags.Report(diag::err_fe_error_opening) << OutputFile << EC.message();
return;
}
outputDependencyFile(OS);
}
void DependencyFileGenerator::outputDependencyFile(llvm::raw_ostream &OS) {
const unsigned MaxColumns = 75;
unsigned Columns = 0;
for (StringRef Target : Targets) {
unsigned N = Target.size();
if (Columns == 0) {
Columns += N;
} else if (Columns + N + 2 > MaxColumns) {
Columns = N + 2;
OS << " \\\n ";
} else {
Columns += N + 1;
OS << ' ';
}
OS << Target;
}
OS << ':';
Columns += 1;
ArrayRef<std::string> Files = getDependencies();
for (StringRef File : Files) {
unsigned N = File.size();
if (Columns + (N + 1) + 2 > MaxColumns) {
OS << " \\\n ";
Columns = 2;
}
OS << ' ';
PrintFilename(OS, File, OutputFormat);
Columns += N + 1;
}
OS << '\n';
if (PhonyTarget && !Files.empty()) {
unsigned Index = 0;
for (auto I = Files.begin(), E = Files.end(); I != E; ++I) {
if (Index++ == InputFileIndex)
continue;
OS << '\n';
PrintFilename(OS, *I, OutputFormat);
OS << ":\n";
}
}
}