#include "clang/Basic/LangStandard.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/Types.h"
#include "clang/Tooling/CompilationDatabase.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/StringSaver.h"
#include "llvm/Support/raw_ostream.h"
#include <memory>
namespace clang {
namespace tooling {
namespace {
using namespace llvm;
namespace types = clang::driver::types;
namespace path = llvm::sys::path;
size_t matchingPrefix(StringRef L, StringRef R) {
size_t Limit = std::min(L.size(), R.size());
for (size_t I = 0; I < Limit; ++I)
if (L[I] != R[I])
return I;
return Limit;
}
template <bool Prefix> struct Less {
bool operator()(StringRef Key, std::pair<StringRef, size_t> Value) const {
StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
return Key < V;
}
bool operator()(std::pair<StringRef, size_t> Value, StringRef Key) const {
StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
return V < Key;
}
};
types::ID guessType(StringRef Filename, bool *Certain = nullptr) {
auto Lang =
types::lookupTypeForExtension(path::extension(Filename).substr(1));
if (Certain)
*Certain = Lang != types::TY_CHeader && Lang != types::TY_INVALID;
return Lang;
}
static types::ID foldType(types::ID Lang) {
switch (Lang) {
case types::TY_C:
case types::TY_CHeader:
return types::TY_C;
case types::TY_ObjC:
case types::TY_ObjCHeader:
return types::TY_ObjC;
case types::TY_CXX:
case types::TY_CXXHeader:
return types::TY_CXX;
case types::TY_ObjCXX:
case types::TY_ObjCXXHeader:
return types::TY_ObjCXX;
case types::TY_CUDA:
case types::TY_CUDA_DEVICE:
return types::TY_CUDA;
default:
return types::TY_INVALID;
}
}
struct TransferableCommand {
CompileCommand Cmd;
Optional<types::ID> Type;
LangStandard::Kind Std = LangStandard::lang_unspecified;
bool ClangCLMode;
TransferableCommand(CompileCommand C)
: Cmd(std::move(C)), Type(guessType(Cmd.Filename)) {
std::vector<std::string> OldArgs = std::move(Cmd.CommandLine);
Cmd.CommandLine.clear();
llvm::opt::InputArgList ArgList;
{
SmallVector<const char *, 16> TmpArgv;
for (const std::string &S : OldArgs)
TmpArgv.push_back(S.c_str());
ClangCLMode = !TmpArgv.empty() &&
driver::IsClangCL(driver::getDriverMode(
TmpArgv.front(), llvm::makeArrayRef(TmpArgv).slice(1)));
ArgList = {TmpArgv.begin(), TmpArgv.end()};
}
auto &OptTable = clang::driver::getDriverOptTable();
if (!OldArgs.empty())
Cmd.CommandLine.emplace_back(OldArgs.front());
for (unsigned Pos = 1; Pos < OldArgs.size();) {
using namespace driver::options;
const unsigned OldPos = Pos;
std::unique_ptr<llvm::opt::Arg> Arg(OptTable.ParseOneArg(
ArgList, Pos,
ClangCLMode ? CoreOption | CLOption | CLDXCOption : 0,
ClangCLMode ? 0 : CLOption | CLDXCOption));
if (!Arg)
continue;
const llvm::opt::Option &Opt = Arg->getOption();
if (Opt.matches(OPT_INPUT) || Opt.matches(OPT_o) ||
(ClangCLMode && (Opt.matches(OPT__SLASH_Fa) ||
Opt.matches(OPT__SLASH_Fe) ||
Opt.matches(OPT__SLASH_Fi) ||
Opt.matches(OPT__SLASH_Fo))))
continue;
if (Opt.matches(OPT__DASH_DASH))
break;
if (const auto GivenType = tryParseTypeArg(*Arg)) {
Type = *GivenType;
continue;
}
if (const auto GivenStd = tryParseStdArg(*Arg)) {
if (*GivenStd != LangStandard::lang_unspecified)
Std = *GivenStd;
continue;
}
Cmd.CommandLine.insert(Cmd.CommandLine.end(),
OldArgs.data() + OldPos, OldArgs.data() + Pos);
}
if (Type == types::TY_INVALID && Std != LangStandard::lang_unspecified)
Type = toType(LangStandard::getLangStandardForKind(Std).getLanguage());
Type = foldType(*Type);
if (Type == types::TY_INVALID)
Type = llvm::None;
}
CompileCommand transferTo(StringRef Filename) && {
CompileCommand Result = std::move(Cmd);
Result.Heuristic = "inferred from " + Result.Filename;
Result.Filename = std::string(Filename);
bool TypeCertain;
auto TargetType = guessType(Filename, &TypeCertain);
if ((!TargetType || !TypeCertain) && Type) {
TargetType =
(!TargetType || types::onlyPrecompileType(TargetType)) ? types::lookupHeaderTypeForSourceType(*Type)
: *Type;
if (ClangCLMode) {
const StringRef Flag = toCLFlag(TargetType);
if (!Flag.empty())
Result.CommandLine.push_back(std::string(Flag));
} else {
Result.CommandLine.push_back("-x");
Result.CommandLine.push_back(types::getTypeName(TargetType));
}
}
if (Std != LangStandard::lang_unspecified && foldType(TargetType) == Type) {
Result.CommandLine.emplace_back((
llvm::Twine(ClangCLMode ? "/std:" : "-std=") +
LangStandard::getLangStandardForKind(Std).getName()).str());
}
Result.CommandLine.push_back("--");
Result.CommandLine.push_back(std::string(Filename));
return Result;
}
private:
static types::ID toType(Language Lang) {
switch (Lang) {
case Language::C:
return types::TY_C;
case Language::CXX:
return types::TY_CXX;
case Language::ObjC:
return types::TY_ObjC;
case Language::ObjCXX:
return types::TY_ObjCXX;
default:
return types::TY_INVALID;
}
}
static StringRef toCLFlag(types::ID Type) {
switch (Type) {
case types::TY_C:
case types::TY_CHeader:
return "/TC";
case types::TY_CXX:
case types::TY_CXXHeader:
return "/TP";
default:
return StringRef();
}
}
Optional<types::ID> tryParseTypeArg(const llvm::opt::Arg &Arg) {
const llvm::opt::Option &Opt = Arg.getOption();
using namespace driver::options;
if (ClangCLMode) {
if (Opt.matches(OPT__SLASH_TC) || Opt.matches(OPT__SLASH_Tc))
return types::TY_C;
if (Opt.matches(OPT__SLASH_TP) || Opt.matches(OPT__SLASH_Tp))
return types::TY_CXX;
} else {
if (Opt.matches(driver::options::OPT_x))
return types::lookupTypeForTypeSpecifier(Arg.getValue());
}
return None;
}
Optional<LangStandard::Kind> tryParseStdArg(const llvm::opt::Arg &Arg) {
using namespace driver::options;
if (Arg.getOption().matches(ClangCLMode ? OPT__SLASH_std : OPT_std_EQ))
return LangStandard::getLangKind(Arg.getValue());
return None;
}
};
class FileIndex {
public:
FileIndex(std::vector<std::string> Files)
: OriginalPaths(std::move(Files)), Strings(Arena) {
llvm::sort(OriginalPaths);
Paths.reserve(OriginalPaths.size());
Types.reserve(OriginalPaths.size());
Stems.reserve(OriginalPaths.size());
for (size_t I = 0; I < OriginalPaths.size(); ++I) {
StringRef Path = Strings.save(StringRef(OriginalPaths[I]).lower());
Paths.emplace_back(Path, I);
Types.push_back(foldType(guessType(OriginalPaths[I])));
Stems.emplace_back(sys::path::stem(Path), I);
auto Dir = ++sys::path::rbegin(Path), DirEnd = sys::path::rend(Path);
for (int J = 0; J < DirectorySegmentsIndexed && Dir != DirEnd; ++J, ++Dir)
if (Dir->size() > ShortDirectorySegment) Components.emplace_back(*Dir, I);
}
llvm::sort(Paths);
llvm::sort(Stems);
llvm::sort(Components);
}
bool empty() const { return Paths.empty(); }
StringRef chooseProxy(StringRef OriginalFilename,
types::ID PreferLanguage) const {
assert(!empty() && "need at least one candidate!");
std::string Filename = OriginalFilename.lower();
auto Candidates = scoreCandidates(Filename);
std::pair<size_t, int> Best =
pickWinner(Candidates, Filename, PreferLanguage);
DEBUG_WITH_TYPE(
"interpolate",
llvm::dbgs() << "interpolate: chose " << OriginalPaths[Best.first]
<< " as proxy for " << OriginalFilename << " preferring "
<< (PreferLanguage == types::TY_INVALID
? "none"
: types::getTypeName(PreferLanguage))
<< " score=" << Best.second << "\n");
return OriginalPaths[Best.first];
}
private:
using SubstringAndIndex = std::pair<StringRef, size_t>;
constexpr static int DirectorySegmentsIndexed = 4;
constexpr static int DirectorySegmentsQueried = 2;
constexpr static int ShortDirectorySegment = 1;
DenseMap<size_t, int> scoreCandidates(StringRef Filename) const {
StringRef Stem = sys::path::stem(Filename);
llvm::SmallVector<StringRef, DirectorySegmentsQueried> Dirs;
llvm::StringRef Prefix;
auto Dir = ++sys::path::rbegin(Filename),
DirEnd = sys::path::rend(Filename);
for (int I = 0; I < DirectorySegmentsQueried && Dir != DirEnd; ++I, ++Dir) {
if (Dir->size() > ShortDirectorySegment)
Dirs.push_back(*Dir);
Prefix = Filename.substr(0, Dir - DirEnd);
}
DenseMap<size_t, int> Candidates; auto Award = [&](int Points, ArrayRef<SubstringAndIndex> Range) {
for (const auto &Entry : Range)
Candidates[Entry.second] += Points;
};
Award(1, indexLookup<true>(Stem, Stems));
Award(1, indexLookup<false>(Stem, Stems));
for (StringRef Dir : Dirs)
Award(1, indexLookup<false>(Dir, Components));
if (sys::path::root_directory(Prefix) != Prefix)
Award(1, indexLookup<true>(Prefix, Paths));
return Candidates;
}
std::pair<size_t, int> pickWinner(const DenseMap<size_t, int> &Candidates,
StringRef Filename,
types::ID PreferredLanguage) const {
struct ScoredCandidate {
size_t Index;
bool Preferred;
int Points;
size_t PrefixLength;
};
ScoredCandidate Best = {size_t(-1), false, 0, 0};
for (const auto &Candidate : Candidates) {
ScoredCandidate S;
S.Index = Candidate.first;
S.Preferred = PreferredLanguage == types::TY_INVALID ||
PreferredLanguage == Types[S.Index];
S.Points = Candidate.second;
if (!S.Preferred && Best.Preferred)
continue;
if (S.Preferred == Best.Preferred) {
if (S.Points < Best.Points)
continue;
if (S.Points == Best.Points) {
S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
if (S.PrefixLength < Best.PrefixLength)
continue;
if (S.PrefixLength == Best.PrefixLength)
if (S.Index > Best.Index)
continue;
}
}
S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
Best = S;
}
if (Best.Index == size_t(-1))
return {longestMatch(Filename, Paths).second, 0};
return {Best.Index, Best.Points};
}
template <bool Prefix>
ArrayRef<SubstringAndIndex>
indexLookup(StringRef Key, ArrayRef<SubstringAndIndex> Idx) const {
auto Range = std::equal_range(Idx.data(), Idx.data() + Idx.size(), Key,
Less<Prefix>());
return {Range.first, Range.second};
}
SubstringAndIndex longestMatch(StringRef Key,
ArrayRef<SubstringAndIndex> Idx) const {
assert(!Idx.empty());
auto It = llvm::lower_bound(Idx, SubstringAndIndex{Key, 0});
if (It == Idx.begin())
return *It;
if (It == Idx.end())
return *--It;
size_t Prefix = matchingPrefix(Key, It->first);
size_t PrevPrefix = matchingPrefix(Key, (It - 1)->first);
return Prefix > PrevPrefix ? *It : *--It;
}
std::vector<std::string> OriginalPaths;
BumpPtrAllocator Arena;
StringSaver Strings;
std::vector<SubstringAndIndex> Paths; std::vector<types::ID> Types;
std::vector<SubstringAndIndex> Stems; std::vector<SubstringAndIndex> Components; };
class InterpolatingCompilationDatabase : public CompilationDatabase {
public:
InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)
: Inner(std::move(Inner)), Index(this->Inner->getAllFiles()) {}
std::vector<CompileCommand>
getCompileCommands(StringRef Filename) const override {
auto Known = Inner->getCompileCommands(Filename);
if (Index.empty() || !Known.empty())
return Known;
bool TypeCertain;
auto Lang = guessType(Filename, &TypeCertain);
if (!TypeCertain)
Lang = types::TY_INVALID;
auto ProxyCommands =
Inner->getCompileCommands(Index.chooseProxy(Filename, foldType(Lang)));
if (ProxyCommands.empty())
return {};
return {transferCompileCommand(std::move(ProxyCommands.front()), Filename)};
}
std::vector<std::string> getAllFiles() const override {
return Inner->getAllFiles();
}
std::vector<CompileCommand> getAllCompileCommands() const override {
return Inner->getAllCompileCommands();
}
private:
std::unique_ptr<CompilationDatabase> Inner;
FileIndex Index;
};
}
std::unique_ptr<CompilationDatabase>
inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner) {
return std::make_unique<InterpolatingCompilationDatabase>(std::move(Inner));
}
tooling::CompileCommand transferCompileCommand(CompileCommand Cmd,
StringRef Filename) {
return TransferableCommand(std::move(Cmd)).transferTo(Filename);
}
} }