Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-extract/llvm-extract.cpp | //===- llvm-extract.cpp - LLVM function extraction utility ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility changes the input module to only contain a single function,
// which is primarily used for debugging transformations.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Bitcode/BitcodeWriterPass.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/IRPrintingPasses.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Transforms/IPO.h"
#include <memory>
using namespace llvm;
// InputFilename - The filename to read from.
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
cl::init("-"), cl::value_desc("filename"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Specify output filename"),
cl::value_desc("filename"), cl::init("-"));
static cl::opt<bool>
Force("f", cl::desc("Enable binary output on terminals"));
static cl::opt<bool>
DeleteFn("delete", cl::desc("Delete specified Globals from Module"));
// ExtractFuncs - The functions to extract from the module.
static cl::list<std::string>
ExtractFuncs("func", cl::desc("Specify function to extract"),
cl::ZeroOrMore, cl::value_desc("function"));
// ExtractRegExpFuncs - The functions, matched via regular expression, to
// extract from the module.
static cl::list<std::string>
ExtractRegExpFuncs("rfunc", cl::desc("Specify function(s) to extract using a "
"regular expression"),
cl::ZeroOrMore, cl::value_desc("rfunction"));
// ExtractAlias - The alias to extract from the module.
static cl::list<std::string>
ExtractAliases("alias", cl::desc("Specify alias to extract"),
cl::ZeroOrMore, cl::value_desc("alias"));
// ExtractRegExpAliases - The aliases, matched via regular expression, to
// extract from the module.
static cl::list<std::string>
ExtractRegExpAliases("ralias", cl::desc("Specify alias(es) to extract using a "
"regular expression"),
cl::ZeroOrMore, cl::value_desc("ralias"));
// ExtractGlobals - The globals to extract from the module.
static cl::list<std::string>
ExtractGlobals("glob", cl::desc("Specify global to extract"),
cl::ZeroOrMore, cl::value_desc("global"));
// ExtractRegExpGlobals - The globals, matched via regular expression, to
// extract from the module...
static cl::list<std::string>
ExtractRegExpGlobals("rglob", cl::desc("Specify global(s) to extract using a "
"regular expression"),
cl::ZeroOrMore, cl::value_desc("rglobal"));
static cl::opt<bool>
OutputAssembly("S",
cl::desc("Write output as LLVM assembly"), cl::Hidden);
static cl::opt<bool> PreserveBitcodeUseListOrder(
"preserve-bc-uselistorder",
cl::desc("Preserve use-list order when writing LLVM bitcode."),
cl::init(true), cl::Hidden);
static cl::opt<bool> PreserveAssemblyUseListOrder(
"preserve-ll-uselistorder",
cl::desc("Preserve use-list order when writing LLVM assembly."),
cl::init(false), cl::Hidden);
int __cdecl main(int argc, char **argv) { // HLSL Change - __cdecl
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "llvm extractor\n");
// Use lazy loading, since we only care about selected global values.
SMDiagnostic Err;
std::unique_ptr<Module> M = getLazyIRFileModule(InputFilename, Err, Context);
if (!M.get()) {
Err.print(argv[0], errs());
return 1;
}
// Use SetVector to avoid duplicates.
SetVector<GlobalValue *> GVs;
// Figure out which aliases we should extract.
for (size_t i = 0, e = ExtractAliases.size(); i != e; ++i) {
GlobalAlias *GA = M->getNamedAlias(ExtractAliases[i]);
if (!GA) {
errs() << argv[0] << ": program doesn't contain alias named '"
<< ExtractAliases[i] << "'!\n";
return 1;
}
GVs.insert(GA);
}
// Extract aliases via regular expression matching.
for (size_t i = 0, e = ExtractRegExpAliases.size(); i != e; ++i) {
std::string Error;
Regex RegEx(ExtractRegExpAliases[i]);
if (!RegEx.isValid(Error)) {
errs() << argv[0] << ": '" << ExtractRegExpAliases[i] << "' "
"invalid regex: " << Error;
}
bool match = false;
for (Module::alias_iterator GA = M->alias_begin(), E = M->alias_end();
GA != E; GA++) {
if (RegEx.match(GA->getName())) {
GVs.insert(&*GA);
match = true;
}
}
if (!match) {
errs() << argv[0] << ": program doesn't contain global named '"
<< ExtractRegExpAliases[i] << "'!\n";
return 1;
}
}
// Figure out which globals we should extract.
for (size_t i = 0, e = ExtractGlobals.size(); i != e; ++i) {
GlobalValue *GV = M->getNamedGlobal(ExtractGlobals[i]);
if (!GV) {
errs() << argv[0] << ": program doesn't contain global named '"
<< ExtractGlobals[i] << "'!\n";
return 1;
}
GVs.insert(GV);
}
// Extract globals via regular expression matching.
for (size_t i = 0, e = ExtractRegExpGlobals.size(); i != e; ++i) {
std::string Error;
Regex RegEx(ExtractRegExpGlobals[i]);
if (!RegEx.isValid(Error)) {
errs() << argv[0] << ": '" << ExtractRegExpGlobals[i] << "' "
"invalid regex: " << Error;
}
bool match = false;
for (auto &GV : M->globals()) {
if (RegEx.match(GV.getName())) {
GVs.insert(&GV);
match = true;
}
}
if (!match) {
errs() << argv[0] << ": program doesn't contain global named '"
<< ExtractRegExpGlobals[i] << "'!\n";
return 1;
}
}
// Figure out which functions we should extract.
for (size_t i = 0, e = ExtractFuncs.size(); i != e; ++i) {
GlobalValue *GV = M->getFunction(ExtractFuncs[i]);
if (!GV) {
errs() << argv[0] << ": program doesn't contain function named '"
<< ExtractFuncs[i] << "'!\n";
return 1;
}
GVs.insert(GV);
}
// Extract functions via regular expression matching.
for (size_t i = 0, e = ExtractRegExpFuncs.size(); i != e; ++i) {
std::string Error;
StringRef RegExStr = ExtractRegExpFuncs[i];
Regex RegEx(RegExStr);
if (!RegEx.isValid(Error)) {
errs() << argv[0] << ": '" << ExtractRegExpFuncs[i] << "' "
"invalid regex: " << Error;
}
bool match = false;
for (Module::iterator F = M->begin(), E = M->end(); F != E;
F++) {
if (RegEx.match(F->getName())) {
GVs.insert(&*F);
match = true;
}
}
if (!match) {
errs() << argv[0] << ": program doesn't contain global named '"
<< ExtractRegExpFuncs[i] << "'!\n";
return 1;
}
}
// Materialize requisite global values.
if (!DeleteFn)
for (size_t i = 0, e = GVs.size(); i != e; ++i) {
GlobalValue *GV = GVs[i];
if (std::error_code EC = GV->materialize()) {
errs() << argv[0] << ": error reading input: " << EC.message() << "\n";
return 1;
}
}
else {
// Deleting. Materialize every GV that's *not* in GVs.
SmallPtrSet<GlobalValue *, 8> GVSet(GVs.begin(), GVs.end());
for (auto &G : M->globals()) {
if (!GVSet.count(&G)) {
if (std::error_code EC = G.materialize()) {
errs() << argv[0] << ": error reading input: " << EC.message()
<< "\n";
return 1;
}
}
}
for (auto &F : *M) {
if (!GVSet.count(&F)) {
if (std::error_code EC = F.materialize()) {
errs() << argv[0] << ": error reading input: " << EC.message()
<< "\n";
return 1;
}
}
}
}
// In addition to deleting all other functions, we also want to spiff it
// up a little bit. Do this now.
legacy::PassManager Passes;
std::vector<GlobalValue*> Gvs(GVs.begin(), GVs.end());
Passes.add(createGVExtractionPass(Gvs, DeleteFn));
if (!DeleteFn)
Passes.add(createGlobalDCEPass()); // Delete unreachable globals
Passes.add(createStripDeadDebugInfoPass()); // Remove dead debug info
Passes.add(createStripDeadPrototypesPass()); // Remove dead func decls
std::error_code EC;
tool_output_file Out(OutputFilename, EC, sys::fs::F_None);
if (EC) {
errs() << EC.message() << '\n';
return 1;
}
if (OutputAssembly)
Passes.add(
createPrintModulePass(Out.os(), "", PreserveAssemblyUseListOrder));
else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
Passes.add(createBitcodeWriterPass(Out.os(), PreserveBitcodeUseListOrder));
Passes.run(*M.get());
// Declare success.
Out.keep();
return 0;
}
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-as/llvm-as.cpp | //===--- llvm-as.cpp - The low-level LLVM assembler -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility may be invoked in the following manner:
// llvm-as --help - Output information about command line switches
// llvm-as [options] - Read LLVM asm from stdin, write bitcode to stdout
// llvm-as [options] x.ll - Read LLVM asm from the x.ll file, write bitcode
// to the x.bc file.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/LLVMContext.h"
#include "llvm/AsmParser/Parser.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/ToolOutputFile.h"
#include <memory>
using namespace llvm;
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input .llvm file>"), cl::init("-"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Override output filename"),
cl::value_desc("filename"));
static cl::opt<bool>
Force("f", cl::desc("Enable binary output on terminals"));
static cl::opt<bool>
DisableOutput("disable-output", cl::desc("Disable output"), cl::init(false));
static cl::opt<bool>
DumpAsm("d", cl::desc("Print assembly as parsed"), cl::Hidden);
static cl::opt<bool>
DisableVerify("disable-verify", cl::Hidden,
cl::desc("Do not run verifier on input LLVM (dangerous!)"));
static cl::opt<bool> PreserveBitcodeUseListOrder(
"preserve-bc-uselistorder",
cl::desc("Preserve use-list order when writing LLVM bitcode."),
cl::init(true), cl::Hidden);
static void WriteOutputFile(const Module *M) {
// Infer the output filename if needed.
if (OutputFilename.empty()) {
if (InputFilename == "-") {
OutputFilename = "-";
} else {
StringRef IFN = InputFilename;
OutputFilename = (IFN.endswith(".ll") ? IFN.drop_back(3) : IFN).str();
OutputFilename += ".bc";
}
}
std::error_code EC;
std::unique_ptr<tool_output_file> Out(
new tool_output_file(OutputFilename, EC, sys::fs::F_None));
if (EC) {
errs() << EC.message() << '\n';
exit(1);
}
if (Force || !CheckBitcodeOutputToConsole(Out->os(), true))
WriteBitcodeToFile(M, Out->os(), PreserveBitcodeUseListOrder);
// Declare success.
Out->keep();
}
// HLSL Change Starts
#define NOMINMAX
#include "dxc/Support/WinIncludes.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MSFileSystem.h"
// HLSL Change Ends
// HLSL Change: changed calling convention to __cdecl
int __cdecl main(int argc, char **argv) {
// Print a stack trace if we signal out.
// sys::PrintStackTraceOnErrorSignal(); // HLSL Change - disable this
// PrettyStackTraceProgram X(argc, argv); // HLSL Change - disable this
// HLSL Change Starts
llvm::sys::fs::MSFileSystem* msfPtr;
HRESULT hr;
if (!SUCCEEDED(hr = CreateMSFileSystemForDisk(&msfPtr)))
return 1;
std::unique_ptr<llvm::sys::fs::MSFileSystem> msf(msfPtr);
llvm::sys::fs::AutoPerThreadSystem pts(msf.get());
llvm::STDStreamCloser stdStreamCloser;
// HLSL Change Ends
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "llvm .ll -> .bc assembler\n");
// Parse the file now...
SMDiagnostic Err;
std::unique_ptr<Module> M = parseAssemblyFile(InputFilename, Err, Context);
if (!M.get()) {
Err.print(argv[0], errs());
return 1;
}
if (!DisableVerify) {
std::string ErrorStr;
raw_string_ostream OS(ErrorStr);
if (verifyModule(*M.get(), &OS)) {
errs() << argv[0]
<< ": assembly parsed, but does not verify as correct!\n";
errs() << OS.str();
return 1;
}
}
if (DumpAsm) errs() << "Here's the assembly:\n" << *M.get();
if (!DisableOutput)
WriteOutputFile(M.get());
return 0;
}
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-as/CMakeLists.txt | set(LLVM_LINK_COMPONENTS
AsmParser
BitWriter
Core
Support
MSSupport # HLSL Change
)
add_llvm_tool(llvm-as
llvm-as.cpp
)
# HLSL Change Starts
if (NOT HLSL_OPTIONAL_PROJS_IN_DEFAULT)
set_target_properties(llvm-as PROPERTIES EXCLUDE_FROM_ALL ON EXCLUDE_FROM_DEFAULT_BUILD ON)
endif ()
# HLSL Change Ends
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-as/LLVMBuild.txt | ;===- ./tools/llvm-as/LLVMBuild.txt ----------------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Tool
name = llvm-as
parent = Tools
required_libraries = AsmParser BitWriter
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-symbolizer/CMakeLists.txt | # FIXME: As we plan to execute llvm-symbolizer binary from compiler-rt
# libraries, it has to be compiled for all supported targets (x86_64, i386 etc).
# This means that we need LLVM libraries to be compiled for these
# targets as well. Currently, there is no support for such a build strategy.
set(LLVM_LINK_COMPONENTS
DebugInfoDWARF
DebugInfoPDB
Object
Support
)
add_llvm_tool(llvm-symbolizer
LLVMSymbolize.cpp
llvm-symbolizer.cpp
)
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-symbolizer/llvm-symbolizer.cpp | //===-- llvm-symbolizer.cpp - Simple addr2line-like symbolizer ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility works much like "addr2line". It is able of transforming
// tuples (module name, module offset) to code locations (function name,
// file, line number, column number). It is targeted for compiler-rt tools
// (especially AddressSanitizer and ThreadSanitizer) that can use it
// to symbolize stack traces in their error reports.
//
//===----------------------------------------------------------------------===//
#include "LLVMSymbolize.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/COM.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdio>
#include <cstring>
#include <string>
using namespace llvm;
using namespace symbolize;
static cl::opt<bool>
ClUseSymbolTable("use-symbol-table", cl::init(true),
cl::desc("Prefer names in symbol table to names "
"in debug info"));
static cl::opt<FunctionNameKind> ClPrintFunctions(
"functions", cl::init(FunctionNameKind::LinkageName),
cl::desc("Print function name for a given address:"),
cl::values(clEnumValN(FunctionNameKind::None, "none", "omit function name"),
clEnumValN(FunctionNameKind::ShortName, "short",
"print short function name"),
clEnumValN(FunctionNameKind::LinkageName, "linkage",
"print function linkage name"),
clEnumValEnd));
static cl::opt<bool>
ClUseRelativeAddress("relative-address", cl::init(false),
cl::desc("Interpret addresses as relative addresses"),
cl::ReallyHidden);
static cl::opt<bool>
ClPrintInlining("inlining", cl::init(true),
cl::desc("Print all inlined frames for a given address"));
static cl::opt<bool>
ClDemangle("demangle", cl::init(true), cl::desc("Demangle function names"));
static cl::opt<std::string> ClDefaultArch("default-arch", cl::init(""),
cl::desc("Default architecture "
"(for multi-arch objects)"));
static cl::opt<std::string>
ClBinaryName("obj", cl::init(""),
cl::desc("Path to object file to be symbolized (if not provided, "
"object file should be specified for each input line)"));
static cl::list<std::string>
ClDsymHint("dsym-hint", cl::ZeroOrMore,
cl::desc("Path to .dSYM bundles to search for debug info for the "
"object files"));
static bool parseCommand(bool &IsData, std::string &ModuleName,
uint64_t &ModuleOffset) {
const char *kDataCmd = "DATA ";
const char *kCodeCmd = "CODE ";
const int kMaxInputStringLength = 1024;
const char kDelimiters[] = " \n";
char InputString[kMaxInputStringLength];
if (!fgets(InputString, sizeof(InputString), stdin))
return false;
IsData = false;
ModuleName = "";
char *pos = InputString;
if (strncmp(pos, kDataCmd, strlen(kDataCmd)) == 0) {
IsData = true;
pos += strlen(kDataCmd);
} else if (strncmp(pos, kCodeCmd, strlen(kCodeCmd)) == 0) {
IsData = false;
pos += strlen(kCodeCmd);
} else {
// If no cmd, assume it's CODE.
IsData = false;
}
// Skip delimiters and parse input filename (if needed).
if (ClBinaryName == "") {
pos += strspn(pos, kDelimiters);
if (*pos == '"' || *pos == '\'') {
char quote = *pos;
pos++;
char *end = strchr(pos, quote);
if (!end)
return false;
ModuleName = std::string(pos, end - pos);
pos = end + 1;
} else {
int name_length = strcspn(pos, kDelimiters);
ModuleName = std::string(pos, name_length);
pos += name_length;
}
} else {
ModuleName = ClBinaryName;
}
// Skip delimiters and parse module offset.
pos += strspn(pos, kDelimiters);
int offset_length = strcspn(pos, kDelimiters);
if (StringRef(pos, offset_length).getAsInteger(0, ModuleOffset))
return false;
return true;
}
// HLSL Change: changed calling convention to __cdecl
int __cdecl main(int argc, char **argv) {
// Print stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
llvm::sys::InitializeCOMRAII COM(llvm::sys::COMThreadingMode::MultiThreaded);
cl::ParseCommandLineOptions(argc, argv, "llvm-symbolizer\n");
LLVMSymbolizer::Options Opts(ClPrintFunctions, ClUseSymbolTable,
ClPrintInlining, ClDemangle,
ClUseRelativeAddress, ClDefaultArch);
for (const auto &hint : ClDsymHint) {
if (sys::path::extension(hint) == ".dSYM") {
Opts.DsymHints.push_back(hint);
} else {
errs() << "Warning: invalid dSYM hint: \"" << hint <<
"\" (must have the '.dSYM' extension).\n";
}
}
LLVMSymbolizer Symbolizer(Opts);
bool IsData = false;
std::string ModuleName;
uint64_t ModuleOffset;
while (parseCommand(IsData, ModuleName, ModuleOffset)) {
std::string Result =
IsData ? Symbolizer.symbolizeData(ModuleName, ModuleOffset)
: Symbolizer.symbolizeCode(ModuleName, ModuleOffset);
outs() << Result << "\n";
outs().flush();
}
return 0;
}
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-symbolizer/LLVMSymbolize.h | //===-- LLVMSymbolize.h ----------------------------------------- C++ -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Header for LLVM symbolization library.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TOOLS_LLVM_SYMBOLIZER_LLVMSYMBOLIZE_H
#define LLVM_TOOLS_LLVM_SYMBOLIZER_LLVMSYMBOLIZE_H
#include "llvm/ADT/SmallVector.h"
#include "llvm/DebugInfo/DIContext.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/DataExtractor.h"
#include "llvm/Support/MemoryBuffer.h"
#include <map>
#include <memory>
#include <string>
namespace llvm {
typedef DILineInfoSpecifier::FunctionNameKind FunctionNameKind;
using namespace object;
namespace symbolize {
class ModuleInfo;
class LLVMSymbolizer {
public:
struct Options {
FunctionNameKind PrintFunctions;
bool UseSymbolTable : 1;
bool PrintInlining : 1;
bool Demangle : 1;
bool RelativeAddresses : 1;
std::string DefaultArch;
std::vector<std::string> DsymHints;
Options(FunctionNameKind PrintFunctions = FunctionNameKind::LinkageName,
bool UseSymbolTable = true, bool PrintInlining = true,
bool Demangle = true, bool RelativeAddresses = false,
std::string DefaultArch = "")
: PrintFunctions(PrintFunctions), UseSymbolTable(UseSymbolTable),
PrintInlining(PrintInlining), Demangle(Demangle),
RelativeAddresses(RelativeAddresses), DefaultArch(DefaultArch) {}
};
LLVMSymbolizer(const Options &Opts = Options()) : Opts(Opts) {}
~LLVMSymbolizer() {
flush();
}
// Returns the result of symbolization for module name/offset as
// a string (possibly containing newlines).
std::string
symbolizeCode(const std::string &ModuleName, uint64_t ModuleOffset);
std::string
symbolizeData(const std::string &ModuleName, uint64_t ModuleOffset);
void flush();
static std::string DemangleName(const std::string &Name);
private:
typedef std::pair<ObjectFile*, ObjectFile*> ObjectPair;
ModuleInfo *getOrCreateModuleInfo(const std::string &ModuleName);
ObjectFile *lookUpDsymFile(const std::string &Path, const MachOObjectFile *ExeObj,
const std::string &ArchName);
/// \brief Returns pair of pointers to object and debug object.
ObjectPair getOrCreateObjects(const std::string &Path,
const std::string &ArchName);
/// \brief Returns a parsed object file for a given architecture in a
/// universal binary (or the binary itself if it is an object file).
ObjectFile *getObjectFileFromBinary(Binary *Bin, const std::string &ArchName);
std::string printDILineInfo(DILineInfo LineInfo) const;
// Owns all the parsed binaries and object files.
SmallVector<std::unique_ptr<Binary>, 4> ParsedBinariesAndObjects;
SmallVector<std::unique_ptr<MemoryBuffer>, 4> MemoryBuffers;
void addOwningBinary(OwningBinary<Binary> OwningBin) {
std::unique_ptr<Binary> Bin;
std::unique_ptr<MemoryBuffer> MemBuf;
std::tie(Bin, MemBuf) = OwningBin.takeBinary();
ParsedBinariesAndObjects.push_back(std::move(Bin));
MemoryBuffers.push_back(std::move(MemBuf));
}
// Owns module info objects.
std::map<std::string, ModuleInfo *> Modules;
std::map<std::pair<MachOUniversalBinary *, std::string>, ObjectFile *>
ObjectFileForArch;
std::map<std::pair<std::string, std::string>, ObjectPair>
ObjectPairForPathArch;
Options Opts;
static const char kBadString[];
};
class ModuleInfo {
public:
ModuleInfo(ObjectFile *Obj, DIContext *DICtx);
DILineInfo symbolizeCode(uint64_t ModuleOffset,
const LLVMSymbolizer::Options &Opts) const;
DIInliningInfo symbolizeInlinedCode(
uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const;
bool symbolizeData(uint64_t ModuleOffset, std::string &Name, uint64_t &Start,
uint64_t &Size) const;
private:
bool getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
std::string &Name, uint64_t &Addr,
uint64_t &Size) const;
// For big-endian PowerPC64 ELF, OpdAddress is the address of the .opd
// (function descriptor) section and OpdExtractor refers to its contents.
void addSymbol(const SymbolRef &Symbol, uint64_t SymbolSize,
DataExtractor *OpdExtractor = nullptr,
uint64_t OpdAddress = 0);
ObjectFile *Module;
std::unique_ptr<DIContext> DebugInfoContext;
struct SymbolDesc {
uint64_t Addr;
// If size is 0, assume that symbol occupies the whole memory range up to
// the following symbol.
uint64_t Size;
friend bool operator<(const SymbolDesc &s1, const SymbolDesc &s2) {
return s1.Addr < s2.Addr;
}
};
std::map<SymbolDesc, StringRef> Functions;
std::map<SymbolDesc, StringRef> Objects;
};
} // namespace symbolize
} // namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-symbolizer/LLVMSymbolize.cpp | //===-- LLVMSymbolize.cpp -------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implementation for LLVM symbolization library.
//
//===----------------------------------------------------------------------===//
#include "LLVMSymbolize.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Config/config.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/PDB/PDB.h"
#include "llvm/DebugInfo/PDB/PDBContext.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/SymbolSize.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compression.h"
#include "llvm/Support/DataExtractor.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include <sstream>
#include <stdlib.h>
#if defined(_MSC_VER)
#include <windows.h>
#include <dbghelp.h>
#pragma comment(lib, "dbghelp.lib")
#endif
namespace llvm {
namespace symbolize {
static bool error(std::error_code ec) {
if (!ec)
return false;
errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
return true;
}
static DILineInfoSpecifier
getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
return DILineInfoSpecifier(
DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
Opts.PrintFunctions);
}
ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
: Module(Obj), DebugInfoContext(DICtx) {
std::unique_ptr<DataExtractor> OpdExtractor;
uint64_t OpdAddress = 0;
// Find the .opd (function descriptor) section if any, for big-endian
// PowerPC64 ELF.
if (Module->getArch() == Triple::ppc64) {
for (section_iterator Section : Module->sections()) {
StringRef Name;
if (!error(Section->getName(Name)) && Name == ".opd") {
StringRef Data;
if (!error(Section->getContents(Data))) {
OpdExtractor.reset(new DataExtractor(Data, Module->isLittleEndian(),
Module->getBytesInAddress()));
OpdAddress = Section->getAddress();
}
break;
}
}
}
std::vector<std::pair<SymbolRef, uint64_t>> Symbols =
computeSymbolSizes(*Module);
for (auto &P : Symbols)
addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress);
}
void ModuleInfo::addSymbol(const SymbolRef &Symbol, uint64_t SymbolSize,
DataExtractor *OpdExtractor, uint64_t OpdAddress) {
SymbolRef::Type SymbolType = Symbol.getType();
if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
return;
ErrorOr<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
if (error(SymbolAddressOrErr.getError()))
return;
uint64_t SymbolAddress = *SymbolAddressOrErr;
if (OpdExtractor) {
// For big-endian PowerPC64 ELF, symbols in the .opd section refer to
// function descriptors. The first word of the descriptor is a pointer to
// the function's code.
// For the purposes of symbolization, pretend the symbol's address is that
// of the function's code, not the descriptor.
uint64_t OpdOffset = SymbolAddress - OpdAddress;
uint32_t OpdOffset32 = OpdOffset;
if (OpdOffset == OpdOffset32 &&
OpdExtractor->isValidOffsetForAddress(OpdOffset32))
SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
}
ErrorOr<StringRef> SymbolNameOrErr = Symbol.getName();
if (error(SymbolNameOrErr.getError()))
return;
StringRef SymbolName = *SymbolNameOrErr;
// Mach-O symbol table names have leading underscore, skip it.
if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
SymbolName = SymbolName.drop_front();
// FIXME: If a function has alias, there are two entries in symbol table
// with same address size. Make sure we choose the correct one.
auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
SymbolDesc SD = { SymbolAddress, SymbolSize };
M.insert(std::make_pair(SD, SymbolName));
}
bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
std::string &Name, uint64_t &Addr,
uint64_t &Size) const {
const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
if (SymbolMap.empty())
return false;
SymbolDesc SD = { Address, Address };
auto SymbolIterator = SymbolMap.upper_bound(SD);
if (SymbolIterator == SymbolMap.begin())
return false;
--SymbolIterator;
if (SymbolIterator->first.Size != 0 &&
SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
return false;
Name = SymbolIterator->second.str();
Addr = SymbolIterator->first.Addr;
Size = SymbolIterator->first.Size;
return true;
}
DILineInfo ModuleInfo::symbolizeCode(
uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
DILineInfo LineInfo;
if (DebugInfoContext) {
LineInfo = DebugInfoContext->getLineInfoForAddress(
ModuleOffset, getDILineInfoSpecifier(Opts));
}
// Override function name from symbol table if necessary.
if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
std::string FunctionName;
uint64_t Start, Size;
if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
FunctionName, Start, Size)) {
LineInfo.FunctionName = FunctionName;
}
}
return LineInfo;
}
DIInliningInfo ModuleInfo::symbolizeInlinedCode(
uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
DIInliningInfo InlinedContext;
if (DebugInfoContext) {
InlinedContext = DebugInfoContext->getInliningInfoForAddress(
ModuleOffset, getDILineInfoSpecifier(Opts));
}
// Make sure there is at least one frame in context.
if (InlinedContext.getNumberOfFrames() == 0) {
InlinedContext.addFrame(DILineInfo());
}
// Override the function name in lower frame with name from symbol table.
if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
DIInliningInfo PatchedInlinedContext;
for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
DILineInfo LineInfo = InlinedContext.getFrame(i);
if (i == n - 1) {
std::string FunctionName;
uint64_t Start, Size;
if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
FunctionName, Start, Size)) {
LineInfo.FunctionName = FunctionName;
}
}
PatchedInlinedContext.addFrame(LineInfo);
}
InlinedContext = PatchedInlinedContext;
}
return InlinedContext;
}
bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
uint64_t &Start, uint64_t &Size) const {
return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
Size);
}
const char LLVMSymbolizer::kBadString[] = "??";
std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
uint64_t ModuleOffset) {
ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
if (!Info)
return printDILineInfo(DILineInfo());
if (Opts.PrintInlining) {
DIInliningInfo InlinedContext =
Info->symbolizeInlinedCode(ModuleOffset, Opts);
uint32_t FramesNum = InlinedContext.getNumberOfFrames();
assert(FramesNum > 0);
std::string Result;
for (uint32_t i = 0; i < FramesNum; i++) {
DILineInfo LineInfo = InlinedContext.getFrame(i);
Result += printDILineInfo(LineInfo);
}
return Result;
}
DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
return printDILineInfo(LineInfo);
}
std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
uint64_t ModuleOffset) {
std::string Name = kBadString;
uint64_t Start = 0;
uint64_t Size = 0;
if (Opts.UseSymbolTable) {
if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
Name = DemangleName(Name);
}
}
std::stringstream ss;
ss << Name << "\n" << Start << " " << Size << "\n";
return ss.str();
}
void LLVMSymbolizer::flush() {
DeleteContainerSeconds(Modules);
ObjectPairForPathArch.clear();
ObjectFileForArch.clear();
}
// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
static
std::string getDarwinDWARFResourceForPath(
const std::string &Path, const std::string &Basename) {
SmallString<16> ResourceName = StringRef(Path);
if (sys::path::extension(Path) != ".dSYM") {
ResourceName += ".dSYM";
}
sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
sys::path::append(ResourceName, Basename);
return ResourceName.str();
}
static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
MemoryBuffer::getFileOrSTDIN(Path);
if (!MB)
return false;
return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
}
static bool findDebugBinary(const std::string &OrigPath,
const std::string &DebuglinkName, uint32_t CRCHash,
std::string &Result) {
std::string OrigRealPath = OrigPath;
#if defined(HAVE_REALPATH)
if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
OrigRealPath = RP;
free(RP);
}
#endif
SmallString<16> OrigDir(OrigRealPath);
llvm::sys::path::remove_filename(OrigDir);
SmallString<16> DebugPath = OrigDir;
// Try /path/to/original_binary/debuglink_name
llvm::sys::path::append(DebugPath, DebuglinkName);
if (checkFileCRC(DebugPath, CRCHash)) {
Result = DebugPath.str();
return true;
}
// Try /path/to/original_binary/.debug/debuglink_name
DebugPath = OrigRealPath;
llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
if (checkFileCRC(DebugPath, CRCHash)) {
Result = DebugPath.str();
return true;
}
// Try /usr/lib/debug/path/to/original_binary/debuglink_name
DebugPath = "/usr/lib/debug";
llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
DebuglinkName);
if (checkFileCRC(DebugPath, CRCHash)) {
Result = DebugPath.str();
return true;
}
return false;
}
static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
uint32_t &CRCHash) {
if (!Obj)
return false;
for (const SectionRef &Section : Obj->sections()) {
StringRef Name;
Section.getName(Name);
Name = Name.substr(Name.find_first_not_of("._"));
if (Name == "gnu_debuglink") {
StringRef Data;
Section.getContents(Data);
DataExtractor DE(Data, Obj->isLittleEndian(), 0);
uint32_t Offset = 0;
if (const char *DebugNameStr = DE.getCStr(&Offset)) {
// 4-byte align the offset.
Offset = (Offset + 3) & ~0x3;
if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
DebugName = DebugNameStr;
CRCHash = DE.getU32(&Offset);
return true;
}
}
break;
}
}
return false;
}
static
bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
const MachOObjectFile *Obj) {
ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
if (dbg_uuid.empty() || bin_uuid.empty())
return false;
return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
}
ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
const MachOObjectFile *MachExeObj, const std::string &ArchName) {
// On Darwin we may find DWARF in separate object file in
// resource directory.
std::vector<std::string> DsymPaths;
StringRef Filename = sys::path::filename(ExePath);
DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
for (const auto &Path : Opts.DsymHints) {
DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
}
for (const auto &path : DsymPaths) {
ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
std::error_code EC = BinaryOrErr.getError();
if (EC != errc::no_such_file_or_directory && !error(EC)) {
OwningBinary<Binary> B = std::move(BinaryOrErr.get());
ObjectFile *DbgObj =
getObjectFileFromBinary(B.getBinary(), ArchName);
const MachOObjectFile *MachDbgObj =
dyn_cast<const MachOObjectFile>(DbgObj);
if (!MachDbgObj) continue;
if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
addOwningBinary(std::move(B));
return DbgObj;
}
}
}
return nullptr;
}
LLVMSymbolizer::ObjectPair
LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
const std::string &ArchName) {
const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
if (I != ObjectPairForPathArch.end())
return I->second;
ObjectFile *Obj = nullptr;
ObjectFile *DbgObj = nullptr;
ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
if (!error(BinaryOrErr.getError())) {
OwningBinary<Binary> &B = BinaryOrErr.get();
Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
if (!Obj) {
ObjectPair Res = std::make_pair(nullptr, nullptr);
ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
return Res;
}
addOwningBinary(std::move(B));
if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
// Try to locate the debug binary using .gnu_debuglink section.
if (!DbgObj) {
std::string DebuglinkName;
uint32_t CRCHash;
std::string DebugBinaryPath;
if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
BinaryOrErr = createBinary(DebugBinaryPath);
if (!error(BinaryOrErr.getError())) {
OwningBinary<Binary> B = std::move(BinaryOrErr.get());
DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
addOwningBinary(std::move(B));
}
}
}
}
if (!DbgObj)
DbgObj = Obj;
ObjectPair Res = std::make_pair(Obj, DbgObj);
ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
return Res;
}
ObjectFile *
LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
const std::string &ArchName) {
if (!Bin)
return nullptr;
ObjectFile *Res = nullptr;
if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
const auto &I = ObjectFileForArch.find(
std::make_pair(UB, ArchName));
if (I != ObjectFileForArch.end())
return I->second;
ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
UB->getObjectForArch(ArchName);
if (ParsedObj) {
Res = ParsedObj.get().get();
ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
}
ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
} else if (Bin->isObject()) {
Res = cast<ObjectFile>(Bin);
}
return Res;
}
ModuleInfo *
LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
const auto &I = Modules.find(ModuleName);
if (I != Modules.end())
return I->second;
std::string BinaryName = ModuleName;
std::string ArchName = Opts.DefaultArch;
size_t ColonPos = ModuleName.find_last_of(':');
// Verify that substring after colon form a valid arch name.
if (ColonPos != std::string::npos) {
std::string ArchStr = ModuleName.substr(ColonPos + 1);
if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
BinaryName = ModuleName.substr(0, ColonPos);
ArchName = ArchStr;
}
}
ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
if (!Objects.first) {
// Failed to find valid object file.
Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
return nullptr;
}
DIContext *Context = nullptr;
if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
// If this is a COFF object, assume it contains PDB debug information. If
// we don't find any we will fall back to the DWARF case.
std::unique_ptr<IPDBSession> Session;
PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
Objects.first->getFileName(), Session);
if (Error == PDB_ErrorCode::Success) {
Context = new PDBContext(*CoffObject, std::move(Session),
Opts.RelativeAddresses);
}
}
if (!Context)
Context = new DWARFContextInMemory(*Objects.second);
assert(Context);
ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
Modules.insert(make_pair(ModuleName, Info));
return Info;
}
std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
// By default, DILineInfo contains "<invalid>" for function/filename it
// cannot fetch. We replace it to "??" to make our output closer to addr2line.
static const std::string kDILineInfoBadString = "<invalid>";
std::stringstream Result;
if (Opts.PrintFunctions != FunctionNameKind::None) {
std::string FunctionName = LineInfo.FunctionName;
if (FunctionName == kDILineInfoBadString)
FunctionName = kBadString;
else if (Opts.Demangle)
FunctionName = DemangleName(FunctionName);
Result << FunctionName << "\n";
}
std::string Filename = LineInfo.FileName;
if (Filename == kDILineInfoBadString)
Filename = kBadString;
Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
return Result.str();
}
#if !defined(_MSC_VER)
// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
size_t *length, int *status);
#endif
std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
#if !defined(_MSC_VER)
// We can spoil names of symbols with C linkage, so use an heuristic
// approach to check if the name should be demangled.
if (Name.substr(0, 2) != "_Z")
return Name;
int status = 0;
char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
if (status != 0)
return Name;
std::string Result = DemangledName;
free(DemangledName);
return Result;
#else
char DemangledName[1024] = {0};
DWORD result = ::UnDecorateSymbolName(
Name.c_str(), DemangledName, 1023,
UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
return (result == 0) ? Name : std::string(DemangledName);
#endif
}
} // namespace symbolize
} // namespace llvm
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-config/llvm-config.cpp | //===-- llvm-config.cpp - LLVM project configuration utility --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool encapsulates information about an LLVM project configuration for
// use by other project's build environments (to determine installed path,
// available features, required libraries, etc.).
//
// Note that although this tool *may* be used by some parts of LLVM's build
// itself (i.e., the Makefiles use it to compute required libraries when linking
// tools), this tool is primarily designed to support external projects.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Config/config.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdlib>
#include <set>
#include <vector>
using namespace llvm;
// Include the build time variables we can report to the user. This is generated
// at build time from the BuildVariables.inc.in file by the build system.
#include "BuildVariables.inc"
// Include the component table. This creates an array of struct
// AvailableComponent entries, which record the component name, library name,
// and required components for all of the available libraries.
//
// Not all components define a library, we also use "library groups" as a way to
// create entries for pseudo groups like x86 or all-targets.
#include "LibraryDependencies.inc"
/// \brief Traverse a single component adding to the topological ordering in
/// \arg RequiredLibs.
///
/// \param Name - The component to traverse.
/// \param ComponentMap - A prebuilt map of component names to descriptors.
/// \param VisitedComponents [in] [out] - The set of already visited components.
/// \param RequiredLibs [out] - The ordered list of required libraries.
static void VisitComponent(StringRef Name,
const StringMap<AvailableComponent*> &ComponentMap,
std::set<AvailableComponent*> &VisitedComponents,
std::vector<StringRef> &RequiredLibs,
bool IncludeNonInstalled) {
// Lookup the component.
AvailableComponent *AC = ComponentMap.lookup(Name);
assert(AC && "Invalid component name!");
// Add to the visited table.
if (!VisitedComponents.insert(AC).second) {
// We are done if the component has already been visited.
return;
}
// Only include non-installed components if requested.
if (!AC->IsInstalled && !IncludeNonInstalled)
return;
// Otherwise, visit all the dependencies.
for (unsigned i = 0; AC->RequiredLibraries[i]; ++i) {
VisitComponent(AC->RequiredLibraries[i], ComponentMap, VisitedComponents,
RequiredLibs, IncludeNonInstalled);
}
// Add to the required library list.
if (AC->Library)
RequiredLibs.push_back(AC->Library);
}
/// \brief Compute the list of required libraries for a given list of
/// components, in an order suitable for passing to a linker (that is, libraries
/// appear prior to their dependencies).
///
/// \param Components - The names of the components to find libraries for.
/// \param RequiredLibs [out] - On return, the ordered list of libraries that
/// are required to link the given components.
/// \param IncludeNonInstalled - Whether non-installed components should be
/// reported.
static void ComputeLibsForComponents(const std::vector<StringRef> &Components,
std::vector<StringRef> &RequiredLibs,
bool IncludeNonInstalled) {
std::set<AvailableComponent*> VisitedComponents;
// Build a map of component names to information.
StringMap<AvailableComponent*> ComponentMap;
for (unsigned i = 0; i != array_lengthof(AvailableComponents); ++i) {
AvailableComponent *AC = &AvailableComponents[i];
ComponentMap[AC->Name] = AC;
}
// Visit the components.
for (unsigned i = 0, e = Components.size(); i != e; ++i) {
// Users are allowed to provide mixed case component names.
std::string ComponentLower = Components[i].lower();
// Validate that the user supplied a valid component name.
if (!ComponentMap.count(ComponentLower)) {
llvm::errs() << "llvm-config: unknown component name: " << Components[i]
<< "\n";
exit(1);
}
VisitComponent(ComponentLower, ComponentMap, VisitedComponents,
RequiredLibs, IncludeNonInstalled);
}
// The list is now ordered with leafs first, we want the libraries to printed
// in the reverse order of dependency.
std::reverse(RequiredLibs.begin(), RequiredLibs.end());
}
/* *** */
static void usage() {
errs() << "\
usage: llvm-config <OPTION>... [<COMPONENT>...]\n\
\n\
Get various configuration information needed to compile programs which use\n\
LLVM. Typically called from 'configure' scripts. Examples:\n\
llvm-config --cxxflags\n\
llvm-config --ldflags\n\
llvm-config --libs engine bcreader scalaropts\n\
\n\
Options:\n\
--version Print LLVM version.\n\
--prefix Print the installation prefix.\n\
--src-root Print the source root LLVM was built from.\n\
--obj-root Print the object root used to build LLVM.\n\
--bindir Directory containing LLVM executables.\n\
--includedir Directory containing LLVM headers.\n\
--libdir Directory containing LLVM libraries.\n\
--cppflags C preprocessor flags for files that include LLVM headers.\n\
--cflags C compiler flags for files that include LLVM headers.\n\
--cxxflags C++ compiler flags for files that include LLVM headers.\n\
--ldflags Print Linker flags.\n\
--system-libs System Libraries needed to link against LLVM components.\n\
--libs Libraries needed to link against LLVM components.\n\
--libnames Bare library names for in-tree builds.\n\
--libfiles Fully qualified library filenames for makefile depends.\n\
--components List of all possible components.\n\
--targets-built List of all targets currently built.\n\
--host-target Target triple used to configure LLVM.\n\
--build-mode Print build mode of LLVM tree (e.g. Debug or Release).\n\
--assertion-mode Print assertion mode of LLVM tree (ON or OFF).\n\
Typical components:\n\
all All LLVM libraries (default).\n\
engine Either a native JIT or a bitcode interpreter.\n";
exit(1);
}
/// \brief Compute the path to the main executable.
std::string GetExecutablePath(const char *Argv0) {
// This just needs to be some symbol in the binary; C++ doesn't
// allow taking the address of ::main however.
void *P = (void*) (intptr_t) GetExecutablePath;
return llvm::sys::fs::getMainExecutable(Argv0, P);
}
// HLSL Change: changed calling convention to __cdecl
int __cdecl main(int argc, char **argv) {
std::vector<StringRef> Components;
bool PrintLibs = false, PrintLibNames = false, PrintLibFiles = false;
bool PrintSystemLibs = false;
bool HasAnyOption = false;
// llvm-config is designed to support being run both from a development tree
// and from an installed path. We try and auto-detect which case we are in so
// that we can report the correct information when run from a development
// tree.
bool IsInDevelopmentTree;
enum { MakefileStyle, CMakeStyle, CMakeBuildModeStyle } DevelopmentTreeLayout;
llvm::SmallString<256> CurrentPath(GetExecutablePath(argv[0]));
std::string CurrentExecPrefix;
std::string ActiveObjRoot;
// If CMAKE_CFG_INTDIR is given, honor it as build mode.
char const *build_mode = LLVM_BUILDMODE;
#if defined(CMAKE_CFG_INTDIR)
if (!(CMAKE_CFG_INTDIR[0] == '.' && CMAKE_CFG_INTDIR[1] == '\0'))
build_mode = CMAKE_CFG_INTDIR;
#endif
// Create an absolute path, and pop up one directory (we expect to be inside a
// bin dir).
sys::fs::make_absolute(CurrentPath);
CurrentExecPrefix = sys::path::parent_path(
sys::path::parent_path(CurrentPath)).str();
// Check to see if we are inside a development tree by comparing to possible
// locations (prefix style or CMake style).
if (sys::fs::equivalent(CurrentExecPrefix,
Twine(LLVM_OBJ_ROOT) + "/" + build_mode)) {
IsInDevelopmentTree = true;
DevelopmentTreeLayout = MakefileStyle;
// If we are in a development tree, then check if we are in a BuildTools
// directory. This indicates we are built for the build triple, but we
// always want to provide information for the host triple.
if (sys::path::filename(LLVM_OBJ_ROOT) == "BuildTools") {
ActiveObjRoot = sys::path::parent_path(LLVM_OBJ_ROOT);
} else {
ActiveObjRoot = LLVM_OBJ_ROOT;
}
} else if (sys::fs::equivalent(CurrentExecPrefix, LLVM_OBJ_ROOT)) {
IsInDevelopmentTree = true;
DevelopmentTreeLayout = CMakeStyle;
ActiveObjRoot = LLVM_OBJ_ROOT;
} else if (sys::fs::equivalent(CurrentExecPrefix,
Twine(LLVM_OBJ_ROOT) + "/bin")) {
IsInDevelopmentTree = true;
DevelopmentTreeLayout = CMakeBuildModeStyle;
ActiveObjRoot = LLVM_OBJ_ROOT;
} else {
IsInDevelopmentTree = false;
DevelopmentTreeLayout = MakefileStyle; // Initialized to avoid warnings.
}
// Compute various directory locations based on the derived location
// information.
std::string ActivePrefix, ActiveBinDir, ActiveIncludeDir, ActiveLibDir;
std::string ActiveIncludeOption;
if (IsInDevelopmentTree) {
ActiveIncludeDir = std::string(LLVM_SRC_ROOT) + "/include";
ActivePrefix = CurrentExecPrefix;
// CMake organizes the products differently than a normal prefix style
// layout.
switch (DevelopmentTreeLayout) {
case MakefileStyle:
ActivePrefix = ActiveObjRoot;
ActiveBinDir = ActiveObjRoot + "/" + build_mode + "/bin";
ActiveLibDir =
ActiveObjRoot + "/" + build_mode + "/lib" + LLVM_LIBDIR_SUFFIX;
break;
case CMakeStyle:
ActiveBinDir = ActiveObjRoot + "/bin";
ActiveLibDir = ActiveObjRoot + "/lib" + LLVM_LIBDIR_SUFFIX;
break;
case CMakeBuildModeStyle:
ActivePrefix = ActiveObjRoot;
ActiveBinDir = ActiveObjRoot + "/bin/" + build_mode;
ActiveLibDir =
ActiveObjRoot + "/lib" + LLVM_LIBDIR_SUFFIX + "/" + build_mode;
break;
}
// We need to include files from both the source and object trees.
ActiveIncludeOption = ("-I" + ActiveIncludeDir + " " +
"-I" + ActiveObjRoot + "/include");
} else {
ActivePrefix = CurrentExecPrefix;
ActiveIncludeDir = ActivePrefix + "/include";
ActiveBinDir = ActivePrefix + "/bin";
ActiveLibDir = ActivePrefix + "/lib" + LLVM_LIBDIR_SUFFIX;
ActiveIncludeOption = "-I" + ActiveIncludeDir;
}
raw_ostream &OS = outs();
for (int i = 1; i != argc; ++i) {
StringRef Arg = argv[i];
if (Arg.startswith("-")) {
HasAnyOption = true;
if (Arg == "--version") {
OS << PACKAGE_VERSION << '\n';
} else if (Arg == "--prefix") {
OS << ActivePrefix << '\n';
} else if (Arg == "--bindir") {
OS << ActiveBinDir << '\n';
} else if (Arg == "--includedir") {
OS << ActiveIncludeDir << '\n';
} else if (Arg == "--libdir") {
OS << ActiveLibDir << '\n';
} else if (Arg == "--cppflags") {
OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\n';
} else if (Arg == "--cflags") {
OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\n';
} else if (Arg == "--cxxflags") {
OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\n';
} else if (Arg == "--ldflags") {
OS << "-L" << ActiveLibDir << ' ' << LLVM_LDFLAGS << '\n';
} else if (Arg == "--system-libs") {
PrintSystemLibs = true;
} else if (Arg == "--libs") {
PrintLibs = true;
} else if (Arg == "--libnames") {
PrintLibNames = true;
} else if (Arg == "--libfiles") {
PrintLibFiles = true;
} else if (Arg == "--components") {
for (unsigned j = 0; j != array_lengthof(AvailableComponents); ++j) {
// Only include non-installed components when in a development tree.
if (!AvailableComponents[j].IsInstalled && !IsInDevelopmentTree)
continue;
OS << ' ';
OS << AvailableComponents[j].Name;
}
OS << '\n';
} else if (Arg == "--targets-built") {
OS << LLVM_TARGETS_BUILT << '\n';
} else if (Arg == "--host-target") {
OS << Triple::normalize(LLVM_DEFAULT_TARGET_TRIPLE) << '\n';
} else if (Arg == "--build-mode") {
OS << build_mode << '\n';
} else if (Arg == "--assertion-mode") {
#if defined(NDEBUG)
OS << "OFF\n";
#else
OS << "ON\n";
#endif
} else if (Arg == "--obj-root") {
OS << ActivePrefix << '\n';
} else if (Arg == "--src-root") {
OS << LLVM_SRC_ROOT << '\n';
} else {
usage();
}
} else {
Components.push_back(Arg);
}
}
if (!HasAnyOption)
usage();
if (PrintLibs || PrintLibNames || PrintLibFiles || PrintSystemLibs) {
// If no components were specified, default to "all".
if (Components.empty())
Components.push_back("all");
// Construct the list of all the required libraries.
std::vector<StringRef> RequiredLibs;
ComputeLibsForComponents(Components, RequiredLibs,
/*IncludeNonInstalled=*/IsInDevelopmentTree);
if (PrintLibs || PrintLibNames || PrintLibFiles) {
for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {
StringRef Lib = RequiredLibs[i];
if (i)
OS << ' ';
if (PrintLibNames) {
OS << Lib;
} else if (PrintLibFiles) {
OS << ActiveLibDir << '/' << Lib;
} else if (PrintLibs) {
// If this is a typical library name, include it using -l.
if (Lib.startswith("lib") && Lib.endswith(".a")) {
OS << "-l" << Lib.slice(3, Lib.size()-2);
continue;
}
// Otherwise, print the full path.
OS << ActiveLibDir << '/' << Lib;
}
}
OS << '\n';
}
// Print SYSTEM_LIBS after --libs.
// FIXME: Each LLVM component may have its dependent system libs.
if (PrintSystemLibs)
OS << LLVM_SYSTEM_LIBS << '\n';
} else if (!Components.empty()) {
errs() << "llvm-config: error: components given, but unused\n\n";
usage();
}
return 0;
}
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-config/BuildVariables.inc.in | //===-- BuildVariables.inc.in - llvm-config build variables -*- C++ -*-----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is configured by the build system to define the variables
// llvm-config wants to report to the user, but which can only be determined at
// build time.
//
// The variant of this file not ending with .in has been autogenerated by the
// LLVM build. Do not edit!
//
//===----------------------------------------------------------------------===//
#define LLVM_SRC_ROOT "@LLVM_SRC_ROOT@"
#define LLVM_OBJ_ROOT "@LLVM_OBJ_ROOT@"
#define LLVM_CPPFLAGS "@LLVM_CPPFLAGS@"
#define LLVM_CFLAGS "@LLVM_CFLAGS@"
#define LLVM_LDFLAGS "@LLVM_LDFLAGS@"
#define LLVM_CXXFLAGS "@LLVM_CXXFLAGS@"
#define LLVM_BUILDMODE "@LLVM_BUILDMODE@"
#define LLVM_LIBDIR_SUFFIX "@LLVM_LIBDIR_SUFFIX@"
#define LLVM_TARGETS_BUILT "@LLVM_TARGETS_BUILT@"
#define LLVM_SYSTEM_LIBS "@LLVM_SYSTEM_LIBS@"
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-config/CMakeLists.txt | set(LLVM_LINK_COMPONENTS support)
set(BUILDVARIABLES_SRCPATH ${CMAKE_CURRENT_SOURCE_DIR}/BuildVariables.inc.in)
set(BUILDVARIABLES_OBJPATH ${CMAKE_CURRENT_BINARY_DIR}/BuildVariables.inc)
# Add the llvm-config tool.
add_llvm_tool(llvm-config
llvm-config.cpp
)
# Compute the substitution values for various items.
get_property(LLVM_SYSTEM_LIBS_LIST TARGET LLVMSupport PROPERTY LLVM_SYSTEM_LIBS)
foreach(l ${LLVM_SYSTEM_LIBS_LIST})
set(SYSTEM_LIBS ${SYSTEM_LIBS} "-l${l}")
endforeach()
string(REPLACE ";" " " SYSTEM_LIBS "${SYSTEM_LIBS}")
# Fetch target specific compile options, e.g. RTTI option
get_property(COMPILE_FLAGS TARGET llvm-config PROPERTY COMPILE_FLAGS)
# Use configure_file to create BuildVariables.inc.
set(LLVM_SRC_ROOT ${LLVM_MAIN_SRC_DIR})
set(LLVM_OBJ_ROOT ${LLVM_BINARY_DIR})
set(LLVM_CPPFLAGS "${CMAKE_CPP_FLAGS} ${CMAKE_CPP_FLAGS_${uppercase_CMAKE_BUILD_TYPE}} ${LLVM_DEFINITIONS}")
set(LLVM_CFLAGS "${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_${uppercase_CMAKE_BUILD_TYPE}} ${LLVM_DEFINITIONS}")
set(LLVM_CXXFLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_${uppercase_CMAKE_BUILD_TYPE}} ${COMPILE_FLAGS} ${LLVM_DEFINITIONS}")
# Use the C++ link flags, since they should be a superset of C link flags.
set(LLVM_LDFLAGS "${CMAKE_CXX_LINK_FLAGS}")
set(LLVM_BUILDMODE ${CMAKE_BUILD_TYPE})
set(LLVM_SYSTEM_LIBS ${SYSTEM_LIBS})
string(REPLACE ";" " " LLVM_TARGETS_BUILT "${LLVM_TARGETS_TO_BUILD}")
configure_file(${BUILDVARIABLES_SRCPATH} ${BUILDVARIABLES_OBJPATH} @ONLY)
# Set build-time environment(s).
add_definitions(-DCMAKE_CFG_INTDIR="${CMAKE_CFG_INTDIR}")
# Add the dependency on the generation step.
add_file_dependencies(${CMAKE_CURRENT_SOURCE_DIR}/llvm-config.cpp ${BUILDVARIABLES_OBJPATH})
if(CMAKE_CROSSCOMPILING)
set(${project}_LLVM_CONFIG_EXE "${LLVM_NATIVE_BUILD}/bin/llvm-config")
set(${project}_LLVM_CONFIG_EXE ${${project}_LLVM_CONFIG_EXE} PARENT_SCOPE)
add_custom_command(OUTPUT "${${project}_LLVM_CONFIG_EXE}"
COMMAND ${CMAKE_COMMAND} --build . --target llvm-config --config $<CONFIGURATION>
DEPENDS ${LLVM_NATIVE_BUILD}/CMakeCache.txt
WORKING_DIRECTORY ${LLVM_NATIVE_BUILD}
COMMENT "Building native llvm-config...")
add_custom_target(${project}NativeLLVMConfig DEPENDS ${${project}_LLVM_CONFIG_EXE})
add_dependencies(${project}NativeLLVMConfig CONFIGURE_LLVM_NATIVE)
add_dependencies(llvm-config ${project}NativeLLVMConfig)
endif(CMAKE_CROSSCOMPILING)
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-diff/DiffLog.h | //===-- DiffLog.h - Difference Log Builder and accessories ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This header defines the interface to the LLVM difference log builder.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TOOLS_LLVM_DIFF_DIFFLOG_H
#define LLVM_TOOLS_LLVM_DIFF_DIFFLOG_H
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
namespace llvm {
class Instruction;
class Value;
class Consumer;
/// Trichotomy assumption
enum DiffChange { DC_match, DC_left, DC_right };
/// A temporary-object class for building up log messages.
class LogBuilder {
Consumer &consumer;
/// The use of a stored StringRef here is okay because
/// LogBuilder should be used only as a temporary, and as a
/// temporary it will be destructed before whatever temporary
/// might be initializing this format.
StringRef Format;
SmallVector<Value*, 4> Arguments;
public:
LogBuilder(Consumer &c, StringRef Format)
: consumer(c), Format(Format) {}
LogBuilder &operator<<(Value *V) {
Arguments.push_back(V);
return *this;
}
~LogBuilder();
StringRef getFormat() const;
unsigned getNumArguments() const;
Value *getArgument(unsigned I) const;
};
/// A temporary-object class for building up diff messages.
class DiffLogBuilder {
typedef std::pair<Instruction*,Instruction*> DiffRecord;
SmallVector<DiffRecord, 20> Diff;
Consumer &consumer;
public:
DiffLogBuilder(Consumer &c) : consumer(c) {}
~DiffLogBuilder();
void addMatch(Instruction *L, Instruction *R);
// HACK: VS 2010 has a bug in the stdlib that requires this.
void addLeft(Instruction *L);
void addRight(Instruction *R);
unsigned getNumLines() const;
DiffChange getLineKind(unsigned I) const;
Instruction *getLeft(unsigned I) const;
Instruction *getRight(unsigned I) const;
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-diff/CMakeLists.txt | set(LLVM_LINK_COMPONENTS
Core
IRReader
Support
)
add_llvm_tool(llvm-diff
llvm-diff.cpp
DiffConsumer.cpp
DiffLog.cpp
DifferenceEngine.cpp
)
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-diff/LLVMBuild.txt | ;===- ./tools/llvm-diff/LLVMBuild.txt --------------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Tool
name = llvm-diff
parent = Tools
required_libraries = AsmParser BitReader IRReader
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-diff/DiffConsumer.cpp | //===-- DiffConsumer.cpp - Difference Consumer ------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This files implements the LLVM difference Consumer
//
//===----------------------------------------------------------------------===//
#include "DiffConsumer.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/ErrorHandling.h"
using namespace llvm;
static void ComputeNumbering(Function *F, DenseMap<Value*,unsigned> &Numbering){
unsigned IN = 0;
// Arguments get the first numbers.
for (Function::arg_iterator
AI = F->arg_begin(), AE = F->arg_end(); AI != AE; ++AI)
if (!AI->hasName())
Numbering[&*AI] = IN++;
// Walk the basic blocks in order.
for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) {
if (!FI->hasName())
Numbering[&*FI] = IN++;
// Walk the instructions in order.
for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
// void instructions don't get numbers.
if (!BI->hasName() && !BI->getType()->isVoidTy())
Numbering[&*BI] = IN++;
}
assert(!Numbering.empty() && "asked for numbering but numbering was no-op");
}
void Consumer::anchor() { }
void DiffConsumer::printValue(Value *V, bool isL) {
if (V->hasName()) {
out << (isa<GlobalValue>(V) ? '@' : '%') << V->getName();
return;
}
if (V->getType()->isVoidTy()) {
if (isa<StoreInst>(V)) {
out << "store to ";
printValue(cast<StoreInst>(V)->getPointerOperand(), isL);
} else if (isa<CallInst>(V)) {
out << "call to ";
printValue(cast<CallInst>(V)->getCalledValue(), isL);
} else if (isa<InvokeInst>(V)) {
out << "invoke to ";
printValue(cast<InvokeInst>(V)->getCalledValue(), isL);
} else {
out << *V;
}
return;
}
if (isa<Constant>(V)) {
out << *V;
return;
}
unsigned N = contexts.size();
while (N > 0) {
--N;
DiffContext &ctxt = contexts[N];
if (!ctxt.IsFunction) continue;
if (isL) {
if (ctxt.LNumbering.empty())
ComputeNumbering(cast<Function>(ctxt.L), ctxt.LNumbering);
out << '%' << ctxt.LNumbering[V];
return;
} else {
if (ctxt.RNumbering.empty())
ComputeNumbering(cast<Function>(ctxt.R), ctxt.RNumbering);
out << '%' << ctxt.RNumbering[V];
return;
}
}
out << "<anonymous>";
}
void DiffConsumer::header() {
if (contexts.empty()) return;
for (SmallVectorImpl<DiffContext>::iterator
I = contexts.begin(), E = contexts.end(); I != E; ++I) {
if (I->Differences) continue;
if (isa<Function>(I->L)) {
// Extra newline between functions.
if (Differences) out << "\n";
Function *L = cast<Function>(I->L);
Function *R = cast<Function>(I->R);
if (L->getName() != R->getName())
out << "in function " << L->getName()
<< " / " << R->getName() << ":\n";
else
out << "in function " << L->getName() << ":\n";
} else if (isa<BasicBlock>(I->L)) {
BasicBlock *L = cast<BasicBlock>(I->L);
BasicBlock *R = cast<BasicBlock>(I->R);
if (L->hasName() && R->hasName() && L->getName() == R->getName())
out << " in block %" << L->getName() << ":\n";
else {
out << " in block ";
printValue(L, true);
out << " / ";
printValue(R, false);
out << ":\n";
}
} else if (isa<Instruction>(I->L)) {
out << " in instruction ";
printValue(I->L, true);
out << " / ";
printValue(I->R, false);
out << ":\n";
}
I->Differences = true;
}
}
void DiffConsumer::indent() {
unsigned N = Indent;
while (N--) out << ' ';
}
bool DiffConsumer::hadDifferences() const {
return Differences;
}
void DiffConsumer::enterContext(Value *L, Value *R) {
contexts.push_back(DiffContext(L, R));
Indent += 2;
}
void DiffConsumer::exitContext() {
Differences |= contexts.back().Differences;
contexts.pop_back();
Indent -= 2;
}
void DiffConsumer::log(StringRef text) {
header();
indent();
out << text << '\n';
}
void DiffConsumer::logf(const LogBuilder &Log) {
header();
indent();
unsigned arg = 0;
StringRef format = Log.getFormat();
while (true) {
size_t percent = format.find('%');
if (percent == StringRef::npos) {
out << format;
break;
}
assert(format[percent] == '%');
if (percent > 0) out << format.substr(0, percent);
switch (format[percent+1]) {
case '%': out << '%'; break;
case 'l': printValue(Log.getArgument(arg++), true); break;
case 'r': printValue(Log.getArgument(arg++), false); break;
default: llvm_unreachable("unknown format character");
}
format = format.substr(percent+2);
}
out << '\n';
}
void DiffConsumer::logd(const DiffLogBuilder &Log) {
header();
for (unsigned I = 0, E = Log.getNumLines(); I != E; ++I) {
indent();
switch (Log.getLineKind(I)) {
case DC_match:
out << " ";
Log.getLeft(I)->dump();
//printValue(Log.getLeft(I), true);
break;
case DC_left:
out << "< ";
Log.getLeft(I)->dump();
//printValue(Log.getLeft(I), true);
break;
case DC_right:
out << "> ";
Log.getRight(I)->dump();
//printValue(Log.getRight(I), false);
break;
}
//out << "\n";
}
}
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-diff/DiffLog.cpp | //===-- DiffLog.h - Difference Log Builder and accessories ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This header defines the interface to the LLVM difference log builder.
//
//===----------------------------------------------------------------------===//
#include "DiffLog.h"
#include "DiffConsumer.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/Instructions.h"
using namespace llvm;
LogBuilder::~LogBuilder() {
consumer.logf(*this);
}
StringRef LogBuilder::getFormat() const { return Format; }
unsigned LogBuilder::getNumArguments() const { return Arguments.size(); }
Value *LogBuilder::getArgument(unsigned I) const { return Arguments[I]; }
DiffLogBuilder::~DiffLogBuilder() { consumer.logd(*this); }
void DiffLogBuilder::addMatch(Instruction *L, Instruction *R) {
Diff.push_back(DiffRecord(L, R));
}
void DiffLogBuilder::addLeft(Instruction *L) {
// HACK: VS 2010 has a bug in the stdlib that requires this.
Diff.push_back(DiffRecord(L, DiffRecord::second_type(nullptr)));
}
void DiffLogBuilder::addRight(Instruction *R) {
// HACK: VS 2010 has a bug in the stdlib that requires this.
Diff.push_back(DiffRecord(DiffRecord::first_type(nullptr), R));
}
unsigned DiffLogBuilder::getNumLines() const { return Diff.size(); }
DiffChange DiffLogBuilder::getLineKind(unsigned I) const {
return (Diff[I].first ? (Diff[I].second ? DC_match : DC_left)
: DC_right);
}
Instruction *DiffLogBuilder::getLeft(unsigned I) const { return Diff[I].first; }
Instruction *DiffLogBuilder::getRight(unsigned I) const { return Diff[I].second; }
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-diff/DifferenceEngine.h | //===-- DifferenceEngine.h - Module comparator ------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This header defines the interface to the LLVM difference engine,
// which structurally compares functions within a module.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TOOLS_LLVM_DIFF_DIFFERENCEENGINE_H
#define LLVM_TOOLS_LLVM_DIFF_DIFFERENCEENGINE_H
#include "DiffConsumer.h"
#include "DiffLog.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include <utility>
namespace llvm {
class Function;
class GlobalValue;
class Instruction;
class LLVMContext;
class Module;
class Twine;
class Value;
/// A class for performing structural comparisons of LLVM assembly.
class DifferenceEngine {
public:
/// A RAII object for recording the current context.
struct Context {
Context(DifferenceEngine &Engine, Value *L, Value *R) : Engine(Engine) {
Engine.consumer.enterContext(L, R);
}
~Context() {
Engine.consumer.exitContext();
}
private:
DifferenceEngine &Engine;
};
/// An oracle for answering whether two values are equivalent as
/// operands.
class Oracle {
virtual void anchor();
public:
virtual bool operator()(Value *L, Value *R) = 0;
protected:
virtual ~Oracle() {}
};
DifferenceEngine(Consumer &consumer)
: consumer(consumer), globalValueOracle(nullptr) {}
void diff(Module *L, Module *R);
void diff(Function *L, Function *R);
void log(StringRef text) {
consumer.log(text);
}
LogBuilder logf(StringRef text) {
return LogBuilder(consumer, text);
}
Consumer& getConsumer() const { return consumer; }
/// Installs an oracle to decide whether two global values are
/// equivalent as operands. Without an oracle, global values are
/// considered equivalent as operands precisely when they have the
/// same name.
void setGlobalValueOracle(Oracle *oracle) {
globalValueOracle = oracle;
}
/// Determines whether two global values are equivalent.
bool equivalentAsOperands(GlobalValue *L, GlobalValue *R);
private:
Consumer &consumer;
Oracle *globalValueOracle;
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-diff/llvm-diff.cpp | //===-- llvm-diff.cpp - Module comparator command-line driver ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the command-line driver for the difference engine.
//
//===----------------------------------------------------------------------===//
#include "DiffLog.h"
#include "DifferenceEngine.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include <string>
#include <utility>
using namespace llvm;
/// Reads a module from a file. On error, messages are written to stderr
/// and null is returned.
static std::unique_ptr<Module> readModule(LLVMContext &Context,
StringRef Name) {
SMDiagnostic Diag;
std::unique_ptr<Module> M = parseIRFile(Name, Diag, Context);
if (!M)
Diag.print("llvm-diff", errs());
return M;
}
static void diffGlobal(DifferenceEngine &Engine, Module &L, Module &R,
StringRef Name) {
// Drop leading sigils from the global name.
if (Name.startswith("@")) Name = Name.substr(1);
Function *LFn = L.getFunction(Name);
Function *RFn = R.getFunction(Name);
if (LFn && RFn)
Engine.diff(LFn, RFn);
else if (!LFn && !RFn)
errs() << "No function named @" << Name << " in either module\n";
else if (!LFn)
errs() << "No function named @" << Name << " in left module\n";
else
errs() << "No function named @" << Name << " in right module\n";
}
static cl::opt<std::string> LeftFilename(cl::Positional,
cl::desc("<first file>"),
cl::Required);
static cl::opt<std::string> RightFilename(cl::Positional,
cl::desc("<second file>"),
cl::Required);
static cl::list<std::string> GlobalsToCompare(cl::Positional,
cl::desc("<globals to compare>"));
// HLSL Change: changed calling convention to __cdecl
int __cdecl main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv);
LLVMContext Context;
// Load both modules. Die if that fails.
std::unique_ptr<Module> LModule = readModule(Context, LeftFilename);
std::unique_ptr<Module> RModule = readModule(Context, RightFilename);
if (!LModule || !RModule) return 1;
DiffConsumer Consumer;
DifferenceEngine Engine(Consumer);
// If any global names were given, just diff those.
if (!GlobalsToCompare.empty()) {
for (unsigned I = 0, E = GlobalsToCompare.size(); I != E; ++I)
diffGlobal(Engine, *LModule, *RModule, GlobalsToCompare[I]);
// Otherwise, diff everything in the module.
} else {
Engine.diff(LModule.get(), RModule.get());
}
return Consumer.hadDifferences();
}
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-diff/DifferenceEngine.cpp | //===-- DifferenceEngine.cpp - Structural function/module comparison ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This header defines the implementation of the LLVM difference
// engine, which structurally compares global values within a module.
//
//===----------------------------------------------------------------------===//
#include "DifferenceEngine.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/type_traits.h"
#include <utility>
using namespace llvm;
namespace {
/// A priority queue, implemented as a heap.
template <class T, class Sorter, unsigned InlineCapacity>
class PriorityQueue {
Sorter Precedes;
llvm::SmallVector<T, InlineCapacity> Storage;
public:
PriorityQueue(const Sorter &Precedes) : Precedes(Precedes) {}
/// Checks whether the heap is empty.
bool empty() const { return Storage.empty(); }
/// Insert a new value on the heap.
void insert(const T &V) {
unsigned Index = Storage.size();
Storage.push_back(V);
if (Index == 0) return;
T *data = Storage.data();
while (true) {
unsigned Target = (Index + 1) / 2 - 1;
if (!Precedes(data[Index], data[Target])) return;
std::swap(data[Index], data[Target]);
if (Target == 0) return;
Index = Target;
}
}
/// Remove the minimum value in the heap. Only valid on a non-empty heap.
T remove_min() {
assert(!empty());
T tmp = Storage[0];
unsigned NewSize = Storage.size() - 1;
if (NewSize) {
// Move the slot at the end to the beginning.
if (isPodLike<T>::value)
Storage[0] = Storage[NewSize];
else
std::swap(Storage[0], Storage[NewSize]);
// Bubble the root up as necessary.
unsigned Index = 0;
while (true) {
// With a 1-based index, the children would be Index*2 and Index*2+1.
unsigned R = (Index + 1) * 2;
unsigned L = R - 1;
// If R is out of bounds, we're done after this in any case.
if (R >= NewSize) {
// If L is also out of bounds, we're done immediately.
if (L >= NewSize) break;
// Otherwise, test whether we should swap L and Index.
if (Precedes(Storage[L], Storage[Index]))
std::swap(Storage[L], Storage[Index]);
break;
}
// Otherwise, we need to compare with the smaller of L and R.
// Prefer R because it's closer to the end of the array.
unsigned IndexToTest = (Precedes(Storage[L], Storage[R]) ? L : R);
// If Index is >= the min of L and R, then heap ordering is restored.
if (!Precedes(Storage[IndexToTest], Storage[Index]))
break;
// Otherwise, keep bubbling up.
std::swap(Storage[IndexToTest], Storage[Index]);
Index = IndexToTest;
}
}
Storage.pop_back();
return tmp;
}
};
/// A function-scope difference engine.
class FunctionDifferenceEngine {
DifferenceEngine &Engine;
/// The current mapping from old local values to new local values.
DenseMap<Value*, Value*> Values;
/// The current mapping from old blocks to new blocks.
DenseMap<BasicBlock*, BasicBlock*> Blocks;
DenseSet<std::pair<Value*, Value*> > TentativeValues;
unsigned getUnprocPredCount(BasicBlock *Block) const {
unsigned Count = 0;
for (pred_iterator I = pred_begin(Block), E = pred_end(Block); I != E; ++I)
if (!Blocks.count(*I)) Count++;
return Count;
}
typedef std::pair<BasicBlock*, BasicBlock*> BlockPair;
/// A type which sorts a priority queue by the number of unprocessed
/// predecessor blocks it has remaining.
///
/// This is actually really expensive to calculate.
struct QueueSorter {
const FunctionDifferenceEngine &fde;
explicit QueueSorter(const FunctionDifferenceEngine &fde) : fde(fde) {}
bool operator()(const BlockPair &Old, const BlockPair &New) {
return fde.getUnprocPredCount(Old.first)
< fde.getUnprocPredCount(New.first);
}
};
/// A queue of unified blocks to process.
PriorityQueue<BlockPair, QueueSorter, 20> Queue;
/// Try to unify the given two blocks. Enqueues them for processing
/// if they haven't already been processed.
///
/// Returns true if there was a problem unifying them.
bool tryUnify(BasicBlock *L, BasicBlock *R) {
BasicBlock *&Ref = Blocks[L];
if (Ref) {
if (Ref == R) return false;
Engine.logf("successor %l cannot be equivalent to %r; "
"it's already equivalent to %r")
<< L << R << Ref;
return true;
}
Ref = R;
Queue.insert(BlockPair(L, R));
return false;
}
/// Unifies two instructions, given that they're known not to have
/// structural differences.
void unify(Instruction *L, Instruction *R) {
DifferenceEngine::Context C(Engine, L, R);
bool Result = diff(L, R, true, true);
assert(!Result && "structural differences second time around?");
(void) Result;
if (!L->use_empty())
Values[L] = R;
}
void processQueue() {
while (!Queue.empty()) {
BlockPair Pair = Queue.remove_min();
diff(Pair.first, Pair.second);
}
}
void diff(BasicBlock *L, BasicBlock *R) {
DifferenceEngine::Context C(Engine, L, R);
BasicBlock::iterator LI = L->begin(), LE = L->end();
BasicBlock::iterator RI = R->begin();
do {
assert(LI != LE && RI != R->end());
Instruction *LeftI = &*LI, *RightI = &*RI;
// If the instructions differ, start the more sophisticated diff
// algorithm at the start of the block.
if (diff(LeftI, RightI, false, false)) {
TentativeValues.clear();
return runBlockDiff(L->begin(), R->begin());
}
// Otherwise, tentatively unify them.
if (!LeftI->use_empty())
TentativeValues.insert(std::make_pair(LeftI, RightI));
++LI, ++RI;
} while (LI != LE); // This is sufficient: we can't get equality of
// terminators if there are residual instructions.
// Unify everything in the block, non-tentatively this time.
TentativeValues.clear();
for (LI = L->begin(), RI = R->begin(); LI != LE; ++LI, ++RI)
unify(&*LI, &*RI);
}
bool matchForBlockDiff(Instruction *L, Instruction *R);
void runBlockDiff(BasicBlock::iterator LI, BasicBlock::iterator RI);
bool diffCallSites(CallSite L, CallSite R, bool Complain) {
// FIXME: call attributes
if (!equivalentAsOperands(L.getCalledValue(), R.getCalledValue())) {
if (Complain) Engine.log("called functions differ");
return true;
}
if (L.arg_size() != R.arg_size()) {
if (Complain) Engine.log("argument counts differ");
return true;
}
for (unsigned I = 0, E = L.arg_size(); I != E; ++I)
if (!equivalentAsOperands(L.getArgument(I), R.getArgument(I))) {
if (Complain)
Engine.logf("arguments %l and %r differ")
<< L.getArgument(I) << R.getArgument(I);
return true;
}
return false;
}
bool diff(Instruction *L, Instruction *R, bool Complain, bool TryUnify) {
// FIXME: metadata (if Complain is set)
// Different opcodes always imply different operations.
if (L->getOpcode() != R->getOpcode()) {
if (Complain) Engine.log("different instruction types");
return true;
}
if (isa<CmpInst>(L)) {
if (cast<CmpInst>(L)->getPredicate()
!= cast<CmpInst>(R)->getPredicate()) {
if (Complain) Engine.log("different predicates");
return true;
}
} else if (isa<CallInst>(L)) {
return diffCallSites(CallSite(L), CallSite(R), Complain);
} else if (isa<PHINode>(L)) {
// FIXME: implement.
// This is really weird; type uniquing is broken?
if (L->getType() != R->getType()) {
if (!L->getType()->isPointerTy() || !R->getType()->isPointerTy()) {
if (Complain) Engine.log("different phi types");
return true;
}
}
return false;
// Terminators.
} else if (isa<InvokeInst>(L)) {
InvokeInst *LI = cast<InvokeInst>(L);
InvokeInst *RI = cast<InvokeInst>(R);
if (diffCallSites(CallSite(LI), CallSite(RI), Complain))
return true;
if (TryUnify) {
tryUnify(LI->getNormalDest(), RI->getNormalDest());
tryUnify(LI->getUnwindDest(), RI->getUnwindDest());
}
return false;
} else if (isa<BranchInst>(L)) {
BranchInst *LI = cast<BranchInst>(L);
BranchInst *RI = cast<BranchInst>(R);
if (LI->isConditional() != RI->isConditional()) {
if (Complain) Engine.log("branch conditionality differs");
return true;
}
if (LI->isConditional()) {
if (!equivalentAsOperands(LI->getCondition(), RI->getCondition())) {
if (Complain) Engine.log("branch conditions differ");
return true;
}
if (TryUnify) tryUnify(LI->getSuccessor(1), RI->getSuccessor(1));
}
if (TryUnify) tryUnify(LI->getSuccessor(0), RI->getSuccessor(0));
return false;
} else if (isa<SwitchInst>(L)) {
SwitchInst *LI = cast<SwitchInst>(L);
SwitchInst *RI = cast<SwitchInst>(R);
if (!equivalentAsOperands(LI->getCondition(), RI->getCondition())) {
if (Complain) Engine.log("switch conditions differ");
return true;
}
if (TryUnify) tryUnify(LI->getDefaultDest(), RI->getDefaultDest());
bool Difference = false;
DenseMap<ConstantInt*,BasicBlock*> LCases;
for (SwitchInst::CaseIt I = LI->case_begin(), E = LI->case_end();
I != E; ++I)
LCases[I.getCaseValue()] = I.getCaseSuccessor();
for (SwitchInst::CaseIt I = RI->case_begin(), E = RI->case_end();
I != E; ++I) {
ConstantInt *CaseValue = I.getCaseValue();
BasicBlock *LCase = LCases[CaseValue];
if (LCase) {
if (TryUnify) tryUnify(LCase, I.getCaseSuccessor());
LCases.erase(CaseValue);
} else if (Complain || !Difference) {
if (Complain)
Engine.logf("right switch has extra case %r") << CaseValue;
Difference = true;
}
}
if (!Difference)
for (DenseMap<ConstantInt*,BasicBlock*>::iterator
I = LCases.begin(), E = LCases.end(); I != E; ++I) {
if (Complain)
Engine.logf("left switch has extra case %l") << I->first;
Difference = true;
}
return Difference;
} else if (isa<UnreachableInst>(L)) {
return false;
}
if (L->getNumOperands() != R->getNumOperands()) {
if (Complain) Engine.log("instructions have different operand counts");
return true;
}
for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) {
Value *LO = L->getOperand(I), *RO = R->getOperand(I);
if (!equivalentAsOperands(LO, RO)) {
if (Complain) Engine.logf("operands %l and %r differ") << LO << RO;
return true;
}
}
return false;
}
bool equivalentAsOperands(Constant *L, Constant *R) {
// Use equality as a preliminary filter.
if (L == R)
return true;
if (L->getValueID() != R->getValueID())
return false;
// Ask the engine about global values.
if (isa<GlobalValue>(L))
return Engine.equivalentAsOperands(cast<GlobalValue>(L),
cast<GlobalValue>(R));
// Compare constant expressions structurally.
if (isa<ConstantExpr>(L))
return equivalentAsOperands(cast<ConstantExpr>(L),
cast<ConstantExpr>(R));
// Nulls of the "same type" don't always actually have the same
// type; I don't know why. Just white-list them.
if (isa<ConstantPointerNull>(L))
return true;
// Block addresses only match if we've already encountered the
// block. FIXME: tentative matches?
if (isa<BlockAddress>(L))
return Blocks[cast<BlockAddress>(L)->getBasicBlock()]
== cast<BlockAddress>(R)->getBasicBlock();
return false;
}
bool equivalentAsOperands(ConstantExpr *L, ConstantExpr *R) {
if (L == R)
return true;
if (L->getOpcode() != R->getOpcode())
return false;
switch (L->getOpcode()) {
case Instruction::ICmp:
case Instruction::FCmp:
if (L->getPredicate() != R->getPredicate())
return false;
break;
case Instruction::GetElementPtr:
// FIXME: inbounds?
break;
default:
break;
}
if (L->getNumOperands() != R->getNumOperands())
return false;
for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I)
if (!equivalentAsOperands(L->getOperand(I), R->getOperand(I)))
return false;
return true;
}
bool equivalentAsOperands(Value *L, Value *R) {
// Fall out if the values have different kind.
// This possibly shouldn't take priority over oracles.
if (L->getValueID() != R->getValueID())
return false;
// Value subtypes: Argument, Constant, Instruction, BasicBlock,
// InlineAsm, MDNode, MDString, PseudoSourceValue
if (isa<Constant>(L))
return equivalentAsOperands(cast<Constant>(L), cast<Constant>(R));
if (isa<Instruction>(L))
return Values[L] == R || TentativeValues.count(std::make_pair(L, R));
if (isa<Argument>(L))
return Values[L] == R;
if (isa<BasicBlock>(L))
return Blocks[cast<BasicBlock>(L)] != R;
// Pretend everything else is identical.
return true;
}
// Avoid a gcc warning about accessing 'this' in an initializer.
FunctionDifferenceEngine *this_() { return this; }
public:
FunctionDifferenceEngine(DifferenceEngine &Engine) :
Engine(Engine), Queue(QueueSorter(*this_())) {}
void diff(Function *L, Function *R) {
if (L->arg_size() != R->arg_size())
Engine.log("different argument counts");
// Map the arguments.
for (Function::arg_iterator
LI = L->arg_begin(), LE = L->arg_end(),
RI = R->arg_begin(), RE = R->arg_end();
LI != LE && RI != RE; ++LI, ++RI)
Values[&*LI] = &*RI;
tryUnify(&*L->begin(), &*R->begin());
processQueue();
}
};
struct DiffEntry {
DiffEntry() : Cost(0) {}
unsigned Cost;
llvm::SmallVector<char, 8> Path; // actually of DifferenceEngine::DiffChange
};
bool FunctionDifferenceEngine::matchForBlockDiff(Instruction *L,
Instruction *R) {
return !diff(L, R, false, false);
}
void FunctionDifferenceEngine::runBlockDiff(BasicBlock::iterator LStart,
BasicBlock::iterator RStart) {
BasicBlock::iterator LE = LStart->getParent()->end();
BasicBlock::iterator RE = RStart->getParent()->end();
unsigned NL = std::distance(LStart, LE);
SmallVector<DiffEntry, 20> Paths1(NL+1);
SmallVector<DiffEntry, 20> Paths2(NL+1);
DiffEntry *Cur = Paths1.data();
DiffEntry *Next = Paths2.data();
const unsigned LeftCost = 2;
const unsigned RightCost = 2;
const unsigned MatchCost = 0;
assert(TentativeValues.empty());
// Initialize the first column.
for (unsigned I = 0; I != NL+1; ++I) {
Cur[I].Cost = I * LeftCost;
for (unsigned J = 0; J != I; ++J)
Cur[I].Path.push_back(DC_left);
}
for (BasicBlock::iterator RI = RStart; RI != RE; ++RI) {
// Initialize the first row.
Next[0] = Cur[0];
Next[0].Cost += RightCost;
Next[0].Path.push_back(DC_right);
unsigned Index = 1;
for (BasicBlock::iterator LI = LStart; LI != LE; ++LI, ++Index) {
if (matchForBlockDiff(&*LI, &*RI)) {
Next[Index] = Cur[Index-1];
Next[Index].Cost += MatchCost;
Next[Index].Path.push_back(DC_match);
TentativeValues.insert(std::make_pair(&*LI, &*RI));
} else if (Next[Index-1].Cost <= Cur[Index].Cost) {
Next[Index] = Next[Index-1];
Next[Index].Cost += LeftCost;
Next[Index].Path.push_back(DC_left);
} else {
Next[Index] = Cur[Index];
Next[Index].Cost += RightCost;
Next[Index].Path.push_back(DC_right);
}
}
std::swap(Cur, Next);
}
// We don't need the tentative values anymore; everything from here
// on out should be non-tentative.
TentativeValues.clear();
SmallVectorImpl<char> &Path = Cur[NL].Path;
BasicBlock::iterator LI = LStart, RI = RStart;
DiffLogBuilder Diff(Engine.getConsumer());
// Drop trailing matches.
while (Path.back() == DC_match)
Path.pop_back();
// Skip leading matches.
SmallVectorImpl<char>::iterator
PI = Path.begin(), PE = Path.end();
while (PI != PE && *PI == DC_match) {
unify(&*LI, &*RI);
++PI, ++LI, ++RI;
}
for (; PI != PE; ++PI) {
switch (static_cast<DiffChange>(*PI)) {
case DC_match:
assert(LI != LE && RI != RE);
{
Instruction *L = &*LI, *R = &*RI;
unify(L, R);
Diff.addMatch(L, R);
}
++LI; ++RI;
break;
case DC_left:
assert(LI != LE);
Diff.addLeft(&*LI);
++LI;
break;
case DC_right:
assert(RI != RE);
Diff.addRight(&*RI);
++RI;
break;
}
}
// Finishing unifying and complaining about the tails of the block,
// which should be matches all the way through.
while (LI != LE) {
assert(RI != RE);
unify(&*LI, &*RI);
++LI, ++RI;
}
// If the terminators have different kinds, but one is an invoke and the
// other is an unconditional branch immediately following a call, unify
// the results and the destinations.
TerminatorInst *LTerm = LStart->getParent()->getTerminator();
TerminatorInst *RTerm = RStart->getParent()->getTerminator();
if (isa<BranchInst>(LTerm) && isa<InvokeInst>(RTerm)) {
if (cast<BranchInst>(LTerm)->isConditional()) return;
BasicBlock::iterator I = LTerm;
if (I == LStart->getParent()->begin()) return;
--I;
if (!isa<CallInst>(*I)) return;
CallInst *LCall = cast<CallInst>(&*I);
InvokeInst *RInvoke = cast<InvokeInst>(RTerm);
if (!equivalentAsOperands(LCall->getCalledValue(), RInvoke->getCalledValue()))
return;
if (!LCall->use_empty())
Values[LCall] = RInvoke;
tryUnify(LTerm->getSuccessor(0), RInvoke->getNormalDest());
} else if (isa<InvokeInst>(LTerm) && isa<BranchInst>(RTerm)) {
if (cast<BranchInst>(RTerm)->isConditional()) return;
BasicBlock::iterator I = RTerm;
if (I == RStart->getParent()->begin()) return;
--I;
if (!isa<CallInst>(*I)) return;
CallInst *RCall = cast<CallInst>(I);
InvokeInst *LInvoke = cast<InvokeInst>(LTerm);
if (!equivalentAsOperands(LInvoke->getCalledValue(), RCall->getCalledValue()))
return;
if (!LInvoke->use_empty())
Values[LInvoke] = RCall;
tryUnify(LInvoke->getNormalDest(), RTerm->getSuccessor(0));
}
}
}
void DifferenceEngine::Oracle::anchor() { }
void DifferenceEngine::diff(Function *L, Function *R) {
Context C(*this, L, R);
// FIXME: types
// FIXME: attributes and CC
// FIXME: parameter attributes
// If both are declarations, we're done.
if (L->empty() && R->empty())
return;
else if (L->empty())
log("left function is declaration, right function is definition");
else if (R->empty())
log("right function is declaration, left function is definition");
else
FunctionDifferenceEngine(*this).diff(L, R);
}
void DifferenceEngine::diff(Module *L, Module *R) {
StringSet<> LNames;
SmallVector<std::pair<Function*,Function*>, 20> Queue;
for (Module::iterator I = L->begin(), E = L->end(); I != E; ++I) {
Function *LFn = &*I;
LNames.insert(LFn->getName());
if (Function *RFn = R->getFunction(LFn->getName()))
Queue.push_back(std::make_pair(LFn, RFn));
else
logf("function %l exists only in left module") << LFn;
}
for (Module::iterator I = R->begin(), E = R->end(); I != E; ++I) {
Function *RFn = &*I;
if (!LNames.count(RFn->getName()))
logf("function %r exists only in right module") << RFn;
}
for (SmallVectorImpl<std::pair<Function*,Function*> >::iterator
I = Queue.begin(), E = Queue.end(); I != E; ++I)
diff(I->first, I->second);
}
bool DifferenceEngine::equivalentAsOperands(GlobalValue *L, GlobalValue *R) {
if (globalValueOracle) return (*globalValueOracle)(L, R);
return L->getName() == R->getName();
}
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-diff/DiffConsumer.h | //===-- DiffConsumer.h - Difference Consumer --------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This header defines the interface to the LLVM difference Consumer
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TOOLS_LLVM_DIFF_DIFFCONSUMER_H
#define LLVM_TOOLS_LLVM_DIFF_DIFFCONSUMER_H
#include "DiffLog.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
namespace llvm {
class Module;
class Value;
class Function;
/// The interface for consumers of difference data.
class Consumer {
virtual void anchor();
public:
/// Record that a local context has been entered. Left and
/// Right are IR "containers" of some sort which are being
/// considered for structural equivalence: global variables,
/// functions, blocks, instructions, etc.
virtual void enterContext(Value *Left, Value *Right) = 0;
/// Record that a local context has been exited.
virtual void exitContext() = 0;
/// Record a difference within the current context.
virtual void log(StringRef Text) = 0;
/// Record a formatted difference within the current context.
virtual void logf(const LogBuilder &Log) = 0;
/// Record a line-by-line instruction diff.
virtual void logd(const DiffLogBuilder &Log) = 0;
protected:
virtual ~Consumer() {}
};
class DiffConsumer : public Consumer {
private:
struct DiffContext {
DiffContext(Value *L, Value *R)
: L(L), R(R), Differences(false), IsFunction(isa<Function>(L)) {}
Value *L;
Value *R;
bool Differences;
bool IsFunction;
DenseMap<Value*,unsigned> LNumbering;
DenseMap<Value*,unsigned> RNumbering;
};
raw_ostream &out;
SmallVector<DiffContext, 5> contexts;
bool Differences;
unsigned Indent;
void printValue(Value *V, bool isL);
void header();
void indent();
public:
DiffConsumer()
: out(errs()), Differences(false), Indent(0) {}
bool hadDifferences() const;
void enterContext(Value *L, Value *R) override;
void exitContext() override;
void log(StringRef text) override;
void logf(const LogBuilder &Log) override;
void logd(const DiffLogBuilder &Log) override;
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-link/CMakeLists.txt | set(LLVM_LINK_COMPONENTS
BitWriter
Core
IRReader
Linker
Support
)
add_llvm_tool(llvm-link
llvm-link.cpp
)
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-link/LLVMBuild.txt | ;===- ./tools/llvm-link/LLVMBuild.txt --------------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Tool
name = llvm-link
parent = Tools
required_libraries = AsmParser BitReader BitWriter IRReader Linker
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/llvm-link/llvm-link.cpp | //===- llvm-link.cpp - Low-level LLVM linker ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility may be invoked in the following manner:
// llvm-link a.bc b.bc c.bc -o x.bc
//
//===----------------------------------------------------------------------===//
#include "llvm/Linker/Linker.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/AutoUpgrade.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/ToolOutputFile.h"
#include <memory>
using namespace llvm;
static cl::list<std::string>
InputFilenames(cl::Positional, cl::OneOrMore,
cl::desc("<input bitcode files>"));
static cl::list<std::string> OverridingInputs(
"override", cl::ZeroOrMore, cl::value_desc("filename"),
cl::desc(
"input bitcode file which can override previously defined symbol(s)"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Override output filename"), cl::init("-"),
cl::value_desc("filename"));
static cl::opt<bool>
Force("f", cl::desc("Enable binary output on terminals"));
static cl::opt<bool>
OutputAssembly("S",
cl::desc("Write output as LLVM assembly"), cl::Hidden);
static cl::opt<bool>
Verbose("v", cl::desc("Print information about actions taken"));
static cl::opt<bool>
DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden);
static cl::opt<bool>
SuppressWarnings("suppress-warnings", cl::desc("Suppress all linking warnings"),
cl::init(false));
static cl::opt<bool> PreserveBitcodeUseListOrder(
"preserve-bc-uselistorder",
cl::desc("Preserve use-list order when writing LLVM bitcode."),
cl::init(true), cl::Hidden);
static cl::opt<bool> PreserveAssemblyUseListOrder(
"preserve-ll-uselistorder",
cl::desc("Preserve use-list order when writing LLVM assembly."),
cl::init(false), cl::Hidden);
// Read the specified bitcode file in and return it. This routine searches the
// link path for the specified file to try to find it...
//
static std::unique_ptr<Module>
loadFile(const char *argv0, const std::string &FN, LLVMContext &Context) {
SMDiagnostic Err;
if (Verbose) errs() << "Loading '" << FN << "'\n";
std::unique_ptr<Module> Result = getLazyIRFileModule(FN, Err, Context);
if (!Result)
Err.print(argv0, errs());
Result->materializeMetadata();
UpgradeDebugInfo(*Result);
return Result;
}
static void diagnosticHandler(const DiagnosticInfo &DI) {
unsigned Severity = DI.getSeverity();
switch (Severity) {
case DS_Error:
errs() << "ERROR: ";
break;
case DS_Warning:
if (SuppressWarnings)
return;
errs() << "WARNING: ";
break;
case DS_Remark:
case DS_Note:
llvm_unreachable("Only expecting warnings and errors");
}
DiagnosticPrinterRawOStream DP(errs());
DI.print(DP);
errs() << '\n';
}
static bool linkFiles(const char *argv0, LLVMContext &Context, Linker &L,
const cl::list<std::string> &Files,
bool OverrideDuplicateSymbols) {
for (const auto &File : Files) {
std::unique_ptr<Module> M = loadFile(argv0, File, Context);
if (!M.get()) {
errs() << argv0 << ": error loading file '" << File << "'\n";
return false;
}
if (verifyModule(*M, &errs())) {
errs() << argv0 << ": " << File << ": error: input module is broken!\n";
return false;
}
if (Verbose)
errs() << "Linking in '" << File << "'\n";
if (L.linkInModule(M.get(), OverrideDuplicateSymbols))
return false;
}
return true;
}
// HLSL Change: changed calling convention to __cdecl
int __cdecl main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "llvm linker\n");
auto Composite = make_unique<Module>("llvm-link", Context);
Linker L(Composite.get(), diagnosticHandler);
// First add all the regular input files
if (!linkFiles(argv[0], Context, L, InputFilenames, false))
return 1;
// Next the -override ones.
if (!linkFiles(argv[0], Context, L, OverridingInputs, true))
return 1;
if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite;
std::error_code EC;
tool_output_file Out(OutputFilename, EC, sys::fs::F_None);
if (EC) {
errs() << EC.message() << '\n';
return 1;
}
if (verifyModule(*Composite, &errs())) {
errs() << argv[0] << ": error: linked module is broken!\n";
return 1;
}
if (Verbose) errs() << "Writing bitcode...\n";
if (OutputAssembly) {
Composite->print(Out.os(), nullptr, PreserveAssemblyUseListOrder);
} else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
WriteBitcodeToFile(Composite.get(), Out.os(), PreserveBitcodeUseListOrder);
// Declare success.
Out.keep();
return 0;
}
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/clang/NOTES.txt | //===---------------------------------------------------------------------===//
// Random Notes
//===---------------------------------------------------------------------===//
//===---------------------------------------------------------------------===//
To time GCC preprocessing speed without output, use:
"time gcc -MM file"
This is similar to -Eonly.
//===---------------------------------------------------------------------===//
Creating and using a PTH file for performance measurement (use a release build).
$ clang -ccc-pch-is-pth -x objective-c-header INPUTS/Cocoa_h.m -o /tmp/tokencache
$ clang -cc1 -token-cache /tmp/tokencache INPUTS/Cocoa_h.m
//===---------------------------------------------------------------------===//
C++ Template Instantiation benchmark:
http://users.rcn.com/abrahams/instantiation_speed/index.html
//===---------------------------------------------------------------------===//
TODO: File Manager Speedup:
We currently do a lot of stat'ing for files that don't exist, particularly
when lots of -I paths exist (e.g. see the <iostream> example, check for
failures in stat in FileManager::getFile). It would be far better to make
the following changes:
1. FileEntry contains a sys::Path instead of a std::string for Name.
2. sys::Path contains timestamp and size, lazily computed. Eliminate from
FileEntry.
3. File UIDs are created on request, not when files are opened.
These changes make it possible to efficiently have FileEntry objects for
files that exist on the file system, but have not been used yet.
Once this is done:
1. DirectoryEntry gets a boolean value "has read entries". When false, not
all entries in the directory are in the file mgr, when true, they are.
2. Instead of stat'ing the file in FileManager::getFile, check to see if
the dir has been read. If so, fail immediately, if not, read the dir,
then retry.
3. Reading the dir uses the getdirentries syscall, creating a FileEntry
for all files found.
//===---------------------------------------------------------------------===//
// Specifying targets: -triple and -arch
//===---------------------------------------------------------------------===//
The clang supports "-triple" and "-arch" options. At most one -triple and one
-arch option may be specified. Both are optional.
The "selection of target" behavior is defined as follows:
(1) If the user does not specify -triple, we default to the host triple.
(2) If the user specifies a -arch, that overrides the arch in the host or
specified triple.
//===---------------------------------------------------------------------===//
verifyInputConstraint and verifyOutputConstraint should not return bool.
Instead we should return something like:
enum VerifyConstraintResult {
Valid,
// Output only
OutputOperandConstraintLacksEqualsCharacter,
MatchingConstraintNotValidInOutputOperand,
// Input only
InputOperandConstraintContainsEqualsCharacter,
MatchingConstraintReferencesInvalidOperandNumber,
// Both
PercentConstraintUsedWithLastOperand
};
//===---------------------------------------------------------------------===//
Blocks should not capture variables that are only used in dead code.
The rule that we came up with is that blocks are required to capture
variables if they're referenced in evaluated code, even if that code
doesn't actually rely on the value of the captured variable.
For example, this requires a capture:
(void) var;
But this does not:
if (false) puts(var);
Summary of <rdar://problem/9851835>: if we implement this, we should
warn about non-POD variables that are referenced but not captured, but
only if the non-reachability is not due to macro or template
metaprogramming.
//===---------------------------------------------------------------------===//
We can still apply a modified version of the constructor/destructor
delegation optimization in cases of virtual inheritance where:
- there is no function-try-block,
- the constructor signature is not variadic, and
- the parameter variables can safely be copied and repassed
to the base constructor because either
- they have not had their addresses taken by the vbase initializers or
- they were passed indirectly.
//===---------------------------------------------------------------------===//
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/clang/CMakeLists.txt | cmake_minimum_required(VERSION 2.8.8)
# FIXME: It may be removed when we use 2.8.12.
if(CMAKE_VERSION VERSION_LESS 2.8.12)
# Invalidate a couple of keywords.
set(cmake_2_8_12_INTERFACE)
set(cmake_2_8_12_PRIVATE)
else()
# Use ${cmake_2_8_12_KEYWORD} intead of KEYWORD in target_link_libraries().
set(cmake_2_8_12_INTERFACE INTERFACE)
set(cmake_2_8_12_PRIVATE PRIVATE)
if(POLICY CMP0022)
cmake_policy(SET CMP0022 NEW) # automatic when 2.8.12 is required
endif()
endif()
# If we are not building as a part of LLVM, build Clang as an
# standalone project, using LLVM as an external library:
if( CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR )
project(Clang)
# Rely on llvm-config.
set(CONFIG_OUTPUT)
find_program(LLVM_CONFIG "llvm-config")
if(LLVM_CONFIG)
message(STATUS "Found LLVM_CONFIG as ${LLVM_CONFIG}")
set(CONFIG_COMMAND ${LLVM_CONFIG}
"--assertion-mode"
"--bindir"
"--libdir"
"--includedir"
"--prefix"
"--src-root")
execute_process(
COMMAND ${CONFIG_COMMAND}
RESULT_VARIABLE HAD_ERROR
OUTPUT_VARIABLE CONFIG_OUTPUT
)
if(NOT HAD_ERROR)
string(REGEX REPLACE
"[ \t]*[\r\n]+[ \t]*" ";"
CONFIG_OUTPUT ${CONFIG_OUTPUT})
else()
string(REPLACE ";" " " CONFIG_COMMAND_STR "${CONFIG_COMMAND}")
message(STATUS "${CONFIG_COMMAND_STR}")
message(FATAL_ERROR "llvm-config failed with status ${HAD_ERROR}")
endif()
else()
message(FATAL_ERROR "llvm-config not found -- ${LLVM_CONFIG}")
endif()
list(GET CONFIG_OUTPUT 0 ENABLE_ASSERTIONS)
list(GET CONFIG_OUTPUT 1 TOOLS_BINARY_DIR)
list(GET CONFIG_OUTPUT 2 LIBRARY_DIR)
list(GET CONFIG_OUTPUT 3 INCLUDE_DIR)
list(GET CONFIG_OUTPUT 4 LLVM_OBJ_ROOT)
list(GET CONFIG_OUTPUT 5 MAIN_SRC_DIR)
if(NOT MSVC_IDE)
set(LLVM_ENABLE_ASSERTIONS ${ENABLE_ASSERTIONS}
CACHE BOOL "Enable assertions")
# Assertions should follow llvm-config's.
mark_as_advanced(LLVM_ENABLE_ASSERTIONS)
endif()
set(LLVM_TOOLS_BINARY_DIR ${TOOLS_BINARY_DIR} CACHE PATH "Path to llvm/bin")
set(LLVM_LIBRARY_DIR ${LIBRARY_DIR} CACHE PATH "Path to llvm/lib")
set(LLVM_MAIN_INCLUDE_DIR ${INCLUDE_DIR} CACHE PATH "Path to llvm/include")
set(LLVM_BINARY_DIR ${LLVM_OBJ_ROOT} CACHE PATH "Path to LLVM build tree")
set(LLVM_MAIN_SRC_DIR ${MAIN_SRC_DIR} CACHE PATH "Path to LLVM source tree")
find_program(LLVM_TABLEGEN_EXE "llvm-tblgen" ${LLVM_TOOLS_BINARY_DIR}
NO_DEFAULT_PATH)
set(LLVM_CMAKE_PATH "${LLVM_BINARY_DIR}/share/llvm/cmake")
set(LLVMCONFIG_FILE "${LLVM_CMAKE_PATH}/LLVMConfig.cmake")
if(EXISTS ${LLVMCONFIG_FILE})
list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_PATH}")
include(${LLVMCONFIG_FILE})
else()
message(FATAL_ERROR "Not found: ${LLVMCONFIG_FILE}")
endif()
# They are used as destination of target generators.
set(LLVM_RUNTIME_OUTPUT_INTDIR ${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/bin)
set(LLVM_LIBRARY_OUTPUT_INTDIR ${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/lib${LLVM_LIBDIR_SUFFIX})
if(WIN32 OR CYGWIN)
# DLL platform -- put DLLs into bin.
set(LLVM_SHLIB_OUTPUT_INTDIR ${LLVM_RUNTIME_OUTPUT_INTDIR})
else()
set(LLVM_SHLIB_OUTPUT_INTDIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
endif()
option(LLVM_INSTALL_TOOLCHAIN_ONLY
"Only include toolchain files in the 'install' target." OFF)
option(LLVM_FORCE_USE_OLD_HOST_TOOLCHAIN
"Set to ON to force using an old, unsupported host toolchain." OFF)
include(AddLLVM)
include(TableGen)
include(HandleLLVMOptions)
set(PACKAGE_VERSION "${LLVM_PACKAGE_VERSION}")
if (NOT DEFINED LLVM_INCLUDE_TESTS)
set(LLVM_INCLUDE_TESTS ON)
endif()
include_directories("${LLVM_BINARY_DIR}/include" "${LLVM_MAIN_INCLUDE_DIR}")
link_directories("${LLVM_LIBRARY_DIR}")
set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin )
set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib${LLVM_LIBDIR_SUFFIX} )
set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib${LLVM_LIBDIR_SUFFIX} )
if(LLVM_INCLUDE_TESTS)
# Check prebuilt llvm/utils.
if(EXISTS ${LLVM_TOOLS_BINARY_DIR}/FileCheck${CMAKE_EXECUTABLE_SUFFIX}
AND EXISTS ${LLVM_TOOLS_BINARY_DIR}/count${CMAKE_EXECUTABLE_SUFFIX}
AND EXISTS ${LLVM_TOOLS_BINARY_DIR}/not${CMAKE_EXECUTABLE_SUFFIX})
set(LLVM_UTILS_PROVIDED ON)
endif()
if(EXISTS ${LLVM_MAIN_SRC_DIR}/utils/lit/lit.py)
set(LLVM_LIT ${LLVM_MAIN_SRC_DIR}/utils/lit/lit.py)
if(NOT LLVM_UTILS_PROVIDED)
add_subdirectory(${LLVM_MAIN_SRC_DIR}/utils/FileCheck utils/FileCheck)
add_subdirectory(${LLVM_MAIN_SRC_DIR}/utils/count utils/count)
add_subdirectory(${LLVM_MAIN_SRC_DIR}/utils/not utils/not)
set(LLVM_UTILS_PROVIDED ON)
set(CLANG_TEST_DEPS FileCheck count not)
endif()
set(UNITTEST_DIR ${LLVM_MAIN_SRC_DIR}/utils/unittest)
if(EXISTS ${UNITTEST_DIR}/googletest/include/gtest/gtest.h
AND NOT EXISTS ${LLVM_LIBRARY_DIR}/${CMAKE_STATIC_LIBRARY_PREFIX}gtest${CMAKE_STATIC_LIBRARY_SUFFIX}
AND EXISTS ${UNITTEST_DIR}/CMakeLists.txt)
add_subdirectory(${UNITTEST_DIR} utils/unittest)
endif()
else()
# Seek installed Lit.
find_program(LLVM_LIT "lit.py" ${LLVM_MAIN_SRC_DIR}/utils/lit
DOC "Path to lit.py")
endif()
if(LLVM_LIT)
# Define the default arguments to use with 'lit', and an option for the user
# to override.
set(LIT_ARGS_DEFAULT "-sv")
if (MSVC OR XCODE)
set(LIT_ARGS_DEFAULT "${LIT_ARGS_DEFAULT} --no-progress-bar")
endif()
set(LLVM_LIT_ARGS "${LIT_ARGS_DEFAULT}" CACHE STRING "Default options for lit")
# On Win32 hosts, provide an option to specify the path to the GnuWin32 tools.
if( WIN32 AND NOT CYGWIN )
set(LLVM_LIT_TOOLS_DIR "" CACHE PATH "Path to GnuWin32 tools")
endif()
else()
set(LLVM_INCLUDE_TESTS OFF)
endif()
endif()
set( CLANG_BUILT_STANDALONE 1 )
set(BACKEND_PACKAGE_STRING "LLVM ${LLVM_PACKAGE_VERSION}")
else()
set(BACKEND_PACKAGE_STRING "${PACKAGE_STRING}")
endif()
find_package(LibXml2)
if (LIBXML2_FOUND)
set(CLANG_HAVE_LIBXML 1)
endif()
set(CLANG_RESOURCE_DIR "" CACHE STRING
"Relative directory from the Clang binary to its resource files.")
set(C_INCLUDE_DIRS "" CACHE STRING
"Colon separated list of directories clang will search for headers.")
set(GCC_INSTALL_PREFIX "" CACHE PATH "Directory where gcc is installed." )
set(DEFAULT_SYSROOT "" CACHE PATH
"Default <path> to all compiler invocations for --sysroot=<path>." )
set(CLANG_DEFAULT_OPENMP_RUNTIME "libgomp" CACHE STRING
"Default OpenMP runtime used by -fopenmp.")
set(CLANG_VENDOR "" CACHE STRING
"Vendor-specific text for showing with version information.")
if( CLANG_VENDOR )
add_definitions( -DCLANG_VENDOR="${CLANG_VENDOR} " )
endif()
set(CLANG_REPOSITORY_STRING "" CACHE STRING
"Vendor-specific text for showing the repository the source is taken from.")
if(CLANG_REPOSITORY_STRING)
add_definitions(-DCLANG_REPOSITORY_STRING="${CLANG_REPOSITORY_STRING}")
endif()
set(CLANG_VENDOR_UTI "org.llvm.clang" CACHE STRING
"Vendor-specific uti.")
# The libdir suffix must exactly match whatever LLVM's configuration used.
set(CLANG_LIBDIR_SUFFIX "${LLVM_LIBDIR_SUFFIX}")
set(CLANG_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
set(CLANG_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR})
if( CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR AND NOT MSVC_IDE )
message(FATAL_ERROR "In-source builds are not allowed. CMake would overwrite "
"the makefiles distributed with LLVM. Please create a directory and run cmake "
"from there, passing the path to this source directory as the last argument. "
"This process created the file `CMakeCache.txt' and the directory "
"`CMakeFiles'. Please delete them.")
endif()
if( NOT CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR )
file(GLOB_RECURSE
tablegenned_files_on_include_dir
"${CLANG_SOURCE_DIR}/include/clang/*.inc")
if( tablegenned_files_on_include_dir )
message(FATAL_ERROR "Apparently there is a previous in-source build, "
"probably as the result of running `configure' and `make' on "
"${CLANG_SOURCE_DIR}. This may cause problems. The suspicious files are:\n"
"${tablegenned_files_on_include_dir}\nPlease clean the source directory.")
endif()
endif()
# Compute the Clang version from the LLVM version.
string(REGEX MATCH "[0-9]+\\.[0-9]+(\\.[0-9]+)?" CLANG_VERSION
${PACKAGE_VERSION})
message(STATUS "Clang version: ${CLANG_VERSION}")
string(REGEX REPLACE "([0-9]+)\\.[0-9]+(\\.[0-9]+)?" "\\1" CLANG_VERSION_MAJOR
${CLANG_VERSION})
string(REGEX REPLACE "[0-9]+\\.([0-9]+)(\\.[0-9]+)?" "\\1" CLANG_VERSION_MINOR
${CLANG_VERSION})
if (${CLANG_VERSION} MATCHES "[0-9]+\\.[0-9]+\\.[0-9]+")
set(CLANG_HAS_VERSION_PATCHLEVEL 1)
string(REGEX REPLACE "[0-9]+\\.[0-9]+\\.([0-9]+)" "\\1" CLANG_VERSION_PATCHLEVEL
${CLANG_VERSION})
else()
set(CLANG_HAS_VERSION_PATCHLEVEL 0)
endif()
# Configure the Version.inc file.
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/include/clang/Basic/Version.inc.in
${CMAKE_CURRENT_BINARY_DIR}/include/clang/Basic/Version.inc)
# Add appropriate flags for GCC
if (LLVM_COMPILER_IS_GCC_COMPATIBLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-common -Woverloaded-virtual -fno-strict-aliasing")
# Enable -pedantic for Clang even if it's not enabled for LLVM.
if (NOT LLVM_ENABLE_PEDANTIC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic -Wno-long-long")
endif ()
check_cxx_compiler_flag("-Werror -Wnested-anon-types" CXX_SUPPORTS_NO_NESTED_ANON_TYPES_FLAG)
if( CXX_SUPPORTS_NO_NESTED_ANON_TYPES_FLAG )
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-nested-anon-types" )
endif()
endif ()
# Determine HOST_LINK_VERSION on Darwin.
set(HOST_LINK_VERSION)
if (APPLE)
set(LD_V_OUTPUT)
execute_process(
COMMAND sh -c "${CMAKE_LINKER} -v 2>&1 | head -1"
RESULT_VARIABLE HAD_ERROR
OUTPUT_VARIABLE LD_V_OUTPUT
)
if (NOT HAD_ERROR)
if ("${LD_V_OUTPUT}" MATCHES ".*ld64-([0-9.]+).*")
string(REGEX REPLACE ".*ld64-([0-9.]+).*" "\\1" HOST_LINK_VERSION ${LD_V_OUTPUT})
elseif ("${LD_V_OUTPUT}" MATCHES "[^0-9]*([0-9.]+).*")
string(REGEX REPLACE "[^0-9]*([0-9.]+).*" "\\1" HOST_LINK_VERSION ${LD_V_OUTPUT})
endif()
else()
message(FATAL_ERROR "${CMAKE_LINKER} failed with status ${HAD_ERROR}")
endif()
endif()
configure_file(
${CLANG_SOURCE_DIR}/include/clang/Config/config.h.cmake
${CLANG_BINARY_DIR}/include/clang/Config/config.h)
include(CMakeParseArguments)
function(clang_tablegen)
# Syntax:
# clang_tablegen output-file [tablegen-arg ...] SOURCE source-file
# [[TARGET cmake-target-name] [DEPENDS extra-dependency ...]]
#
# Generates a custom command for invoking tblgen as
#
# tblgen source-file -o=output-file tablegen-arg ...
#
# and, if cmake-target-name is provided, creates a custom target for
# executing the custom command depending on output-file. It is
# possible to list more files to depend after DEPENDS.
cmake_parse_arguments(CTG "" "SOURCE;TARGET" "" ${ARGN})
if( NOT CTG_SOURCE )
message(FATAL_ERROR "SOURCE source-file required by clang_tablegen")
endif()
set( LLVM_TARGET_DEFINITIONS ${CTG_SOURCE} )
tablegen(CLANG ${CTG_UNPARSED_ARGUMENTS})
if(CTG_TARGET)
add_public_tablegen_target(${CTG_TARGET})
set_target_properties( ${CTG_TARGET} PROPERTIES FOLDER "Clang tablegenning")
set_property(GLOBAL APPEND PROPERTY CLANG_TABLEGEN_TARGETS ${CTG_TARGET})
endif()
endfunction(clang_tablegen)
macro(set_clang_windows_version_resource_properties name)
if(DEFINED windows_resource_file)
set_windows_version_resource_properties(${name} ${windows_resource_file}
VERSION_MAJOR ${CLANG_VERSION_MAJOR}
VERSION_MINOR ${CLANG_VERSION_MINOR}
VERSION_PATCHLEVEL ${CLANG_VERSION_PATCHLEVEL}
VERSION_STRING "${CLANG_VERSION} (${BACKEND_PACKAGE_STRING})"
PRODUCT_NAME "clang")
endif()
endmacro()
macro(add_clang_library name)
cmake_parse_arguments(ARG
""
""
"ADDITIONAL_HEADERS"
${ARGN})
set(srcs)
if(MSVC_IDE OR XCODE)
# Add public headers
file(RELATIVE_PATH lib_path
${CLANG_SOURCE_DIR}/lib/
${CMAKE_CURRENT_SOURCE_DIR}
)
if(NOT lib_path MATCHES "^[.][.]")
file( GLOB_RECURSE headers
${CLANG_SOURCE_DIR}/include/clang/${lib_path}/*.h
${CLANG_SOURCE_DIR}/include/clang/${lib_path}/*.def
)
set_source_files_properties(${headers} PROPERTIES HEADER_FILE_ONLY ON)
file( GLOB_RECURSE tds
${CLANG_SOURCE_DIR}/include/clang/${lib_path}/*.td
)
source_group("TableGen descriptions" FILES ${tds})
set_source_files_properties(${tds}} PROPERTIES HEADER_FILE_ONLY ON)
if(headers OR tds)
set(srcs ${headers} ${tds})
endif()
endif()
endif(MSVC_IDE OR XCODE)
if(srcs OR ARG_ADDITIONAL_HEADERS)
set(srcs
ADDITIONAL_HEADERS
${srcs}
${ARG_ADDITIONAL_HEADERS} # It may contain unparsed unknown args.
)
endif()
llvm_add_library(${name} ${ARG_UNPARSED_ARGUMENTS} ${srcs})
if(TARGET ${name})
target_link_libraries(${name} ${cmake_2_8_12_INTERFACE} ${LLVM_COMMON_LIBS})
if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY OR ${name} STREQUAL "libclang")
install(TARGETS ${name}
EXPORT ClangTargets
LIBRARY DESTINATION lib${LLVM_LIBDIR_SUFFIX}
ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX}
RUNTIME DESTINATION bin)
endif()
set_property(GLOBAL APPEND PROPERTY CLANG_EXPORTS ${name})
else()
# Add empty "phony" target
add_custom_target(${name})
endif()
set_target_properties(${name} PROPERTIES FOLDER "Clang libraries")
set_clang_windows_version_resource_properties(${name})
endmacro(add_clang_library)
macro(add_clang_executable name)
add_llvm_executable( ${name} ${ARGN} )
set_target_properties(${name} PROPERTIES FOLDER "Clang executables")
set_clang_windows_version_resource_properties(${name})
endmacro(add_clang_executable)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
include_directories(BEFORE
${CMAKE_CURRENT_BINARY_DIR}/include
${CMAKE_CURRENT_SOURCE_DIR}/include
)
if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
install(DIRECTORY include/clang include/clang-c
DESTINATION include
FILES_MATCHING
PATTERN "*.def"
PATTERN "*.h"
PATTERN "config.h" EXCLUDE
PATTERN ".svn" EXCLUDE
)
install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/include/clang
DESTINATION include
FILES_MATCHING
PATTERN "CMakeFiles" EXCLUDE
PATTERN "*.inc"
PATTERN "*.h"
)
endif()
install(DIRECTORY include/clang-c
DESTINATION include
FILES_MATCHING
PATTERN "*.h"
PATTERN ".svn" EXCLUDE
)
add_definitions( -D_GNU_SOURCE )
option(CLANG_ENABLE_ARCMT "Build ARCMT." ON)
if (CLANG_ENABLE_ARCMT)
set(ENABLE_CLANG_ARCMT "1")
else()
set(ENABLE_CLANG_ARCMT "0")
endif()
option(CLANG_ENABLE_STATIC_ANALYZER "Build static analyzer." ON)
if (CLANG_ENABLE_STATIC_ANALYZER)
set(ENABLE_CLANG_STATIC_ANALYZER "1")
else()
set(ENABLE_CLANG_STATIC_ANALYZER "0")
endif()
if (NOT CLANG_ENABLE_STATIC_ANALYZER AND CLANG_ENABLE_ARCMT)
message(FATAL_ERROR "Cannot disable static analyzer while enabling ARCMT")
endif()
if(CLANG_ENABLE_ARCMT)
add_definitions(-DCLANG_ENABLE_ARCMT)
add_definitions(-DCLANG_ENABLE_OBJC_REWRITER)
endif()
if(CLANG_ENABLE_STATIC_ANALYZER)
add_definitions(-DCLANG_ENABLE_STATIC_ANALYZER)
endif()
# Clang version information
set(CLANG_EXECUTABLE_VERSION
"${CLANG_VERSION_MAJOR}.${CLANG_VERSION_MINOR}" CACHE STRING
"Version number that will be placed into the clang executable, in the form XX.YY")
set(LIBCLANG_LIBRARY_VERSION
"${CLANG_VERSION_MAJOR}.${CLANG_VERSION_MINOR}" CACHE STRING
"Version number that will be placed into the libclang library , in the form XX.YY")
mark_as_advanced(CLANG_EXECUTABLE_VERSION LIBCLANG_LIBRARY_VERSION)
add_subdirectory(utils/TableGen)
add_subdirectory(include)
# All targets below may depend on all tablegen'd files.
get_property(CLANG_TABLEGEN_TARGETS GLOBAL PROPERTY CLANG_TABLEGEN_TARGETS)
list(APPEND LLVM_COMMON_DEPENDS ${CLANG_TABLEGEN_TARGETS})
add_subdirectory(lib)
add_subdirectory(tools)
add_subdirectory(runtime)
option(CLANG_BUILD_EXAMPLES "Build CLANG example programs by default." OFF)
if (CLANG_BUILD_EXAMPLES)
set(ENABLE_CLANG_EXAMPLES "1")
else()
set(ENABLE_CLANG_EXAMPLES "0")
endif()
# add_subdirectory(examples) # HLSL Change
option(CLANG_INCLUDE_TESTS
"Generate build targets for the Clang unit tests."
${LLVM_INCLUDE_TESTS})
if( CLANG_INCLUDE_TESTS OR HLSL_INCLUDE_TESTS ) # HLSL Change
if(HLSL_INCLUDE_TESTS OR EXISTS ${LLVM_MAIN_SRC_DIR}/utils/unittest/googletest/include/gtest/gtest.h) # HLSL Change - no need for gtest
add_subdirectory(unittests)
list(APPEND CLANG_TEST_DEPS ClangUnitTests)
list(APPEND CLANG_TEST_PARAMS
clang_unit_site_config=${CMAKE_CURRENT_BINARY_DIR}/test/Unit/lit.site.cfg
)
endif()
if (CLANG_INCLUDE_TESTS) # HLSL Change - respect variable for clang tests
add_subdirectory(test)
endif()
if(CLANG_BUILT_STANDALONE)
# Add a global check rule now that all subdirectories have been traversed
# and we know the total set of lit testsuites.
get_property(LLVM_LIT_TESTSUITES GLOBAL PROPERTY LLVM_LIT_TESTSUITES)
get_property(LLVM_LIT_PARAMS GLOBAL PROPERTY LLVM_LIT_PARAMS)
get_property(LLVM_LIT_DEPENDS GLOBAL PROPERTY LLVM_LIT_DEPENDS)
get_property(LLVM_LIT_EXTRA_ARGS GLOBAL PROPERTY LLVM_LIT_EXTRA_ARGS)
add_lit_target(check-all
"Running all regression tests"
${LLVM_LIT_TESTSUITES}
PARAMS ${LLVM_LIT_PARAMS}
DEPENDS ${LLVM_LIT_DEPENDS}
ARGS ${LLVM_LIT_EXTRA_ARGS}
)
endif()
endif()
option(CLANG_INCLUDE_DOCS "Generate build targets for the Clang docs."
${LLVM_INCLUDE_DOCS})
if( CLANG_INCLUDE_DOCS )
add_subdirectory(docs)
endif()
set(CLANG_ORDER_FILE "" CACHE FILEPATH
"Order file to use when compiling clang in order to improve startup time.")
if (CLANG_BUILT_STANDALONE)
# Generate a list of CMake library targets so that other CMake projects can
# link against them. LLVM calls its version of this file LLVMExports.cmake, but
# the usual CMake convention seems to be ${Project}Targets.cmake.
set(CLANG_INSTALL_PACKAGE_DIR share/clang/cmake)
set(clang_cmake_builddir "${CMAKE_BINARY_DIR}/${CLANG_INSTALL_PACKAGE_DIR}")
get_property(CLANG_EXPORTS GLOBAL PROPERTY CLANG_EXPORTS)
export(TARGETS ${CLANG_EXPORTS} FILE ${clang_cmake_builddir}/ClangTargets.cmake)
# Install a <prefix>/share/clang/cmake/ClangConfig.cmake file so that
# find_package(Clang) works. Install the target list with it.
install(EXPORT ClangTargets DESTINATION ${CLANG_INSTALL_PACKAGE_DIR})
install(FILES
${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules/ClangConfig.cmake
DESTINATION share/clang/cmake)
# Also copy ClangConfig.cmake to the build directory so that dependent projects
# can build against a build directory of Clang more easily.
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules/ClangConfig.cmake
${CLANG_BINARY_DIR}/share/clang/cmake/ClangConfig.cmake
COPYONLY)
endif ()
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/clang/ModuleInfo.txt | # This file provides information for llvm-top
DepModule: llvm
ConfigCmd:
ConfigTest:
BuildCmd:
|
0 | repos/DirectXShaderCompiler/tools | repos/DirectXShaderCompiler/tools/clang/README.txt | //===----------------------------------------------------------------------===//
// C Language Family Front-end
//===----------------------------------------------------------------------===//
Welcome to Clang. This is a compiler front-end for the C family of languages
(C, C++, Objective-C, and Objective-C++) which is built as part of the LLVM
compiler infrastructure project.
Unlike many other compiler frontends, Clang is useful for a number of things
beyond just compiling code: we intend for Clang to be host to a number of
different source-level tools. One example of this is the Clang Static Analyzer.
If you're interested in more (including how to build Clang) it is best to read
the relevant web sites. Here are some pointers:
Information on Clang: http://clang.llvm.org/
Building and using Clang: http://clang.llvm.org/get_started.html
Clang Static Analyzer: http://clang-analyzer.llvm.org/
Information on the LLVM project: http://llvm.org/
If you have questions or comments about Clang, a great place to discuss them is
on the Clang development mailing list:
http://lists.llvm.org/mailman/listinfo/cfe-dev
If you find a bug in Clang, please file it in the LLVM bug tracker:
http://llvm.org/bugs/
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings | repos/DirectXShaderCompiler/tools/clang/bindings/python/README.txt | //===----------------------------------------------------------------------===//
// Clang Python Bindings
//===----------------------------------------------------------------------===//
This directory implements Python bindings for Clang.
You may need to alter LD_LIBRARY_PATH so that the Clang library can be
found. The unit tests are designed to be run with 'nosetests'. For example:
--
$ env PYTHONPATH=$(echo ~/llvm/tools/clang/bindings/python/) \
LD_LIBRARY_PATH=$(llvm-config --libdir) \
nosetests -v
tests.cindex.test_index.test_create ... ok
...
OK
--
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/test_diagnostics.py | from clang.cindex import *
from .util import get_tu
# FIXME: We need support for invalid translation units to test better.
def test_diagnostic_warning():
tu = get_tu('int f0() {}\n')
assert len(tu.diagnostics) == 1
assert tu.diagnostics[0].severity == Diagnostic.Warning
assert tu.diagnostics[0].location.line == 1
assert tu.diagnostics[0].location.column == 11
assert (tu.diagnostics[0].spelling ==
'control reaches end of non-void function')
def test_diagnostic_note():
# FIXME: We aren't getting notes here for some reason.
tu = get_tu('#define A x\nvoid *A = 1;\n')
assert len(tu.diagnostics) == 1
assert tu.diagnostics[0].severity == Diagnostic.Warning
assert tu.diagnostics[0].location.line == 2
assert tu.diagnostics[0].location.column == 7
assert 'incompatible' in tu.diagnostics[0].spelling
# assert tu.diagnostics[1].severity == Diagnostic.Note
# assert tu.diagnostics[1].location.line == 1
# assert tu.diagnostics[1].location.column == 11
# assert tu.diagnostics[1].spelling == 'instantiated from'
def test_diagnostic_fixit():
tu = get_tu('struct { int f0; } x = { f0 : 1 };')
assert len(tu.diagnostics) == 1
assert tu.diagnostics[0].severity == Diagnostic.Warning
assert tu.diagnostics[0].location.line == 1
assert tu.diagnostics[0].location.column == 26
assert tu.diagnostics[0].spelling.startswith('use of GNU old-style')
assert len(tu.diagnostics[0].fixits) == 1
assert tu.diagnostics[0].fixits[0].range.start.line == 1
assert tu.diagnostics[0].fixits[0].range.start.column == 26
assert tu.diagnostics[0].fixits[0].range.end.line == 1
assert tu.diagnostics[0].fixits[0].range.end.column == 30
assert tu.diagnostics[0].fixits[0].value == '.f0 = '
def test_diagnostic_range():
tu = get_tu('void f() { int i = "a" + 1; }')
assert len(tu.diagnostics) == 1
assert tu.diagnostics[0].severity == Diagnostic.Warning
assert tu.diagnostics[0].location.line == 1
assert tu.diagnostics[0].location.column == 16
assert tu.diagnostics[0].spelling.startswith('incompatible pointer to')
assert len(tu.diagnostics[0].fixits) == 0
assert len(tu.diagnostics[0].ranges) == 1
assert tu.diagnostics[0].ranges[0].start.line == 1
assert tu.diagnostics[0].ranges[0].start.column == 20
assert tu.diagnostics[0].ranges[0].end.line == 1
assert tu.diagnostics[0].ranges[0].end.column == 27
try:
tu.diagnostics[0].ranges[1].start.line
except IndexError:
assert True
else:
assert False
def test_diagnostic_category():
"""Ensure that category properties work."""
tu = get_tu('int f(int i) { return 7; }', all_warnings=True)
assert len(tu.diagnostics) == 1
d = tu.diagnostics[0]
assert d.severity == Diagnostic.Warning
assert d.location.line == 1
assert d.location.column == 11
assert d.category_number == 2
assert d.category_name == 'Semantic Issue'
def test_diagnostic_option():
"""Ensure that category option properties work."""
tu = get_tu('int f(int i) { return 7; }', all_warnings=True)
assert len(tu.diagnostics) == 1
d = tu.diagnostics[0]
assert d.option == '-Wunused-parameter'
assert d.disable_option == '-Wno-unused-parameter'
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/test_location.py | from clang.cindex import Cursor
from clang.cindex import File
from clang.cindex import SourceLocation
from clang.cindex import SourceRange
from .util import get_cursor
from .util import get_tu
baseInput="int one;\nint two;\n"
def assert_location(loc, line, column, offset):
assert loc.line == line
assert loc.column == column
assert loc.offset == offset
def test_location():
tu = get_tu(baseInput)
one = get_cursor(tu, 'one')
two = get_cursor(tu, 'two')
assert one is not None
assert two is not None
assert_location(one.location,line=1,column=5,offset=4)
assert_location(two.location,line=2,column=5,offset=13)
# adding a linebreak at top should keep columns same
tu = get_tu('\n' + baseInput)
one = get_cursor(tu, 'one')
two = get_cursor(tu, 'two')
assert one is not None
assert two is not None
assert_location(one.location,line=2,column=5,offset=5)
assert_location(two.location,line=3,column=5,offset=14)
# adding a space should affect column on first line only
tu = get_tu(' ' + baseInput)
one = get_cursor(tu, 'one')
two = get_cursor(tu, 'two')
assert_location(one.location,line=1,column=6,offset=5)
assert_location(two.location,line=2,column=5,offset=14)
# define the expected location ourselves and see if it matches
# the returned location
tu = get_tu(baseInput)
file = File.from_name(tu, 't.c')
location = SourceLocation.from_position(tu, file, 1, 5)
cursor = Cursor.from_location(tu, location)
one = get_cursor(tu, 'one')
assert one is not None
assert one == cursor
# Ensure locations referring to the same entity are equivalent.
location2 = SourceLocation.from_position(tu, file, 1, 5)
assert location == location2
location3 = SourceLocation.from_position(tu, file, 1, 4)
assert location2 != location3
offset_location = SourceLocation.from_offset(tu, file, 5)
cursor = Cursor.from_location(tu, offset_location)
verified = False
for n in [n for n in tu.cursor.get_children() if n.spelling == 'one']:
assert n == cursor
verified = True
assert verified
def test_extent():
tu = get_tu(baseInput)
one = get_cursor(tu, 'one')
two = get_cursor(tu, 'two')
assert_location(one.extent.start,line=1,column=1,offset=0)
assert_location(one.extent.end,line=1,column=8,offset=7)
assert baseInput[one.extent.start.offset:one.extent.end.offset] == "int one"
assert_location(two.extent.start,line=2,column=1,offset=9)
assert_location(two.extent.end,line=2,column=8,offset=16)
assert baseInput[two.extent.start.offset:two.extent.end.offset] == "int two"
file = File.from_name(tu, 't.c')
location1 = SourceLocation.from_position(tu, file, 1, 1)
location2 = SourceLocation.from_position(tu, file, 1, 8)
range1 = SourceRange.from_locations(location1, location2)
range2 = SourceRange.from_locations(location1, location2)
assert range1 == range2
location3 = SourceLocation.from_position(tu, file, 1, 6)
range3 = SourceRange.from_locations(location1, location3)
assert range1 != range3
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/test_tokens.py | from clang.cindex import CursorKind
from clang.cindex import Index
from clang.cindex import SourceLocation
from clang.cindex import SourceRange
from clang.cindex import TokenKind
from nose.tools import eq_
from nose.tools import ok_
from .util import get_tu
def test_token_to_cursor():
"""Ensure we can obtain a Cursor from a Token instance."""
tu = get_tu('int i = 5;')
r = tu.get_extent('t.c', (0, 9))
tokens = list(tu.get_tokens(extent=r))
assert len(tokens) == 5
assert tokens[1].spelling == 'i'
assert tokens[1].kind == TokenKind.IDENTIFIER
cursor = tokens[1].cursor
assert cursor.kind == CursorKind.VAR_DECL
assert tokens[1].cursor == tokens[2].cursor
def test_token_location():
"""Ensure Token.location works."""
tu = get_tu('int foo = 10;')
r = tu.get_extent('t.c', (0, 11))
tokens = list(tu.get_tokens(extent=r))
eq_(len(tokens), 4)
loc = tokens[1].location
ok_(isinstance(loc, SourceLocation))
eq_(loc.line, 1)
eq_(loc.column, 5)
eq_(loc.offset, 4)
def test_token_extent():
"""Ensure Token.extent works."""
tu = get_tu('int foo = 10;')
r = tu.get_extent('t.c', (0, 11))
tokens = list(tu.get_tokens(extent=r))
eq_(len(tokens), 4)
extent = tokens[1].extent
ok_(isinstance(extent, SourceRange))
eq_(extent.start.offset, 4)
eq_(extent.end.offset, 7)
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/test_index.py | from clang.cindex import *
import os
kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS')
def test_create():
index = Index.create()
# FIXME: test Index.read
def test_parse():
index = Index.create()
assert isinstance(index, Index)
tu = index.parse(os.path.join(kInputsDir, 'hello.cpp'))
assert isinstance(tu, TranslationUnit)
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/test_token_kind.py | from clang.cindex import TokenKind
from nose.tools import eq_
from nose.tools import ok_
from nose.tools import raises
def test_constructor():
"""Ensure TokenKind constructor works as expected."""
t = TokenKind(5, 'foo')
eq_(t.value, 5)
eq_(t.name, 'foo')
@raises(ValueError)
def test_bad_register():
"""Ensure a duplicate value is rejected for registration."""
TokenKind.register(2, 'foo')
@raises(ValueError)
def test_unknown_value():
"""Ensure trying to fetch an unknown value raises."""
TokenKind.from_value(-1)
def test_registration():
"""Ensure that items registered appear as class attributes."""
ok_(hasattr(TokenKind, 'LITERAL'))
literal = TokenKind.LITERAL
ok_(isinstance(literal, TokenKind))
def test_from_value():
"""Ensure registered values can be obtained from from_value()."""
t = TokenKind.from_value(3)
ok_(isinstance(t, TokenKind))
eq_(t, TokenKind.LITERAL)
def test_repr():
"""Ensure repr() works."""
r = repr(TokenKind.LITERAL)
eq_(r, 'TokenKind.LITERAL')
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/test_comment.py | from clang.cindex import TranslationUnit
from tests.cindex.util import get_cursor
def test_comment():
files = [('fake.c', """
/// Aaa.
int test1;
/// Bbb.
/// x
void test2(void);
void f() {
}
""")]
# make a comment-aware TU
tu = TranslationUnit.from_source('fake.c', ['-std=c99'], unsaved_files=files,
options=TranslationUnit.PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION)
test1 = get_cursor(tu, 'test1')
assert test1 is not None, "Could not find test1."
assert test1.type.is_pod()
raw = test1.raw_comment
brief = test1.brief_comment
assert raw == """/// Aaa."""
assert brief == """Aaa."""
test2 = get_cursor(tu, 'test2')
raw = test2.raw_comment
brief = test2.brief_comment
assert raw == """/// Bbb.\n/// x"""
assert brief == """Bbb. x"""
f = get_cursor(tu, 'f')
raw = f.raw_comment
brief = f.brief_comment
assert raw is None
assert brief is None
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/test_code_completion.py | from clang.cindex import TranslationUnit
def check_completion_results(cr, expected):
assert cr is not None
assert len(cr.diagnostics) == 0
completions = [str(c) for c in cr.results]
for c in expected:
assert c in completions
def test_code_complete():
files = [('fake.c', """
/// Aaa.
int test1;
/// Bbb.
void test2(void);
void f() {
}
""")]
tu = TranslationUnit.from_source('fake.c', ['-std=c99'], unsaved_files=files,
options=TranslationUnit.PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION)
cr = tu.codeComplete('fake.c', 9, 1, unsaved_files=files, include_brief_comments=True)
expected = [
"{'int', ResultType} | {'test1', TypedText} || Priority: 50 || Availability: Available || Brief comment: Aaa.",
"{'void', ResultType} | {'test2', TypedText} | {'(', LeftParen} | {')', RightParen} || Priority: 50 || Availability: Available || Brief comment: Bbb.",
"{'return', TypedText} || Priority: 40 || Availability: Available || Brief comment: None"
]
check_completion_results(cr, expected)
def test_code_complete_availability():
files = [('fake.cpp', """
class P {
protected:
int member;
};
class Q : public P {
public:
using P::member;
};
void f(P x, Q y) {
x.; // member is inaccessible
y.; // member is accessible
}
""")]
tu = TranslationUnit.from_source('fake.cpp', ['-std=c++98'], unsaved_files=files)
cr = tu.codeComplete('fake.cpp', 12, 5, unsaved_files=files)
expected = [
"{'const', TypedText} || Priority: 40 || Availability: Available || Brief comment: None",
"{'volatile', TypedText} || Priority: 40 || Availability: Available || Brief comment: None",
"{'operator', TypedText} || Priority: 40 || Availability: Available || Brief comment: None",
"{'P', TypedText} | {'::', Text} || Priority: 75 || Availability: Available || Brief comment: None",
"{'Q', TypedText} | {'::', Text} || Priority: 75 || Availability: Available || Brief comment: None"
]
check_completion_results(cr, expected)
cr = tu.codeComplete('fake.cpp', 13, 5, unsaved_files=files)
expected = [
"{'P', TypedText} | {'::', Text} || Priority: 75 || Availability: Available || Brief comment: None",
"{'P &', ResultType} | {'operator=', TypedText} | {'(', LeftParen} | {'const P &', Placeholder} | {')', RightParen} || Priority: 34 || Availability: Available || Brief comment: None",
"{'int', ResultType} | {'member', TypedText} || Priority: 35 || Availability: NotAccessible || Brief comment: None",
"{'void', ResultType} | {'~P', TypedText} | {'(', LeftParen} | {')', RightParen} || Priority: 34 || Availability: Available || Brief comment: None"
]
check_completion_results(cr, expected)
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/test_access_specifiers.py |
from clang.cindex import AccessSpecifier
from clang.cindex import Cursor
from clang.cindex import TranslationUnit
from .util import get_cursor
from .util import get_tu
def test_access_specifiers():
"""Ensure that C++ access specifiers are available on cursors"""
tu = get_tu("""
class test_class {
public:
void public_member_function();
protected:
void protected_member_function();
private:
void private_member_function();
};
""", lang = 'cpp')
test_class = get_cursor(tu, "test_class")
assert test_class.access_specifier == AccessSpecifier.INVALID;
public = get_cursor(tu.cursor, "public_member_function")
assert public.access_specifier == AccessSpecifier.PUBLIC
protected = get_cursor(tu.cursor, "protected_member_function")
assert protected.access_specifier == AccessSpecifier.PROTECTED
private = get_cursor(tu.cursor, "private_member_function")
assert private.access_specifier == AccessSpecifier.PRIVATE
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/test_cdb.py | from clang.cindex import CompilationDatabase
from clang.cindex import CompilationDatabaseError
from clang.cindex import CompileCommands
from clang.cindex import CompileCommand
import os
import gc
kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS')
def test_create_fail():
"""Check we fail loading a database with an assertion"""
path = os.path.dirname(__file__)
try:
cdb = CompilationDatabase.fromDirectory(path)
except CompilationDatabaseError as e:
assert e.cdb_error == CompilationDatabaseError.ERROR_CANNOTLOADDATABASE
else:
assert False
def test_create():
"""Check we can load a compilation database"""
cdb = CompilationDatabase.fromDirectory(kInputsDir)
def test_lookup_fail():
"""Check file lookup failure"""
cdb = CompilationDatabase.fromDirectory(kInputsDir)
assert cdb.getCompileCommands('file_do_not_exist.cpp') == None
def test_lookup_succeed():
"""Check we get some results if the file exists in the db"""
cdb = CompilationDatabase.fromDirectory(kInputsDir)
cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp')
assert len(cmds) != 0
def test_all_compilecommand():
"""Check we get all results from the db"""
cdb = CompilationDatabase.fromDirectory(kInputsDir)
cmds = cdb.getAllCompileCommands()
assert len(cmds) == 3
expected = [
{ 'wd': '/home/john.doe/MyProjectA',
'line': ['clang++', '-o', 'project2.o', '-c',
'/home/john.doe/MyProject/project2.cpp']},
{ 'wd': '/home/john.doe/MyProjectB',
'line': ['clang++', '-DFEATURE=1', '-o', 'project2-feature.o', '-c',
'/home/john.doe/MyProject/project2.cpp']},
{ 'wd': '/home/john.doe/MyProject',
'line': ['clang++', '-o', 'project.o', '-c',
'/home/john.doe/MyProject/project.cpp']}
]
for i in range(len(cmds)):
assert cmds[i].directory == expected[i]['wd']
for arg, exp in zip(cmds[i].arguments, expected[i]['line']):
assert arg == exp
def test_1_compilecommand():
"""Check file with single compile command"""
cdb = CompilationDatabase.fromDirectory(kInputsDir)
cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp')
assert len(cmds) == 1
assert cmds[0].directory == '/home/john.doe/MyProject'
expected = [ 'clang++', '-o', 'project.o', '-c',
'/home/john.doe/MyProject/project.cpp']
for arg, exp in zip(cmds[0].arguments, expected):
assert arg == exp
def test_2_compilecommand():
"""Check file with 2 compile commands"""
cdb = CompilationDatabase.fromDirectory(kInputsDir)
cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project2.cpp')
assert len(cmds) == 2
expected = [
{ 'wd': '/home/john.doe/MyProjectA',
'line': ['clang++', '-o', 'project2.o', '-c',
'/home/john.doe/MyProject/project2.cpp']},
{ 'wd': '/home/john.doe/MyProjectB',
'line': ['clang++', '-DFEATURE=1', '-o', 'project2-feature.o', '-c',
'/home/john.doe/MyProject/project2.cpp']}
]
for i in range(len(cmds)):
assert cmds[i].directory == expected[i]['wd']
for arg, exp in zip(cmds[i].arguments, expected[i]['line']):
assert arg == exp
def test_compilecommand_iterator_stops():
"""Check that iterator stops after the correct number of elements"""
cdb = CompilationDatabase.fromDirectory(kInputsDir)
count = 0
for cmd in cdb.getCompileCommands('/home/john.doe/MyProject/project2.cpp'):
count += 1
assert count <= 2
def test_compilationDB_references():
"""Ensure CompilationsCommands are independent of the database"""
cdb = CompilationDatabase.fromDirectory(kInputsDir)
cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp')
del cdb
gc.collect()
workingdir = cmds[0].directory
def test_compilationCommands_references():
"""Ensure CompilationsCommand keeps a reference to CompilationCommands"""
cdb = CompilationDatabase.fromDirectory(kInputsDir)
cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp')
del cdb
cmd0 = cmds[0]
del cmds
gc.collect()
workingdir = cmd0.directory
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/test_cursor_kind.py | from clang.cindex import CursorKind
def test_name():
assert CursorKind.UNEXPOSED_DECL.name is 'UNEXPOSED_DECL'
def test_get_all_kinds():
kinds = CursorKind.get_all_kinds()
assert CursorKind.UNEXPOSED_DECL in kinds
assert CursorKind.TRANSLATION_UNIT in kinds
assert CursorKind.VARIABLE_REF in kinds
assert CursorKind.LAMBDA_EXPR in kinds
assert CursorKind.OBJ_BOOL_LITERAL_EXPR in kinds
assert CursorKind.OBJ_SELF_EXPR in kinds
assert CursorKind.MS_ASM_STMT in kinds
assert CursorKind.MODULE_IMPORT_DECL in kinds
def test_kind_groups():
"""Check that every kind classifies to exactly one group."""
assert CursorKind.UNEXPOSED_DECL.is_declaration()
assert CursorKind.TYPE_REF.is_reference()
assert CursorKind.DECL_REF_EXPR.is_expression()
assert CursorKind.UNEXPOSED_STMT.is_statement()
assert CursorKind.INVALID_FILE.is_invalid()
assert CursorKind.TRANSLATION_UNIT.is_translation_unit()
assert not CursorKind.TYPE_REF.is_translation_unit()
assert CursorKind.PREPROCESSING_DIRECTIVE.is_preprocessing()
assert not CursorKind.TYPE_REF.is_preprocessing()
assert CursorKind.UNEXPOSED_DECL.is_unexposed()
assert not CursorKind.TYPE_REF.is_unexposed()
for k in CursorKind.get_all_kinds():
group = [n for n in ('is_declaration', 'is_reference', 'is_expression',
'is_statement', 'is_invalid', 'is_attribute')
if getattr(k, n)()]
if k in ( CursorKind.TRANSLATION_UNIT,
CursorKind.MACRO_DEFINITION,
CursorKind.MACRO_INSTANTIATION,
CursorKind.INCLUSION_DIRECTIVE,
CursorKind.PREPROCESSING_DIRECTIVE):
assert len(group) == 0
else:
assert len(group) == 1
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/test_cursor.py | import ctypes
import gc
from clang.cindex import CursorKind
from clang.cindex import TemplateArgumentKind
from clang.cindex import TranslationUnit
from clang.cindex import TypeKind
from .util import get_cursor
from .util import get_cursors
from .util import get_tu
kInput = """\
struct s0 {
int a;
int b;
};
struct s1;
void f0(int a0, int a1) {
int l0, l1;
if (a0)
return;
for (;;) {
break;
}
}
"""
def test_get_children():
tu = get_tu(kInput)
it = tu.cursor.get_children()
tu_nodes = list(it)
assert len(tu_nodes) == 3
for cursor in tu_nodes:
assert cursor.translation_unit is not None
assert tu_nodes[0] != tu_nodes[1]
assert tu_nodes[0].kind == CursorKind.STRUCT_DECL
assert tu_nodes[0].spelling == 's0'
assert tu_nodes[0].is_definition() == True
assert tu_nodes[0].location.file.name == 't.c'
assert tu_nodes[0].location.line == 1
assert tu_nodes[0].location.column == 8
assert tu_nodes[0].hash > 0
assert tu_nodes[0].translation_unit is not None
s0_nodes = list(tu_nodes[0].get_children())
assert len(s0_nodes) == 2
assert s0_nodes[0].kind == CursorKind.FIELD_DECL
assert s0_nodes[0].spelling == 'a'
assert s0_nodes[0].type.kind == TypeKind.INT
assert s0_nodes[1].kind == CursorKind.FIELD_DECL
assert s0_nodes[1].spelling == 'b'
assert s0_nodes[1].type.kind == TypeKind.INT
assert tu_nodes[1].kind == CursorKind.STRUCT_DECL
assert tu_nodes[1].spelling == 's1'
assert tu_nodes[1].displayname == 's1'
assert tu_nodes[1].is_definition() == False
assert tu_nodes[2].kind == CursorKind.FUNCTION_DECL
assert tu_nodes[2].spelling == 'f0'
assert tu_nodes[2].displayname == 'f0(int, int)'
assert tu_nodes[2].is_definition() == True
def test_references():
"""Ensure that references to TranslationUnit are kept."""
tu = get_tu('int x;')
cursors = list(tu.cursor.get_children())
assert len(cursors) > 0
cursor = cursors[0]
assert isinstance(cursor.translation_unit, TranslationUnit)
# Delete reference to TU and perform a full GC.
del tu
gc.collect()
assert isinstance(cursor.translation_unit, TranslationUnit)
# If the TU was destroyed, this should cause a segfault.
parent = cursor.semantic_parent
def test_canonical():
source = 'struct X; struct X; struct X { int member; };'
tu = get_tu(source)
cursors = []
for cursor in tu.cursor.get_children():
if cursor.spelling == 'X':
cursors.append(cursor)
assert len(cursors) == 3
assert cursors[1].canonical == cursors[2].canonical
def test_is_static_method():
"""Ensure Cursor.is_static_method works."""
source = 'class X { static void foo(); void bar(); };'
tu = get_tu(source, lang='cpp')
cls = get_cursor(tu, 'X')
foo = get_cursor(tu, 'foo')
bar = get_cursor(tu, 'bar')
assert cls is not None
assert foo is not None
assert bar is not None
assert foo.is_static_method()
assert not bar.is_static_method()
def test_underlying_type():
tu = get_tu('typedef int foo;')
typedef = get_cursor(tu, 'foo')
assert typedef is not None
assert typedef.kind.is_declaration()
underlying = typedef.underlying_typedef_type
assert underlying.kind == TypeKind.INT
kParentTest = """\
class C {
void f();
}
void C::f() { }
"""
def test_semantic_parent():
tu = get_tu(kParentTest, 'cpp')
curs = get_cursors(tu, 'f')
decl = get_cursor(tu, 'C')
assert(len(curs) == 2)
assert(curs[0].semantic_parent == curs[1].semantic_parent)
assert(curs[0].semantic_parent == decl)
def test_lexical_parent():
tu = get_tu(kParentTest, 'cpp')
curs = get_cursors(tu, 'f')
decl = get_cursor(tu, 'C')
assert(len(curs) == 2)
assert(curs[0].lexical_parent != curs[1].lexical_parent)
assert(curs[0].lexical_parent == decl)
assert(curs[1].lexical_parent == tu.cursor)
def test_enum_type():
tu = get_tu('enum TEST { FOO=1, BAR=2 };')
enum = get_cursor(tu, 'TEST')
assert enum is not None
assert enum.kind == CursorKind.ENUM_DECL
enum_type = enum.enum_type
assert enum_type.kind == TypeKind.UINT
def test_enum_type_cpp():
tu = get_tu('enum TEST : long long { FOO=1, BAR=2 };', lang="cpp")
enum = get_cursor(tu, 'TEST')
assert enum is not None
assert enum.kind == CursorKind.ENUM_DECL
assert enum.enum_type.kind == TypeKind.LONGLONG
def test_objc_type_encoding():
tu = get_tu('int i;', lang='objc')
i = get_cursor(tu, 'i')
assert i is not None
assert i.objc_type_encoding == 'i'
def test_enum_values():
tu = get_tu('enum TEST { SPAM=1, EGG, HAM = EGG * 20};')
enum = get_cursor(tu, 'TEST')
assert enum is not None
assert enum.kind == CursorKind.ENUM_DECL
enum_constants = list(enum.get_children())
assert len(enum_constants) == 3
spam, egg, ham = enum_constants
assert spam.kind == CursorKind.ENUM_CONSTANT_DECL
assert spam.enum_value == 1
assert egg.kind == CursorKind.ENUM_CONSTANT_DECL
assert egg.enum_value == 2
assert ham.kind == CursorKind.ENUM_CONSTANT_DECL
assert ham.enum_value == 40
def test_enum_values_cpp():
tu = get_tu('enum TEST : long long { SPAM = -1, HAM = 0x10000000000};', lang="cpp")
enum = get_cursor(tu, 'TEST')
assert enum is not None
assert enum.kind == CursorKind.ENUM_DECL
enum_constants = list(enum.get_children())
assert len(enum_constants) == 2
spam, ham = enum_constants
assert spam.kind == CursorKind.ENUM_CONSTANT_DECL
assert spam.enum_value == -1
assert ham.kind == CursorKind.ENUM_CONSTANT_DECL
assert ham.enum_value == 0x10000000000
def test_annotation_attribute():
tu = get_tu('int foo (void) __attribute__ ((annotate("here be annotation attribute")));')
foo = get_cursor(tu, 'foo')
assert foo is not None
for c in foo.get_children():
if c.kind == CursorKind.ANNOTATE_ATTR:
assert c.displayname == "here be annotation attribute"
break
else:
assert False, "Couldn't find annotation"
def test_result_type():
tu = get_tu('int foo();')
foo = get_cursor(tu, 'foo')
assert foo is not None
t = foo.result_type
assert t.kind == TypeKind.INT
def test_get_tokens():
"""Ensure we can map cursors back to tokens."""
tu = get_tu('int foo(int i);')
foo = get_cursor(tu, 'foo')
tokens = list(foo.get_tokens())
assert len(tokens) == 7
assert tokens[0].spelling == 'int'
assert tokens[1].spelling == 'foo'
def test_get_arguments():
tu = get_tu('void foo(int i, int j);')
foo = get_cursor(tu, 'foo')
arguments = list(foo.get_arguments())
assert len(arguments) == 2
assert arguments[0].spelling == "i"
assert arguments[1].spelling == "j"
kTemplateArgTest = """\
template <int kInt, typename T, bool kBool>
void foo();
template<>
void foo<-7, float, true>();
"""
def test_get_num_template_arguments():
tu = get_tu(kTemplateArgTest, lang='cpp')
foos = get_cursors(tu, 'foo')
assert foos[1].get_num_template_arguments() == 3
def test_get_template_argument_kind():
tu = get_tu(kTemplateArgTest, lang='cpp')
foos = get_cursors(tu, 'foo')
assert foos[1].get_template_argument_kind(0) == TemplateArgumentKind.INTEGRAL
assert foos[1].get_template_argument_kind(1) == TemplateArgumentKind.TYPE
assert foos[1].get_template_argument_kind(2) == TemplateArgumentKind.INTEGRAL
def test_get_template_argument_type():
tu = get_tu(kTemplateArgTest, lang='cpp')
foos = get_cursors(tu, 'foo')
assert foos[1].get_template_argument_type(1).kind == TypeKind.FLOAT
def test_get_template_argument_value():
tu = get_tu(kTemplateArgTest, lang='cpp')
foos = get_cursors(tu, 'foo')
assert foos[1].get_template_argument_value(0) == -7
assert foos[1].get_template_argument_value(2) == True
def test_get_template_argument_unsigned_value():
tu = get_tu(kTemplateArgTest, lang='cpp')
foos = get_cursors(tu, 'foo')
assert foos[1].get_template_argument_unsigned_value(0) == 2 ** 32 - 7
assert foos[1].get_template_argument_unsigned_value(2) == True
def test_referenced():
tu = get_tu('void foo(); void bar() { foo(); }')
foo = get_cursor(tu, 'foo')
bar = get_cursor(tu, 'bar')
for c in bar.get_children():
if c.kind == CursorKind.CALL_EXPR:
assert c.referenced.spelling == foo.spelling
break
def test_mangled_name():
kInputForMangling = """\
int foo(int, int);
"""
tu = get_tu(kInputForMangling, lang='cpp')
foo = get_cursor(tu, 'foo')
# Since libclang does not link in targets, we cannot pass a triple to it
# and force the target. To enable this test to pass on all platforms, accept
# all valid manglings.
# [c-index-test handles this by running the source through clang, emitting
# an AST file and running libclang on that AST file]
assert foo.mangled_name in ('_Z3fooii', '__Z3fooii', '?foo@@YAHHH')
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/test_file.py | from clang.cindex import Index, File
def test_file():
index = Index.create()
tu = index.parse('t.c', unsaved_files = [('t.c', "")])
file = File.from_name(tu, "t.c")
assert str(file) == "t.c"
assert file.name == "t.c"
assert repr(file) == "<File: t.c>"
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/util.py | # This file provides common utility functions for the test suite.
from clang.cindex import Cursor
from clang.cindex import TranslationUnit
def get_tu(source, lang='c', all_warnings=False, flags=[]):
"""Obtain a translation unit from source and language.
By default, the translation unit is created from source file "t.<ext>"
where <ext> is the default file extension for the specified language. By
default it is C, so "t.c" is the default file name.
Supported languages are {c, cpp, objc}.
all_warnings is a convenience argument to enable all compiler warnings.
"""
args = list(flags)
name = 't.c'
if lang == 'cpp':
name = 't.cpp'
args.append('-std=c++11')
elif lang == 'objc':
name = 't.m'
elif lang != 'c':
raise Exception('Unknown language: %s' % lang)
if all_warnings:
args += ['-Wall', '-Wextra']
return TranslationUnit.from_source(name, args, unsaved_files=[(name,
source)])
def get_cursor(source, spelling):
"""Obtain a cursor from a source object.
This provides a convenient search mechanism to find a cursor with specific
spelling within a source. The first argument can be either a
TranslationUnit or Cursor instance.
If the cursor is not found, None is returned.
"""
# Convenience for calling on a TU.
root_cursor = source if isinstance(source, Cursor) else source.cursor
for cursor in root_cursor.walk_preorder():
if cursor.spelling == spelling:
return cursor
return None
def get_cursors(source, spelling):
"""Obtain all cursors from a source object with a specific spelling.
This provides a convenient search mechanism to find all cursors with
specific spelling within a source. The first argument can be either a
TranslationUnit or Cursor instance.
If no cursors are found, an empty list is returned.
"""
# Convenience for calling on a TU.
root_cursor = source if isinstance(source, Cursor) else source.cursor
cursors = []
for cursor in root_cursor.walk_preorder():
if cursor.spelling == spelling:
cursors.append(cursor)
return cursors
__all__ = [
'get_cursor',
'get_cursors',
'get_tu',
]
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/test_translation_unit.py | import gc
import os
import tempfile
from clang.cindex import CursorKind
from clang.cindex import Cursor
from clang.cindex import File
from clang.cindex import Index
from clang.cindex import SourceLocation
from clang.cindex import SourceRange
from clang.cindex import TranslationUnitSaveError
from clang.cindex import TranslationUnitLoadError
from clang.cindex import TranslationUnit
from .util import get_cursor
from .util import get_tu
kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS')
def test_spelling():
path = os.path.join(kInputsDir, 'hello.cpp')
tu = TranslationUnit.from_source(path)
assert tu.spelling == path
def test_cursor():
path = os.path.join(kInputsDir, 'hello.cpp')
tu = get_tu(path)
c = tu.cursor
assert isinstance(c, Cursor)
assert c.kind is CursorKind.TRANSLATION_UNIT
def test_parse_arguments():
path = os.path.join(kInputsDir, 'parse_arguments.c')
tu = TranslationUnit.from_source(path, ['-DDECL_ONE=hello', '-DDECL_TWO=hi'])
spellings = [c.spelling for c in tu.cursor.get_children()]
assert spellings[-2] == 'hello'
assert spellings[-1] == 'hi'
def test_reparse_arguments():
path = os.path.join(kInputsDir, 'parse_arguments.c')
tu = TranslationUnit.from_source(path, ['-DDECL_ONE=hello', '-DDECL_TWO=hi'])
tu.reparse()
spellings = [c.spelling for c in tu.cursor.get_children()]
assert spellings[-2] == 'hello'
assert spellings[-1] == 'hi'
def test_unsaved_files():
tu = TranslationUnit.from_source('fake.c', ['-I./'], unsaved_files = [
('fake.c', """
#include "fake.h"
int x;
int SOME_DEFINE;
"""),
('./fake.h', """
#define SOME_DEFINE y
""")
])
spellings = [c.spelling for c in tu.cursor.get_children()]
assert spellings[-2] == 'x'
assert spellings[-1] == 'y'
def test_unsaved_files_2():
import StringIO
tu = TranslationUnit.from_source('fake.c', unsaved_files = [
('fake.c', StringIO.StringIO('int x;'))])
spellings = [c.spelling for c in tu.cursor.get_children()]
assert spellings[-1] == 'x'
def normpaths_equal(path1, path2):
""" Compares two paths for equality after normalizing them with
os.path.normpath
"""
return os.path.normpath(path1) == os.path.normpath(path2)
def test_includes():
def eq(expected, actual):
if not actual.is_input_file:
return normpaths_equal(expected[0], actual.source.name) and \
normpaths_equal(expected[1], actual.include.name)
else:
return normpaths_equal(expected[1], actual.include.name)
src = os.path.join(kInputsDir, 'include.cpp')
h1 = os.path.join(kInputsDir, "header1.h")
h2 = os.path.join(kInputsDir, "header2.h")
h3 = os.path.join(kInputsDir, "header3.h")
inc = [(src, h1), (h1, h3), (src, h2), (h2, h3)]
tu = TranslationUnit.from_source(src)
for i in zip(inc, tu.get_includes()):
assert eq(i[0], i[1])
def save_tu(tu):
"""Convenience API to save a TranslationUnit to a file.
Returns the filename it was saved to.
"""
_, path = tempfile.mkstemp()
tu.save(path)
return path
def test_save():
"""Ensure TranslationUnit.save() works."""
tu = get_tu('int foo();')
path = save_tu(tu)
assert os.path.exists(path)
assert os.path.getsize(path) > 0
os.unlink(path)
def test_save_translation_errors():
"""Ensure that saving to an invalid directory raises."""
tu = get_tu('int foo();')
path = '/does/not/exist/llvm-test.ast'
assert not os.path.exists(os.path.dirname(path))
try:
tu.save(path)
assert False
except TranslationUnitSaveError as ex:
expected = TranslationUnitSaveError.ERROR_UNKNOWN
assert ex.save_error == expected
def test_load():
"""Ensure TranslationUnits can be constructed from saved files."""
tu = get_tu('int foo();')
assert len(tu.diagnostics) == 0
path = save_tu(tu)
assert os.path.exists(path)
assert os.path.getsize(path) > 0
tu2 = TranslationUnit.from_ast_file(filename=path)
assert len(tu2.diagnostics) == 0
foo = get_cursor(tu2, 'foo')
assert foo is not None
# Just in case there is an open file descriptor somewhere.
del tu2
os.unlink(path)
def test_index_parse():
path = os.path.join(kInputsDir, 'hello.cpp')
index = Index.create()
tu = index.parse(path)
assert isinstance(tu, TranslationUnit)
def test_get_file():
"""Ensure tu.get_file() works appropriately."""
tu = get_tu('int foo();')
f = tu.get_file('t.c')
assert isinstance(f, File)
assert f.name == 't.c'
try:
f = tu.get_file('foobar.cpp')
except:
pass
else:
assert False
def test_get_source_location():
"""Ensure tu.get_source_location() works."""
tu = get_tu('int foo();')
location = tu.get_location('t.c', 2)
assert isinstance(location, SourceLocation)
assert location.offset == 2
assert location.file.name == 't.c'
location = tu.get_location('t.c', (1, 3))
assert isinstance(location, SourceLocation)
assert location.line == 1
assert location.column == 3
assert location.file.name == 't.c'
def test_get_source_range():
"""Ensure tu.get_source_range() works."""
tu = get_tu('int foo();')
r = tu.get_extent('t.c', (1,4))
assert isinstance(r, SourceRange)
assert r.start.offset == 1
assert r.end.offset == 4
assert r.start.file.name == 't.c'
assert r.end.file.name == 't.c'
r = tu.get_extent('t.c', ((1,2), (1,3)))
assert isinstance(r, SourceRange)
assert r.start.line == 1
assert r.start.column == 2
assert r.end.line == 1
assert r.end.column == 3
assert r.start.file.name == 't.c'
assert r.end.file.name == 't.c'
start = tu.get_location('t.c', 0)
end = tu.get_location('t.c', 5)
r = tu.get_extent('t.c', (start, end))
assert isinstance(r, SourceRange)
assert r.start.offset == 0
assert r.end.offset == 5
assert r.start.file.name == 't.c'
assert r.end.file.name == 't.c'
def test_get_tokens_gc():
"""Ensures get_tokens() works properly with garbage collection."""
tu = get_tu('int foo();')
r = tu.get_extent('t.c', (0, 10))
tokens = list(tu.get_tokens(extent=r))
assert tokens[0].spelling == 'int'
gc.collect()
assert tokens[0].spelling == 'int'
del tokens[1]
gc.collect()
assert tokens[0].spelling == 'int'
# May trigger segfault if we don't do our job properly.
del tokens
gc.collect()
gc.collect() # Just in case.
def test_fail_from_source():
path = os.path.join(kInputsDir, 'non-existent.cpp')
try:
tu = TranslationUnit.from_source(path)
except TranslationUnitLoadError:
tu = None
assert tu == None
def test_fail_from_ast_file():
path = os.path.join(kInputsDir, 'non-existent.ast')
try:
tu = TranslationUnit.from_ast_file(path)
except TranslationUnitLoadError:
tu = None
assert tu == None
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/test_type.py | import gc
from clang.cindex import CursorKind
from clang.cindex import TranslationUnit
from clang.cindex import TypeKind
from nose.tools import raises
from .util import get_cursor
from .util import get_tu
kInput = """\
typedef int I;
struct teststruct {
int a;
I b;
long c;
unsigned long d;
signed long e;
const int f;
int *g;
int ***h;
};
"""
def test_a_struct():
tu = get_tu(kInput)
teststruct = get_cursor(tu, 'teststruct')
assert teststruct is not None, "Could not find teststruct."
fields = list(teststruct.get_children())
assert all(x.kind == CursorKind.FIELD_DECL for x in fields)
assert all(x.translation_unit is not None for x in fields)
assert fields[0].spelling == 'a'
assert not fields[0].type.is_const_qualified()
assert fields[0].type.kind == TypeKind.INT
assert fields[0].type.get_canonical().kind == TypeKind.INT
assert fields[1].spelling == 'b'
assert not fields[1].type.is_const_qualified()
assert fields[1].type.kind == TypeKind.TYPEDEF
assert fields[1].type.get_canonical().kind == TypeKind.INT
assert fields[1].type.get_declaration().spelling == 'I'
assert fields[2].spelling == 'c'
assert not fields[2].type.is_const_qualified()
assert fields[2].type.kind == TypeKind.LONG
assert fields[2].type.get_canonical().kind == TypeKind.LONG
assert fields[3].spelling == 'd'
assert not fields[3].type.is_const_qualified()
assert fields[3].type.kind == TypeKind.ULONG
assert fields[3].type.get_canonical().kind == TypeKind.ULONG
assert fields[4].spelling == 'e'
assert not fields[4].type.is_const_qualified()
assert fields[4].type.kind == TypeKind.LONG
assert fields[4].type.get_canonical().kind == TypeKind.LONG
assert fields[5].spelling == 'f'
assert fields[5].type.is_const_qualified()
assert fields[5].type.kind == TypeKind.INT
assert fields[5].type.get_canonical().kind == TypeKind.INT
assert fields[6].spelling == 'g'
assert not fields[6].type.is_const_qualified()
assert fields[6].type.kind == TypeKind.POINTER
assert fields[6].type.get_pointee().kind == TypeKind.INT
assert fields[7].spelling == 'h'
assert not fields[7].type.is_const_qualified()
assert fields[7].type.kind == TypeKind.POINTER
assert fields[7].type.get_pointee().kind == TypeKind.POINTER
assert fields[7].type.get_pointee().get_pointee().kind == TypeKind.POINTER
assert fields[7].type.get_pointee().get_pointee().get_pointee().kind == TypeKind.INT
def test_references():
"""Ensure that a Type maintains a reference to a TranslationUnit."""
tu = get_tu('int x;')
children = list(tu.cursor.get_children())
assert len(children) > 0
cursor = children[0]
t = cursor.type
assert isinstance(t.translation_unit, TranslationUnit)
# Delete main TranslationUnit reference and force a GC.
del tu
gc.collect()
assert isinstance(t.translation_unit, TranslationUnit)
# If the TU was destroyed, this should cause a segfault.
decl = t.get_declaration()
constarrayInput="""
struct teststruct {
void *A[2];
};
"""
def testConstantArray():
tu = get_tu(constarrayInput)
teststruct = get_cursor(tu, 'teststruct')
assert teststruct is not None, "Didn't find teststruct??"
fields = list(teststruct.get_children())
assert fields[0].spelling == 'A'
assert fields[0].type.kind == TypeKind.CONSTANTARRAY
assert fields[0].type.get_array_element_type() is not None
assert fields[0].type.get_array_element_type().kind == TypeKind.POINTER
assert fields[0].type.get_array_size() == 2
def test_equal():
"""Ensure equivalence operators work on Type."""
source = 'int a; int b; void *v;'
tu = get_tu(source)
a = get_cursor(tu, 'a')
b = get_cursor(tu, 'b')
v = get_cursor(tu, 'v')
assert a is not None
assert b is not None
assert v is not None
assert a.type == b.type
assert a.type != v.type
assert a.type != None
assert a.type != 'foo'
def test_type_spelling():
"""Ensure Type.spelling works."""
tu = get_tu('int c[5]; int i[]; int x; int v[x];')
c = get_cursor(tu, 'c')
i = get_cursor(tu, 'i')
x = get_cursor(tu, 'x')
v = get_cursor(tu, 'v')
assert c is not None
assert i is not None
assert x is not None
assert v is not None
assert c.type.spelling == "int [5]"
assert i.type.spelling == "int []"
assert x.type.spelling == "int"
assert v.type.spelling == "int [x]"
def test_typekind_spelling():
"""Ensure TypeKind.spelling works."""
tu = get_tu('int a;')
a = get_cursor(tu, 'a')
assert a is not None
assert a.type.kind.spelling == 'Int'
def test_function_argument_types():
"""Ensure that Type.argument_types() works as expected."""
tu = get_tu('void f(int, int);')
f = get_cursor(tu, 'f')
assert f is not None
args = f.type.argument_types()
assert args is not None
assert len(args) == 2
t0 = args[0]
assert t0 is not None
assert t0.kind == TypeKind.INT
t1 = args[1]
assert t1 is not None
assert t1.kind == TypeKind.INT
args2 = list(args)
assert len(args2) == 2
assert t0 == args2[0]
assert t1 == args2[1]
@raises(TypeError)
def test_argument_types_string_key():
"""Ensure that non-int keys raise a TypeError."""
tu = get_tu('void f(int, int);')
f = get_cursor(tu, 'f')
assert f is not None
args = f.type.argument_types()
assert len(args) == 2
args['foo']
@raises(IndexError)
def test_argument_types_negative_index():
"""Ensure that negative indexes on argument_types Raises an IndexError."""
tu = get_tu('void f(int, int);')
f = get_cursor(tu, 'f')
args = f.type.argument_types()
args[-1]
@raises(IndexError)
def test_argument_types_overflow_index():
"""Ensure that indexes beyond the length of Type.argument_types() raise."""
tu = get_tu('void f(int, int);')
f = get_cursor(tu, 'f')
args = f.type.argument_types()
args[2]
@raises(Exception)
def test_argument_types_invalid_type():
"""Ensure that obtaining argument_types on a Type without them raises."""
tu = get_tu('int i;')
i = get_cursor(tu, 'i')
assert i is not None
i.type.argument_types()
def test_is_pod():
"""Ensure Type.is_pod() works."""
tu = get_tu('int i; void f();')
i = get_cursor(tu, 'i')
f = get_cursor(tu, 'f')
assert i is not None
assert f is not None
assert i.type.is_pod()
assert not f.type.is_pod()
def test_function_variadic():
"""Ensure Type.is_function_variadic works."""
source ="""
#include <stdarg.h>
void foo(int a, ...);
void bar(int a, int b);
"""
tu = get_tu(source)
foo = get_cursor(tu, 'foo')
bar = get_cursor(tu, 'bar')
assert foo is not None
assert bar is not None
assert isinstance(foo.type.is_function_variadic(), bool)
assert foo.type.is_function_variadic()
assert not bar.type.is_function_variadic()
def test_element_type():
"""Ensure Type.element_type works."""
tu = get_tu('int c[5]; int i[]; int x; int v[x];')
c = get_cursor(tu, 'c')
i = get_cursor(tu, 'i')
v = get_cursor(tu, 'v')
assert c is not None
assert i is not None
assert v is not None
assert c.type.kind == TypeKind.CONSTANTARRAY
assert c.type.element_type.kind == TypeKind.INT
assert i.type.kind == TypeKind.INCOMPLETEARRAY
assert i.type.element_type.kind == TypeKind.INT
assert v.type.kind == TypeKind.VARIABLEARRAY
assert v.type.element_type.kind == TypeKind.INT
@raises(Exception)
def test_invalid_element_type():
"""Ensure Type.element_type raises if type doesn't have elements."""
tu = get_tu('int i;')
i = get_cursor(tu, 'i')
assert i is not None
i.element_type
def test_element_count():
"""Ensure Type.element_count works."""
tu = get_tu('int i[5]; int j;')
i = get_cursor(tu, 'i')
j = get_cursor(tu, 'j')
assert i is not None
assert j is not None
assert i.type.element_count == 5
try:
j.type.element_count
assert False
except:
assert True
def test_is_volatile_qualified():
"""Ensure Type.is_volatile_qualified works."""
tu = get_tu('volatile int i = 4; int j = 2;')
i = get_cursor(tu, 'i')
j = get_cursor(tu, 'j')
assert i is not None
assert j is not None
assert isinstance(i.type.is_volatile_qualified(), bool)
assert i.type.is_volatile_qualified()
assert not j.type.is_volatile_qualified()
def test_is_restrict_qualified():
"""Ensure Type.is_restrict_qualified works."""
tu = get_tu('struct s { void * restrict i; void * j; };')
i = get_cursor(tu, 'i')
j = get_cursor(tu, 'j')
assert i is not None
assert j is not None
assert isinstance(i.type.is_restrict_qualified(), bool)
assert i.type.is_restrict_qualified()
assert not j.type.is_restrict_qualified()
def test_record_layout():
"""Ensure Cursor.type.get_size, Cursor.type.get_align and
Cursor.type.get_offset works."""
source ="""
struct a {
long a1;
long a2:3;
long a3:4;
long long a4;
};
"""
tries=[(['-target','i386-linux-gnu'],(4,16,0,32,35,64)),
(['-target','nvptx64-unknown-unknown'],(8,24,0,64,67,128)),
(['-target','i386-pc-win32'],(8,16,0,32,35,64)),
(['-target','msp430-none-none'],(2,14,0,32,35,48))]
for flags, values in tries:
align,total,a1,a2,a3,a4 = values
tu = get_tu(source, flags=flags)
teststruct = get_cursor(tu, 'a')
fields = list(teststruct.get_children())
assert teststruct.type.get_align() == align
assert teststruct.type.get_size() == total
assert teststruct.type.get_offset(fields[0].spelling) == a1
assert teststruct.type.get_offset(fields[1].spelling) == a2
assert teststruct.type.get_offset(fields[2].spelling) == a3
assert teststruct.type.get_offset(fields[3].spelling) == a4
assert fields[0].is_bitfield() == False
assert fields[1].is_bitfield() == True
assert fields[1].get_bitfield_width() == 3
assert fields[2].is_bitfield() == True
assert fields[2].get_bitfield_width() == 4
assert fields[3].is_bitfield() == False
def test_offset():
"""Ensure Cursor.get_record_field_offset works in anonymous records"""
source="""
struct Test {
struct {int a;} typeanon;
struct {
int bariton;
union {
int foo;
};
};
int bar;
};"""
tries=[(['-target','i386-linux-gnu'],(4,16,0,32,64,96)),
(['-target','nvptx64-unknown-unknown'],(8,24,0,32,64,96)),
(['-target','i386-pc-win32'],(8,16,0,32,64,96)),
(['-target','msp430-none-none'],(2,14,0,32,64,96))]
for flags, values in tries:
align,total,f1,bariton,foo,bar = values
tu = get_tu(source)
teststruct = get_cursor(tu, 'Test')
children = list(teststruct.get_children())
fields = list(teststruct.type.get_fields())
assert children[0].kind == CursorKind.STRUCT_DECL
assert children[0].spelling != "typeanon"
assert children[1].spelling == "typeanon"
assert fields[0].kind == CursorKind.FIELD_DECL
assert fields[1].kind == CursorKind.FIELD_DECL
assert fields[1].is_anonymous()
assert teststruct.type.get_offset("typeanon") == f1
assert teststruct.type.get_offset("bariton") == bariton
assert teststruct.type.get_offset("foo") == foo
assert teststruct.type.get_offset("bar") == bar
def test_decay():
"""Ensure decayed types are handled as the original type"""
tu = get_tu("void foo(int a[]);")
foo = get_cursor(tu, 'foo')
a = foo.type.argument_types()[0]
assert a.kind == TypeKind.INCOMPLETEARRAY
assert a.element_type.kind == TypeKind.INT
assert a.get_canonical().kind == TypeKind.INCOMPLETEARRAY
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/INPUTS/parse_arguments.c | int DECL_ONE = 1;
int DECL_TWO = 2;
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/INPUTS/header2.h | #ifndef HEADER2
#define HEADER2
#include "header3.h"
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/INPUTS/include.cpp | #include "header1.h"
#include "header2.h"
#include "header1.h"
int main() { }
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/INPUTS/header1.h | #ifndef HEADER1
#define HEADER1
#include "header3.h"
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/INPUTS/header3.h | // Not a guarded header!
void f();
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/INPUTS/hello.cpp | #include "stdio.h"
int main(int argc, char* argv[]) {
printf("hello world\n");
return 0;
}
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex | repos/DirectXShaderCompiler/tools/clang/bindings/python/tests/cindex/INPUTS/compile_commands.json | [
{
"directory": "/home/john.doe/MyProject",
"command": "clang++ -o project.o -c /home/john.doe/MyProject/project.cpp",
"file": "/home/john.doe/MyProject/project.cpp"
},
{
"directory": "/home/john.doe/MyProjectA",
"command": "clang++ -o project2.o -c /home/john.doe/MyProject/project2.cpp",
"file": "/home/john.doe/MyProject/project2.cpp"
},
{
"directory": "/home/john.doe/MyProjectB",
"command": "clang++ -DFEATURE=1 -o project2-feature.o -c /home/john.doe/MyProject/project2.cpp",
"file": "/home/john.doe/MyProject/project2.cpp"
}
]
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/examples | repos/DirectXShaderCompiler/tools/clang/bindings/python/examples/cindex/cindex-dump.py | #!/usr/bin/env python
#===- cindex-dump.py - cindex/Python Source Dump -------------*- python -*--===#
#
# Copyright (C) Microsoft Corporation. All rights reserved.
# This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details.
#
#===------------------------------------------------------------------------===#
"""
A simple command line tool for dumping a source file using the Clang Index
Library.
"""
def get_diag_info(diag):
return { 'severity' : diag.severity,
'location' : diag.location,
'spelling' : diag.spelling,
'ranges' : diag.ranges,
'fixits' : diag.fixits }
def get_cursor_id(cursor, cursor_list = []):
if not opts.showIDs:
return None
if cursor is None:
return None
# FIXME: This is really slow. It would be nice if the index API exposed
# something that let us hash cursors.
for i,c in enumerate(cursor_list):
if cursor == c:
return i
cursor_list.append(cursor)
return len(cursor_list) - 1
def get_info(node, depth=0):
if opts.maxDepth is not None and depth >= opts.maxDepth:
children = None
else:
children = [get_info(c, depth+1)
for c in node.get_children()]
return { 'id' : get_cursor_id(node),
'kind' : node.kind,
'usr' : node.get_usr(),
'spelling' : node.spelling,
'location' : node.location,
'extent.start' : node.extent.start,
'extent.end' : node.extent.end,
'is_definition' : node.is_definition(),
'definition id' : get_cursor_id(node.get_definition()),
'children' : children }
def main():
from clang.cindex import Index
from pprint import pprint
from optparse import OptionParser, OptionGroup
global opts
parser = OptionParser("usage: %prog [options] {filename} [clang-args*]")
parser.add_option("", "--show-ids", dest="showIDs",
help="Compute cursor IDs (very slow)",
action="store_true", default=False)
parser.add_option("", "--max-depth", dest="maxDepth",
help="Limit cursor expansion to depth N",
metavar="N", type=int, default=None)
parser.disable_interspersed_args()
(opts, args) = parser.parse_args()
if len(args) == 0:
parser.error('invalid number arguments')
index = Index.create()
tu = index.parse(None, args)
if not tu:
parser.error("unable to load input")
pprint(('diags', map(get_diag_info, tu.diagnostics)))
pprint(('nodes', get_info(tu.cursor)))
if __name__ == '__main__':
main()
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python/examples | repos/DirectXShaderCompiler/tools/clang/bindings/python/examples/cindex/cindex-includes.py | #!/usr/bin/env python
#===- cindex-includes.py - cindex/Python Inclusion Graph -----*- python -*--===#
#
# Copyright (C) Microsoft Corporation. All rights reserved.
# This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details.
#
#===------------------------------------------------------------------------===#
"""
A simple command line tool for dumping a Graphviz description (dot) that
describes include dependencies.
"""
def main():
import sys
from clang.cindex import Index
from optparse import OptionParser, OptionGroup
parser = OptionParser("usage: %prog [options] {filename} [clang-args*]")
parser.disable_interspersed_args()
(opts, args) = parser.parse_args()
if len(args) == 0:
parser.error('invalid number arguments')
# FIXME: Add an output file option
out = sys.stdout
index = Index.create()
tu = index.parse(None, args)
if not tu:
parser.error("unable to load input")
# A helper function for generating the node name.
def name(f):
if f:
return "\"" + f.name + "\""
# Generate the include graph
out.write("digraph G {\n")
for i in tu.get_includes():
line = " ";
if i.is_input_file:
# Always write the input file as a node just in case it doesn't
# actually include anything. This would generate a 1 node graph.
line += name(i.include)
else:
line += '%s->%s' % (name(i.source), name(i.include))
line += "\n";
out.write(line)
out.write("}\n")
if __name__ == '__main__':
main()
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python | repos/DirectXShaderCompiler/tools/clang/bindings/python/clang/cindex.py | #===- cindex.py - Python Indexing Library Bindings -----------*- python -*--===#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#===------------------------------------------------------------------------===#
r"""
Clang Indexing Library Bindings
===============================
This module provides an interface to the Clang indexing library. It is a
low-level interface to the indexing library which attempts to match the Clang
API directly while also being "pythonic". Notable differences from the C API
are:
* string results are returned as Python strings, not CXString objects.
* null cursors are translated to None.
* access to child cursors is done via iteration, not visitation.
The major indexing objects are:
Index
The top-level object which manages some global library state.
TranslationUnit
High-level object encapsulating the AST for a single translation unit. These
can be loaded from .ast files or parsed on the fly.
Cursor
Generic object for representing a node in the AST.
SourceRange, SourceLocation, and File
Objects representing information about the input source.
Most object information is exposed using properties, when the underlying API
call is efficient.
"""
# TODO
# ====
#
# o API support for invalid translation units. Currently we can't even get the
# diagnostics on failure because they refer to locations in an object that
# will have been invalidated.
#
# o fix memory management issues (currently client must hold on to index and
# translation unit, or risk crashes).
#
# o expose code completion APIs.
#
# o cleanup ctypes wrapping, would be nice to separate the ctypes details more
# clearly, and hide from the external interface (i.e., help(cindex)).
#
# o implement additional SourceLocation, SourceRange, and File methods.
from ctypes import *
import collections
import clang.enumerations
# ctypes doesn't implicitly convert c_void_p to the appropriate wrapper
# object. This is a problem, because it means that from_parameter will see an
# integer and pass the wrong value on platforms where int != void*. Work around
# this by marshalling object arguments as void**.
c_object_p = POINTER(c_void_p)
callbacks = {}
### Exception Classes ###
class TranslationUnitLoadError(Exception):
"""Represents an error that occurred when loading a TranslationUnit.
This is raised in the case where a TranslationUnit could not be
instantiated due to failure in the libclang library.
FIXME: Make libclang expose additional error information in this scenario.
"""
pass
class TranslationUnitSaveError(Exception):
"""Represents an error that occurred when saving a TranslationUnit.
Each error has associated with it an enumerated value, accessible under
e.save_error. Consumers can compare the value with one of the ERROR_
constants in this class.
"""
# Indicates that an unknown error occurred. This typically indicates that
# I/O failed during save.
ERROR_UNKNOWN = 1
# Indicates that errors during translation prevented saving. The errors
# should be available via the TranslationUnit's diagnostics.
ERROR_TRANSLATION_ERRORS = 2
# Indicates that the translation unit was somehow invalid.
ERROR_INVALID_TU = 3
def __init__(self, enumeration, message):
assert isinstance(enumeration, int)
if enumeration < 1 or enumeration > 3:
raise Exception("Encountered undefined TranslationUnit save error "
"constant: %d. Please file a bug to have this "
"value supported." % enumeration)
self.save_error = enumeration
Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
### Structures and Utility Classes ###
class CachedProperty(object):
"""Decorator that lazy-loads the value of a property.
The first time the property is accessed, the original property function is
executed. The value it returns is set as the new value of that instance's
property, replacing the original method.
"""
def __init__(self, wrapped):
self.wrapped = wrapped
try:
self.__doc__ = wrapped.__doc__
except:
pass
def __get__(self, instance, instance_type=None):
if instance is None:
return self
value = self.wrapped(instance)
setattr(instance, self.wrapped.__name__, value)
return value
class _CXString(Structure):
"""Helper for transforming CXString results."""
_fields_ = [("spelling", c_char_p), ("free", c_int)]
def __del__(self):
conf.lib.clang_disposeString(self)
@staticmethod
def from_result(res, fn, args):
assert isinstance(res, _CXString)
return conf.lib.clang_getCString(res)
class SourceLocation(Structure):
"""
A SourceLocation represents a particular location within a source file.
"""
_fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)]
_data = None
def _get_instantiation(self):
if self._data is None:
f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint()
conf.lib.clang_getInstantiationLocation(self, byref(f), byref(l),
byref(c), byref(o))
if f:
f = File(f)
else:
f = None
self._data = (f, int(l.value), int(c.value), int(o.value))
return self._data
@staticmethod
def from_position(tu, file, line, column):
"""
Retrieve the source location associated with a given file/line/column in
a particular translation unit.
"""
return conf.lib.clang_getLocation(tu, file, line, column)
@staticmethod
def from_offset(tu, file, offset):
"""Retrieve a SourceLocation from a given character offset.
tu -- TranslationUnit file belongs to
file -- File instance to obtain offset from
offset -- Integer character offset within file
"""
return conf.lib.clang_getLocationForOffset(tu, file, offset)
@property
def file(self):
"""Get the file represented by this source location."""
return self._get_instantiation()[0]
@property
def line(self):
"""Get the line represented by this source location."""
return self._get_instantiation()[1]
@property
def column(self):
"""Get the column represented by this source location."""
return self._get_instantiation()[2]
@property
def offset(self):
"""Get the file offset represented by this source location."""
return self._get_instantiation()[3]
def __eq__(self, other):
return conf.lib.clang_equalLocations(self, other)
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
if self.file:
filename = self.file.name
else:
filename = None
return "<SourceLocation file %r, line %r, column %r>" % (
filename, self.line, self.column)
class SourceRange(Structure):
"""
A SourceRange describes a range of source locations within the source
code.
"""
_fields_ = [
("ptr_data", c_void_p * 2),
("begin_int_data", c_uint),
("end_int_data", c_uint)]
# FIXME: Eliminate this and make normal constructor? Requires hiding ctypes
# object.
@staticmethod
def from_locations(start, end):
return conf.lib.clang_getRange(start, end)
@property
def start(self):
"""
Return a SourceLocation representing the first character within a
source range.
"""
return conf.lib.clang_getRangeStart(self)
@property
def end(self):
"""
Return a SourceLocation representing the last character within a
source range.
"""
return conf.lib.clang_getRangeEnd(self)
def __eq__(self, other):
return conf.lib.clang_equalRanges(self, other)
def __ne__(self, other):
return not self.__eq__(other)
def __contains__(self, other):
"""Useful to detect the Token/Lexer bug"""
if not isinstance(other, SourceLocation):
return False
if other.file is None and self.start.file is None:
pass
elif ( self.start.file.name != other.file.name or
other.file.name != self.end.file.name):
# same file name
return False
# same file, in between lines
if self.start.line < other.line < self.end.line:
return True
elif self.start.line == other.line:
# same file first line
if self.start.column <= other.column:
return True
elif other.line == self.end.line:
# same file last line
if other.column <= self.end.column:
return True
return False
def __repr__(self):
return "<SourceRange start %r, end %r>" % (self.start, self.end)
class Diagnostic(object):
"""
A Diagnostic is a single instance of a Clang diagnostic. It includes the
diagnostic severity, the message, the location the diagnostic occurred, as
well as additional source ranges and associated fix-it hints.
"""
Ignored = 0
Note = 1
Warning = 2
Error = 3
Fatal = 4
def __init__(self, ptr):
self.ptr = ptr
def __del__(self):
conf.lib.clang_disposeDiagnostic(self)
@property
def severity(self):
return conf.lib.clang_getDiagnosticSeverity(self)
@property
def location(self):
return conf.lib.clang_getDiagnosticLocation(self)
@property
def spelling(self):
return conf.lib.clang_getDiagnosticSpelling(self)
@property
def ranges(self):
class RangeIterator:
def __init__(self, diag):
self.diag = diag
def __len__(self):
return int(conf.lib.clang_getDiagnosticNumRanges(self.diag))
def __getitem__(self, key):
if (key >= len(self)):
raise IndexError
return conf.lib.clang_getDiagnosticRange(self.diag, key)
return RangeIterator(self)
@property
def fixits(self):
class FixItIterator:
def __init__(self, diag):
self.diag = diag
def __len__(self):
return int(conf.lib.clang_getDiagnosticNumFixIts(self.diag))
def __getitem__(self, key):
range = SourceRange()
value = conf.lib.clang_getDiagnosticFixIt(self.diag, key,
byref(range))
if len(value) == 0:
raise IndexError
return FixIt(range, value)
return FixItIterator(self)
@property
def category_number(self):
"""The category number for this diagnostic or 0 if unavailable."""
return conf.lib.clang_getDiagnosticCategory(self)
@property
def category_name(self):
"""The string name of the category for this diagnostic."""
return conf.lib.clang_getDiagnosticCategoryText(self)
@property
def option(self):
"""The command-line option that enables this diagnostic."""
return conf.lib.clang_getDiagnosticOption(self, None)
@property
def disable_option(self):
"""The command-line option that disables this diagnostic."""
disable = _CXString()
conf.lib.clang_getDiagnosticOption(self, byref(disable))
return conf.lib.clang_getCString(disable)
def __repr__(self):
return "<Diagnostic severity %r, location %r, spelling %r>" % (
self.severity, self.location, self.spelling)
def from_param(self):
return self.ptr
class FixIt(object):
"""
A FixIt represents a transformation to be applied to the source to
"fix-it". The fix-it shouldbe applied by replacing the given source range
with the given value.
"""
def __init__(self, range, value):
self.range = range
self.value = value
def __repr__(self):
return "<FixIt range %r, value %r>" % (self.range, self.value)
class TokenGroup(object):
"""Helper class to facilitate token management.
Tokens are allocated from libclang in chunks. They must be disposed of as a
collective group.
One purpose of this class is for instances to represent groups of allocated
tokens. Each token in a group contains a reference back to an instance of
this class. When all tokens from a group are garbage collected, it allows
this class to be garbage collected. When this class is garbage collected,
it calls the libclang destructor which invalidates all tokens in the group.
You should not instantiate this class outside of this module.
"""
def __init__(self, tu, memory, count):
self._tu = tu
self._memory = memory
self._count = count
def __del__(self):
conf.lib.clang_disposeTokens(self._tu, self._memory, self._count)
@staticmethod
def get_tokens(tu, extent):
"""Helper method to return all tokens in an extent.
This functionality is needed multiple places in this module. We define
it here because it seems like a logical place.
"""
tokens_memory = POINTER(Token)()
tokens_count = c_uint()
conf.lib.clang_tokenize(tu, extent, byref(tokens_memory),
byref(tokens_count))
count = int(tokens_count.value)
# If we get no tokens, no memory was allocated. Be sure not to return
# anything and potentially call a destructor on nothing.
if count < 1:
return
tokens_array = cast(tokens_memory, POINTER(Token * count)).contents
token_group = TokenGroup(tu, tokens_memory, tokens_count)
for i in xrange(0, count):
token = Token()
token.int_data = tokens_array[i].int_data
token.ptr_data = tokens_array[i].ptr_data
token._tu = tu
token._group = token_group
yield token
class TokenKind(object):
"""Describes a specific type of a Token."""
_value_map = {} # int -> TokenKind
def __init__(self, value, name):
"""Create a new TokenKind instance from a numeric value and a name."""
self.value = value
self.name = name
def __repr__(self):
return 'TokenKind.%s' % (self.name,)
@staticmethod
def from_value(value):
"""Obtain a registered TokenKind instance from its value."""
result = TokenKind._value_map.get(value, None)
if result is None:
raise ValueError('Unknown TokenKind: %d' % value)
return result
@staticmethod
def register(value, name):
"""Register a new TokenKind enumeration.
This should only be called at module load time by code within this
package.
"""
if value in TokenKind._value_map:
raise ValueError('TokenKind already registered: %d' % value)
kind = TokenKind(value, name)
TokenKind._value_map[value] = kind
setattr(TokenKind, name, kind)
### Cursor Kinds ###
class BaseEnumeration(object):
"""
Common base class for named enumerations held in sync with Index.h values.
Subclasses must define their own _kinds and _name_map members, as:
_kinds = []
_name_map = None
These values hold the per-subclass instances and value-to-name mappings,
respectively.
"""
def __init__(self, value):
if value >= len(self.__class__._kinds):
self.__class__._kinds += [None] * (value - len(self.__class__._kinds) + 1)
if self.__class__._kinds[value] is not None:
raise ValueError,'{0} value {1} already loaded'.format(
str(self.__class__), value)
self.value = value
self.__class__._kinds[value] = self
self.__class__._name_map = None
def from_param(self):
return self.value
@property
def name(self):
"""Get the enumeration name of this cursor kind."""
if self._name_map is None:
self._name_map = {}
for key, value in self.__class__.__dict__.items():
if isinstance(value, self.__class__):
self._name_map[value] = key
return self._name_map[self]
@classmethod
def from_id(cls, id):
if id >= len(cls._kinds) or cls._kinds[id] is None:
raise ValueError,'Unknown template argument kind %d' % id
return cls._kinds[id]
def __repr__(self):
return '%s.%s' % (self.__class__, self.name,)
class CursorKind(BaseEnumeration):
"""
A CursorKind describes the kind of entity that a cursor points to.
"""
# The required BaseEnumeration declarations.
_kinds = []
_name_map = None
@staticmethod
def get_all_kinds():
"""Return all CursorKind enumeration instances."""
return filter(None, CursorKind._kinds)
def is_declaration(self):
"""Test if this is a declaration kind."""
return conf.lib.clang_isDeclaration(self)
def is_reference(self):
"""Test if this is a reference kind."""
return conf.lib.clang_isReference(self)
def is_expression(self):
"""Test if this is an expression kind."""
return conf.lib.clang_isExpression(self)
def is_statement(self):
"""Test if this is a statement kind."""
return conf.lib.clang_isStatement(self)
def is_attribute(self):
"""Test if this is an attribute kind."""
return conf.lib.clang_isAttribute(self)
def is_invalid(self):
"""Test if this is an invalid kind."""
return conf.lib.clang_isInvalid(self)
def is_translation_unit(self):
"""Test if this is a translation unit kind."""
return conf.lib.clang_isTranslationUnit(self)
def is_preprocessing(self):
"""Test if this is a preprocessing kind."""
return conf.lib.clang_isPreprocessing(self)
def is_unexposed(self):
"""Test if this is an unexposed kind."""
return conf.lib.clang_isUnexposed(self)
def __repr__(self):
return 'CursorKind.%s' % (self.name,)
###
# Declaration Kinds
# A declaration whose specific kind is not exposed via this interface.
#
# Unexposed declarations have the same operations as any other kind of
# declaration; one can extract their location information, spelling, find their
# definitions, etc. However, the specific kind of the declaration is not
# reported.
CursorKind.UNEXPOSED_DECL = CursorKind(1)
# A C or C++ struct.
CursorKind.STRUCT_DECL = CursorKind(2)
# A C or C++ union.
CursorKind.UNION_DECL = CursorKind(3)
# A C++ class.
CursorKind.CLASS_DECL = CursorKind(4)
# An enumeration.
CursorKind.ENUM_DECL = CursorKind(5)
# A field (in C) or non-static data member (in C++) in a struct, union, or C++
# class.
CursorKind.FIELD_DECL = CursorKind(6)
# An enumerator constant.
CursorKind.ENUM_CONSTANT_DECL = CursorKind(7)
# A function.
CursorKind.FUNCTION_DECL = CursorKind(8)
# A variable.
CursorKind.VAR_DECL = CursorKind(9)
# A function or method parameter.
CursorKind.PARM_DECL = CursorKind(10)
# An Objective-C @interface.
CursorKind.OBJC_INTERFACE_DECL = CursorKind(11)
# An Objective-C @interface for a category.
CursorKind.OBJC_CATEGORY_DECL = CursorKind(12)
# An Objective-C @protocol declaration.
CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13)
# An Objective-C @property declaration.
CursorKind.OBJC_PROPERTY_DECL = CursorKind(14)
# An Objective-C instance variable.
CursorKind.OBJC_IVAR_DECL = CursorKind(15)
# An Objective-C instance method.
CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16)
# An Objective-C class method.
CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17)
# An Objective-C @implementation.
CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18)
# An Objective-C @implementation for a category.
CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19)
# A typedef.
CursorKind.TYPEDEF_DECL = CursorKind(20)
# A C++ class method.
CursorKind.CXX_METHOD = CursorKind(21)
# A C++ namespace.
CursorKind.NAMESPACE = CursorKind(22)
# A linkage specification, e.g. 'extern "C"'.
CursorKind.LINKAGE_SPEC = CursorKind(23)
# A C++ constructor.
CursorKind.CONSTRUCTOR = CursorKind(24)
# A C++ destructor.
CursorKind.DESTRUCTOR = CursorKind(25)
# A C++ conversion function.
CursorKind.CONVERSION_FUNCTION = CursorKind(26)
# A C++ template type parameter
CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27)
# A C++ non-type template paramater.
CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28)
# A C++ template template parameter.
CursorKind.TEMPLATE_TEMPLATE_PARAMETER = CursorKind(29)
# A C++ function template.
CursorKind.FUNCTION_TEMPLATE = CursorKind(30)
# A C++ class template.
CursorKind.CLASS_TEMPLATE = CursorKind(31)
# A C++ class template partial specialization.
CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32)
# A C++ namespace alias declaration.
CursorKind.NAMESPACE_ALIAS = CursorKind(33)
# A C++ using directive
CursorKind.USING_DIRECTIVE = CursorKind(34)
# A C++ using declaration
CursorKind.USING_DECLARATION = CursorKind(35)
# A Type alias decl.
CursorKind.TYPE_ALIAS_DECL = CursorKind(36)
# A Objective-C synthesize decl
CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37)
# A Objective-C dynamic decl
CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38)
# A C++ access specifier decl.
CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39)
###
# Reference Kinds
CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40)
CursorKind.OBJC_PROTOCOL_REF = CursorKind(41)
CursorKind.OBJC_CLASS_REF = CursorKind(42)
# A reference to a type declaration.
#
# A type reference occurs anywhere where a type is named but not
# declared. For example, given:
# typedef unsigned size_type;
# size_type size;
#
# The typedef is a declaration of size_type (CXCursor_TypedefDecl),
# while the type of the variable "size" is referenced. The cursor
# referenced by the type of size is the typedef for size_type.
CursorKind.TYPE_REF = CursorKind(43)
CursorKind.CXX_BASE_SPECIFIER = CursorKind(44)
# A reference to a class template, function template, template
# template parameter, or class template partial specialization.
CursorKind.TEMPLATE_REF = CursorKind(45)
# A reference to a namespace or namepsace alias.
CursorKind.NAMESPACE_REF = CursorKind(46)
# A reference to a member of a struct, union, or class that occurs in
# some non-expression context, e.g., a designated initializer.
CursorKind.MEMBER_REF = CursorKind(47)
# A reference to a labeled statement.
CursorKind.LABEL_REF = CursorKind(48)
# A reference to a set of overloaded functions or function templates
# that has not yet been resolved to a specific function or function template.
CursorKind.OVERLOADED_DECL_REF = CursorKind(49)
# A reference to a variable that occurs in some non-expression
# context, e.g., a C++ lambda capture list.
CursorKind.VARIABLE_REF = CursorKind(50)
###
# Invalid/Error Kinds
CursorKind.INVALID_FILE = CursorKind(70)
CursorKind.NO_DECL_FOUND = CursorKind(71)
CursorKind.NOT_IMPLEMENTED = CursorKind(72)
CursorKind.INVALID_CODE = CursorKind(73)
###
# Expression Kinds
# An expression whose specific kind is not exposed via this interface.
#
# Unexposed expressions have the same operations as any other kind of
# expression; one can extract their location information, spelling, children,
# etc. However, the specific kind of the expression is not reported.
CursorKind.UNEXPOSED_EXPR = CursorKind(100)
# An expression that refers to some value declaration, such as a function,
# varible, or enumerator.
CursorKind.DECL_REF_EXPR = CursorKind(101)
# An expression that refers to a member of a struct, union, class, Objective-C
# class, etc.
CursorKind.MEMBER_REF_EXPR = CursorKind(102)
# An expression that calls a function.
CursorKind.CALL_EXPR = CursorKind(103)
# An expression that sends a message to an Objective-C object or class.
CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104)
# An expression that represents a block literal.
CursorKind.BLOCK_EXPR = CursorKind(105)
# An integer literal.
CursorKind.INTEGER_LITERAL = CursorKind(106)
# A floating point number literal.
CursorKind.FLOATING_LITERAL = CursorKind(107)
# An imaginary number literal.
CursorKind.IMAGINARY_LITERAL = CursorKind(108)
# A string literal.
CursorKind.STRING_LITERAL = CursorKind(109)
# A character literal.
CursorKind.CHARACTER_LITERAL = CursorKind(110)
# A parenthesized expression, e.g. "(1)".
#
# This AST node is only formed if full location information is requested.
CursorKind.PAREN_EXPR = CursorKind(111)
# This represents the unary-expression's (except sizeof and
# alignof).
CursorKind.UNARY_OPERATOR = CursorKind(112)
# [C99 6.5.2.1] Array Subscripting.
CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113)
# A builtin binary operation expression such as "x + y" or
# "x <= y".
CursorKind.BINARY_OPERATOR = CursorKind(114)
# Compound assignment such as "+=".
CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115)
# The ?: ternary operator.
CursorKind.CONDITIONAL_OPERATOR = CursorKind(116)
# An explicit cast in C (C99 6.5.4) or a C-style cast in C++
# (C++ [expr.cast]), which uses the syntax (Type)expr.
#
# For example: (int)f.
CursorKind.CSTYLE_CAST_EXPR = CursorKind(117)
# [C99 6.5.2.5]
CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118)
# Describes an C or C++ initializer list.
CursorKind.INIT_LIST_EXPR = CursorKind(119)
# The GNU address of label extension, representing &&label.
CursorKind.ADDR_LABEL_EXPR = CursorKind(120)
# This is the GNU Statement Expression extension: ({int X=4; X;})
CursorKind.StmtExpr = CursorKind(121)
# Represents a C11 generic selection.
CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122)
# Implements the GNU __null extension, which is a name for a null
# pointer constant that has integral type (e.g., int or long) and is the same
# size and alignment as a pointer.
#
# The __null extension is typically only used by system headers, which define
# NULL as __null in C++ rather than using 0 (which is an integer that may not
# match the size of a pointer).
CursorKind.GNU_NULL_EXPR = CursorKind(123)
# C++'s static_cast<> expression.
CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124)
# C++'s dynamic_cast<> expression.
CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125)
# C++'s reinterpret_cast<> expression.
CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126)
# C++'s const_cast<> expression.
CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127)
# Represents an explicit C++ type conversion that uses "functional"
# notion (C++ [expr.type.conv]).
#
# Example:
# \code
# x = int(0.5);
# \endcode
CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128)
# A C++ typeid expression (C++ [expr.typeid]).
CursorKind.CXX_TYPEID_EXPR = CursorKind(129)
# [C++ 2.13.5] C++ Boolean Literal.
CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130)
# [C++0x 2.14.7] C++ Pointer Literal.
CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131)
# Represents the "this" expression in C++
CursorKind.CXX_THIS_EXPR = CursorKind(132)
# [C++ 15] C++ Throw Expression.
#
# This handles 'throw' and 'throw' assignment-expression. When
# assignment-expression isn't present, Op will be null.
CursorKind.CXX_THROW_EXPR = CursorKind(133)
# A new expression for memory allocation and constructor calls, e.g:
# "new CXXNewExpr(foo)".
CursorKind.CXX_NEW_EXPR = CursorKind(134)
# A delete expression for memory deallocation and destructor calls,
# e.g. "delete[] pArray".
CursorKind.CXX_DELETE_EXPR = CursorKind(135)
# Represents a unary expression.
CursorKind.CXX_UNARY_EXPR = CursorKind(136)
# ObjCStringLiteral, used for Objective-C string literals i.e. "foo".
CursorKind.OBJC_STRING_LITERAL = CursorKind(137)
# ObjCEncodeExpr, used for in Objective-C.
CursorKind.OBJC_ENCODE_EXPR = CursorKind(138)
# ObjCSelectorExpr used for in Objective-C.
CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139)
# Objective-C's protocol expression.
CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140)
# An Objective-C "bridged" cast expression, which casts between
# Objective-C pointers and C pointers, transferring ownership in the process.
#
# \code
# NSString *str = (__bridge_transfer NSString *)CFCreateString();
# \endcode
CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141)
# Represents a C++0x pack expansion that produces a sequence of
# expressions.
#
# A pack expansion expression contains a pattern (which itself is an
# expression) followed by an ellipsis. For example:
CursorKind.PACK_EXPANSION_EXPR = CursorKind(142)
# Represents an expression that computes the length of a parameter
# pack.
CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143)
# Represents a C++ lambda expression that produces a local function
# object.
#
# \code
# void abssort(float *x, unsigned N) {
# std::sort(x, x + N,
# [](float a, float b) {
# return std::abs(a) < std::abs(b);
# });
# }
# \endcode
CursorKind.LAMBDA_EXPR = CursorKind(144)
# Objective-c Boolean Literal.
CursorKind.OBJ_BOOL_LITERAL_EXPR = CursorKind(145)
# Represents the "self" expression in a ObjC method.
CursorKind.OBJ_SELF_EXPR = CursorKind(146)
# A statement whose specific kind is not exposed via this interface.
#
# Unexposed statements have the same operations as any other kind of statement;
# one can extract their location information, spelling, children, etc. However,
# the specific kind of the statement is not reported.
CursorKind.UNEXPOSED_STMT = CursorKind(200)
# A labelled statement in a function.
CursorKind.LABEL_STMT = CursorKind(201)
# A compound statement
CursorKind.COMPOUND_STMT = CursorKind(202)
# A case statement.
CursorKind.CASE_STMT = CursorKind(203)
# A default statement.
CursorKind.DEFAULT_STMT = CursorKind(204)
# An if statement.
CursorKind.IF_STMT = CursorKind(205)
# A switch statement.
CursorKind.SWITCH_STMT = CursorKind(206)
# A while statement.
CursorKind.WHILE_STMT = CursorKind(207)
# A do statement.
CursorKind.DO_STMT = CursorKind(208)
# A for statement.
CursorKind.FOR_STMT = CursorKind(209)
# A goto statement.
CursorKind.GOTO_STMT = CursorKind(210)
# An indirect goto statement.
CursorKind.INDIRECT_GOTO_STMT = CursorKind(211)
# A continue statement.
CursorKind.CONTINUE_STMT = CursorKind(212)
# A break statement.
CursorKind.BREAK_STMT = CursorKind(213)
# A return statement.
CursorKind.RETURN_STMT = CursorKind(214)
# A GNU-style inline assembler statement.
CursorKind.ASM_STMT = CursorKind(215)
# Objective-C's overall @try-@catch-@finally statement.
CursorKind.OBJC_AT_TRY_STMT = CursorKind(216)
# Objective-C's @catch statement.
CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217)
# Objective-C's @finally statement.
CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218)
# Objective-C's @throw statement.
CursorKind.OBJC_AT_THROW_STMT = CursorKind(219)
# Objective-C's @synchronized statement.
CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220)
# Objective-C's autorealease pool statement.
CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221)
# Objective-C's for collection statement.
CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222)
# C++'s catch statement.
CursorKind.CXX_CATCH_STMT = CursorKind(223)
# C++'s try statement.
CursorKind.CXX_TRY_STMT = CursorKind(224)
# C++'s for (* : *) statement.
CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225)
# Windows Structured Exception Handling's try statement.
CursorKind.SEH_TRY_STMT = CursorKind(226)
# Windows Structured Exception Handling's except statement.
CursorKind.SEH_EXCEPT_STMT = CursorKind(227)
# Windows Structured Exception Handling's finally statement.
CursorKind.SEH_FINALLY_STMT = CursorKind(228)
# A MS inline assembly statement extension.
CursorKind.MS_ASM_STMT = CursorKind(229)
# The null statement.
CursorKind.NULL_STMT = CursorKind(230)
# Adaptor class for mixing declarations with statements and expressions.
CursorKind.DECL_STMT = CursorKind(231)
###
# Other Kinds
# Cursor that represents the translation unit itself.
#
# The translation unit cursor exists primarily to act as the root cursor for
# traversing the contents of a translation unit.
CursorKind.TRANSLATION_UNIT = CursorKind(300)
###
# Attributes
# An attribute whoe specific kind is note exposed via this interface
CursorKind.UNEXPOSED_ATTR = CursorKind(400)
CursorKind.IB_ACTION_ATTR = CursorKind(401)
CursorKind.IB_OUTLET_ATTR = CursorKind(402)
CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403)
CursorKind.CXX_FINAL_ATTR = CursorKind(404)
CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405)
CursorKind.ANNOTATE_ATTR = CursorKind(406)
CursorKind.ASM_LABEL_ATTR = CursorKind(407)
CursorKind.PACKED_ATTR = CursorKind(408)
CursorKind.PURE_ATTR = CursorKind(409)
CursorKind.CONST_ATTR = CursorKind(410)
CursorKind.NODUPLICATE_ATTR = CursorKind(411)
CursorKind.CUDACONSTANT_ATTR = CursorKind(412)
CursorKind.CUDADEVICE_ATTR = CursorKind(413)
CursorKind.CUDAGLOBAL_ATTR = CursorKind(414)
CursorKind.CUDAHOST_ATTR = CursorKind(415)
CursorKind.CUDASHARED_ATTR = CursorKind(416)
###
# Preprocessing
CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500)
CursorKind.MACRO_DEFINITION = CursorKind(501)
CursorKind.MACRO_INSTANTIATION = CursorKind(502)
CursorKind.INCLUSION_DIRECTIVE = CursorKind(503)
###
# Extra declaration
# A module import declaration.
CursorKind.MODULE_IMPORT_DECL = CursorKind(600)
### Template Argument Kinds ###
class TemplateArgumentKind(BaseEnumeration):
"""
A TemplateArgumentKind describes the kind of entity that a template argument
represents.
"""
# The required BaseEnumeration declarations.
_kinds = []
_name_map = None
TemplateArgumentKind.NULL = TemplateArgumentKind(0)
TemplateArgumentKind.TYPE = TemplateArgumentKind(1)
TemplateArgumentKind.DECLARATION = TemplateArgumentKind(2)
TemplateArgumentKind.NULLPTR = TemplateArgumentKind(3)
TemplateArgumentKind.INTEGRAL = TemplateArgumentKind(4)
### Cursors ###
class Cursor(Structure):
"""
The Cursor class represents a reference to an element within the AST. It
acts as a kind of iterator.
"""
_fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
@staticmethod
def from_location(tu, location):
# We store a reference to the TU in the instance so the TU won't get
# collected before the cursor.
cursor = conf.lib.clang_getCursor(tu, location)
cursor._tu = tu
return cursor
def __eq__(self, other):
return conf.lib.clang_equalCursors(self, other)
def __ne__(self, other):
return not self.__eq__(other)
def is_definition(self):
"""
Returns true if the declaration pointed at by the cursor is also a
definition of that entity.
"""
return conf.lib.clang_isCursorDefinition(self)
def is_static_method(self):
"""Returns True if the cursor refers to a C++ member function or member
function template that is declared 'static'.
"""
return conf.lib.clang_CXXMethod_isStatic(self)
def get_definition(self):
"""
If the cursor is a reference to a declaration or a declaration of
some entity, return a cursor that points to the definition of that
entity.
"""
# TODO: Should probably check that this is either a reference or
# declaration prior to issuing the lookup.
return conf.lib.clang_getCursorDefinition(self)
def get_usr(self):
"""Return the Unified Symbol Resultion (USR) for the entity referenced
by the given cursor (or None).
A Unified Symbol Resolution (USR) is a string that identifies a
particular entity (function, class, variable, etc.) within a
program. USRs can be compared across translation units to determine,
e.g., when references in one translation refer to an entity defined in
another translation unit."""
return conf.lib.clang_getCursorUSR(self)
@property
def kind(self):
"""Return the kind of this cursor."""
return CursorKind.from_id(self._kind_id)
@property
def spelling(self):
"""Return the spelling of the entity pointed at by the cursor."""
if not hasattr(self, '_spelling'):
self._spelling = conf.lib.clang_getCursorSpelling(self)
return self._spelling
@property
def displayname(self):
"""
Return the display name for the entity referenced by this cursor.
The display name contains extra information that helps identify the
cursor, such as the parameters of a function or template or the
arguments of a class template specialization.
"""
if not hasattr(self, '_displayname'):
self._displayname = conf.lib.clang_getCursorDisplayName(self)
return self._displayname
@property
def mangled_name(self):
"""Return the mangled name for the entity referenced by this cursor."""
if not hasattr(self, '_mangled_name'):
self._mangled_name = conf.lib.clang_Cursor_getMangling(self)
return self._mangled_name
@property
def location(self):
"""
Return the source location (the starting character) of the entity
pointed at by the cursor.
"""
if not hasattr(self, '_loc'):
self._loc = conf.lib.clang_getCursorLocation(self)
return self._loc
@property
def extent(self):
"""
Return the source range (the range of text) occupied by the entity
pointed at by the cursor.
"""
if not hasattr(self, '_extent'):
self._extent = conf.lib.clang_getCursorExtent(self)
return self._extent
@property
def storage_class(self):
"""
Retrieves the storage class (if any) of the entity pointed at by the
cursor.
"""
if not hasattr(self, '_storage_class'):
self._storage_class = conf.lib.clang_Cursor_getStorageClass(self)
return StorageClass.from_id(self._storage_class)
@property
def access_specifier(self):
"""
Retrieves the access specifier (if any) of the entity pointed at by the
cursor.
"""
if not hasattr(self, '_access_specifier'):
self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self)
return AccessSpecifier.from_id(self._access_specifier)
@property
def type(self):
"""
Retrieve the Type (if any) of the entity pointed at by the cursor.
"""
if not hasattr(self, '_type'):
self._type = conf.lib.clang_getCursorType(self)
return self._type
@property
def canonical(self):
"""Return the canonical Cursor corresponding to this Cursor.
The canonical cursor is the cursor which is representative for the
underlying entity. For example, if you have multiple forward
declarations for the same class, the canonical cursor for the forward
declarations will be identical.
"""
if not hasattr(self, '_canonical'):
self._canonical = conf.lib.clang_getCanonicalCursor(self)
return self._canonical
@property
def result_type(self):
"""Retrieve the Type of the result for this Cursor."""
if not hasattr(self, '_result_type'):
self._result_type = conf.lib.clang_getResultType(self.type)
return self._result_type
@property
def underlying_typedef_type(self):
"""Return the underlying type of a typedef declaration.
Returns a Type for the typedef this cursor is a declaration for. If
the current cursor is not a typedef, this raises.
"""
if not hasattr(self, '_underlying_type'):
assert self.kind.is_declaration()
self._underlying_type = \
conf.lib.clang_getTypedefDeclUnderlyingType(self)
return self._underlying_type
@property
def enum_type(self):
"""Return the integer type of an enum declaration.
Returns a Type corresponding to an integer. If the cursor is not for an
enum, this raises.
"""
if not hasattr(self, '_enum_type'):
assert self.kind == CursorKind.ENUM_DECL
self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self)
return self._enum_type
@property
def enum_value(self):
"""Return the value of an enum constant."""
if not hasattr(self, '_enum_value'):
assert self.kind == CursorKind.ENUM_CONSTANT_DECL
# Figure out the underlying type of the enum to know if it
# is a signed or unsigned quantity.
underlying_type = self.type
if underlying_type.kind == TypeKind.ENUM:
underlying_type = underlying_type.get_declaration().enum_type
if underlying_type.kind in (TypeKind.CHAR_U,
TypeKind.UCHAR,
TypeKind.CHAR16,
TypeKind.CHAR32,
TypeKind.USHORT,
TypeKind.UINT,
TypeKind.ULONG,
TypeKind.ULONGLONG,
TypeKind.UINT128):
self._enum_value = \
conf.lib.clang_getEnumConstantDeclUnsignedValue(self)
else:
self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self)
return self._enum_value
@property
def objc_type_encoding(self):
"""Return the Objective-C type encoding as a str."""
if not hasattr(self, '_objc_type_encoding'):
self._objc_type_encoding = \
conf.lib.clang_getDeclObjCTypeEncoding(self)
return self._objc_type_encoding
@property
def hash(self):
"""Returns a hash of the cursor as an int."""
if not hasattr(self, '_hash'):
self._hash = conf.lib.clang_hashCursor(self)
return self._hash
@property
def semantic_parent(self):
"""Return the semantic parent for this cursor."""
if not hasattr(self, '_semantic_parent'):
self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self)
return self._semantic_parent
@property
def lexical_parent(self):
"""Return the lexical parent for this cursor."""
if not hasattr(self, '_lexical_parent'):
self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self)
return self._lexical_parent
@property
def translation_unit(self):
"""Returns the TranslationUnit to which this Cursor belongs."""
# If this triggers an AttributeError, the instance was not properly
# created.
return self._tu
@property
def referenced(self):
"""
For a cursor that is a reference, returns a cursor
representing the entity that it references.
"""
if not hasattr(self, '_referenced'):
self._referenced = conf.lib.clang_getCursorReferenced(self)
return self._referenced
@property
def brief_comment(self):
"""Returns the brief comment text associated with that Cursor"""
return conf.lib.clang_Cursor_getBriefCommentText(self)
@property
def raw_comment(self):
"""Returns the raw comment text associated with that Cursor"""
return conf.lib.clang_Cursor_getRawCommentText(self)
def get_arguments(self):
"""Return an iterator for accessing the arguments of this cursor."""
num_args = conf.lib.clang_Cursor_getNumArguments(self)
for i in range(0, num_args):
yield conf.lib.clang_Cursor_getArgument(self, i)
def get_num_template_arguments(self):
"""Returns the number of template args associated with this cursor."""
return conf.lib.clang_Cursor_getNumTemplateArguments(self)
def get_template_argument_kind(self, num):
"""Returns the TemplateArgumentKind for the indicated template
argument."""
return conf.lib.clang_Cursor_getTemplateArgumentKind(self, num)
def get_template_argument_type(self, num):
"""Returns the CXType for the indicated template argument."""
return conf.lib.clang_Cursor_getTemplateArgumentType(self, num)
def get_template_argument_value(self, num):
"""Returns the value of the indicated arg as a signed 64b integer."""
return conf.lib.clang_Cursor_getTemplateArgumentValue(self, num)
def get_template_argument_unsigned_value(self, num):
"""Returns the value of the indicated arg as an unsigned 64b integer."""
return conf.lib.clang_Cursor_getTemplateArgumentUnsignedValue(self, num)
def get_children(self):
"""Return an iterator for accessing the children of this cursor."""
# FIXME: Expose iteration from CIndex, PR6125.
def visitor(child, parent, children):
# FIXME: Document this assertion in API.
# FIXME: There should just be an isNull method.
assert child != conf.lib.clang_getNullCursor()
# Create reference to TU so it isn't GC'd before Cursor.
child._tu = self._tu
children.append(child)
return 1 # continue
children = []
conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
children)
return iter(children)
def walk_preorder(self):
"""Depth-first preorder walk over the cursor and its descendants.
Yields cursors.
"""
yield self
for child in self.get_children():
for descendant in child.walk_preorder():
yield descendant
def get_tokens(self):
"""Obtain Token instances formulating that compose this Cursor.
This is a generator for Token instances. It returns all tokens which
occupy the extent this cursor occupies.
"""
return TokenGroup.get_tokens(self._tu, self.extent)
def get_field_offsetof(self):
"""Returns the offsetof the FIELD_DECL pointed by this Cursor."""
return conf.lib.clang_Cursor_getOffsetOfField(self)
def is_anonymous(self):
"""
Check if the record is anonymous.
"""
if self.kind == CursorKind.FIELD_DECL:
return self.type.get_declaration().is_anonymous()
return conf.lib.clang_Cursor_isAnonymous(self)
def is_bitfield(self):
"""
Check if the field is a bitfield.
"""
return conf.lib.clang_Cursor_isBitField(self)
def get_bitfield_width(self):
"""
Retrieve the width of a bitfield.
"""
return conf.lib.clang_getFieldDeclBitWidth(self)
@staticmethod
def from_result(res, fn, args):
assert isinstance(res, Cursor)
# FIXME: There should just be an isNull method.
if res == conf.lib.clang_getNullCursor():
return None
# Store a reference to the TU in the Python object so it won't get GC'd
# before the Cursor.
tu = None
for arg in args:
if isinstance(arg, TranslationUnit):
tu = arg
break
if hasattr(arg, 'translation_unit'):
tu = arg.translation_unit
break
assert tu is not None
res._tu = tu
return res
@staticmethod
def from_cursor_result(res, fn, args):
assert isinstance(res, Cursor)
if res == conf.lib.clang_getNullCursor():
return None
res._tu = args[0]._tu
return res
class StorageClass(object):
"""
Describes the storage class of a declaration
"""
# The unique kind objects, index by id.
_kinds = []
_name_map = None
def __init__(self, value):
if value >= len(StorageClass._kinds):
StorageClass._kinds += [None] * (value - len(StorageClass._kinds) + 1)
if StorageClass._kinds[value] is not None:
raise ValueError,'StorageClass already loaded'
self.value = value
StorageClass._kinds[value] = self
StorageClass._name_map = None
def from_param(self):
return self.value
@property
def name(self):
"""Get the enumeration name of this storage class."""
if self._name_map is None:
self._name_map = {}
for key,value in StorageClass.__dict__.items():
if isinstance(value,StorageClass):
self._name_map[value] = key
return self._name_map[self]
@staticmethod
def from_id(id):
if id >= len(StorageClass._kinds) or not StorageClass._kinds[id]:
raise ValueError,'Unknown storage class %d' % id
return StorageClass._kinds[id]
def __repr__(self):
return 'StorageClass.%s' % (self.name,)
StorageClass.INVALID = StorageClass(0)
StorageClass.NONE = StorageClass(1)
StorageClass.EXTERN = StorageClass(2)
StorageClass.STATIC = StorageClass(3)
StorageClass.PRIVATEEXTERN = StorageClass(4)
StorageClass.OPENCLWORKGROUPLOCAL = StorageClass(5)
StorageClass.AUTO = StorageClass(6)
StorageClass.REGISTER = StorageClass(7)
### C++ access specifiers ###
class AccessSpecifier(BaseEnumeration):
"""
Describes the access of a C++ class member
"""
# The unique kind objects, index by id.
_kinds = []
_name_map = None
def from_param(self):
return self.value
def __repr__(self):
return 'AccessSpecifier.%s' % (self.name,)
AccessSpecifier.INVALID = AccessSpecifier(0)
AccessSpecifier.PUBLIC = AccessSpecifier(1)
AccessSpecifier.PROTECTED = AccessSpecifier(2)
AccessSpecifier.PRIVATE = AccessSpecifier(3)
AccessSpecifier.NONE = AccessSpecifier(4)
### Type Kinds ###
class TypeKind(BaseEnumeration):
"""
Describes the kind of type.
"""
# The unique kind objects, indexed by id.
_kinds = []
_name_map = None
@property
def spelling(self):
"""Retrieve the spelling of this TypeKind."""
return conf.lib.clang_getTypeKindSpelling(self.value)
def __repr__(self):
return 'TypeKind.%s' % (self.name,)
TypeKind.INVALID = TypeKind(0)
TypeKind.UNEXPOSED = TypeKind(1)
TypeKind.VOID = TypeKind(2)
TypeKind.BOOL = TypeKind(3)
TypeKind.CHAR_U = TypeKind(4)
TypeKind.UCHAR = TypeKind(5)
TypeKind.CHAR16 = TypeKind(6)
TypeKind.CHAR32 = TypeKind(7)
TypeKind.USHORT = TypeKind(8)
TypeKind.UINT = TypeKind(9)
TypeKind.ULONG = TypeKind(10)
TypeKind.ULONGLONG = TypeKind(11)
TypeKind.UINT128 = TypeKind(12)
TypeKind.CHAR_S = TypeKind(13)
TypeKind.SCHAR = TypeKind(14)
TypeKind.WCHAR = TypeKind(15)
TypeKind.SHORT = TypeKind(16)
TypeKind.INT = TypeKind(17)
TypeKind.LONG = TypeKind(18)
TypeKind.LONGLONG = TypeKind(19)
TypeKind.INT128 = TypeKind(20)
TypeKind.FLOAT = TypeKind(21)
TypeKind.DOUBLE = TypeKind(22)
TypeKind.LONGDOUBLE = TypeKind(23)
TypeKind.NULLPTR = TypeKind(24)
TypeKind.OVERLOAD = TypeKind(25)
TypeKind.DEPENDENT = TypeKind(26)
TypeKind.OBJCID = TypeKind(27)
TypeKind.OBJCCLASS = TypeKind(28)
TypeKind.OBJCSEL = TypeKind(29)
TypeKind.COMPLEX = TypeKind(100)
TypeKind.POINTER = TypeKind(101)
TypeKind.BLOCKPOINTER = TypeKind(102)
TypeKind.LVALUEREFERENCE = TypeKind(103)
TypeKind.RVALUEREFERENCE = TypeKind(104)
TypeKind.RECORD = TypeKind(105)
TypeKind.ENUM = TypeKind(106)
TypeKind.TYPEDEF = TypeKind(107)
TypeKind.OBJCINTERFACE = TypeKind(108)
TypeKind.OBJCOBJECTPOINTER = TypeKind(109)
TypeKind.FUNCTIONNOPROTO = TypeKind(110)
TypeKind.FUNCTIONPROTO = TypeKind(111)
TypeKind.CONSTANTARRAY = TypeKind(112)
TypeKind.VECTOR = TypeKind(113)
TypeKind.INCOMPLETEARRAY = TypeKind(114)
TypeKind.VARIABLEARRAY = TypeKind(115)
TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116)
TypeKind.MEMBERPOINTER = TypeKind(117)
class RefQualifierKind(BaseEnumeration):
"""Describes a specific ref-qualifier of a type."""
# The unique kind objects, indexed by id.
_kinds = []
_name_map = None
def from_param(self):
return self.value
def __repr__(self):
return 'RefQualifierKind.%s' % (self.name,)
RefQualifierKind.NONE = RefQualifierKind(0)
RefQualifierKind.LVALUE = RefQualifierKind(1)
RefQualifierKind.RVALUE = RefQualifierKind(2)
class Type(Structure):
"""
The type of an element in the abstract syntax tree.
"""
_fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)]
@property
def kind(self):
"""Return the kind of this type."""
return TypeKind.from_id(self._kind_id)
def argument_types(self):
"""Retrieve a container for the non-variadic arguments for this type.
The returned object is iterable and indexable. Each item in the
container is a Type instance.
"""
class ArgumentsIterator(collections.Sequence):
def __init__(self, parent):
self.parent = parent
self.length = None
def __len__(self):
if self.length is None:
self.length = conf.lib.clang_getNumArgTypes(self.parent)
return self.length
def __getitem__(self, key):
# FIXME Support slice objects.
if not isinstance(key, int):
raise TypeError("Must supply a non-negative int.")
if key < 0:
raise IndexError("Only non-negative indexes are accepted.")
if key >= len(self):
raise IndexError("Index greater than container length: "
"%d > %d" % ( key, len(self) ))
result = conf.lib.clang_getArgType(self.parent, key)
if result.kind == TypeKind.INVALID:
raise IndexError("Argument could not be retrieved.")
return result
assert self.kind == TypeKind.FUNCTIONPROTO
return ArgumentsIterator(self)
@property
def element_type(self):
"""Retrieve the Type of elements within this Type.
If accessed on a type that is not an array, complex, or vector type, an
exception will be raised.
"""
result = conf.lib.clang_getElementType(self)
if result.kind == TypeKind.INVALID:
raise Exception('Element type not available on this type.')
return result
@property
def element_count(self):
"""Retrieve the number of elements in this type.
Returns an int.
If the Type is not an array or vector, this raises.
"""
result = conf.lib.clang_getNumElements(self)
if result < 0:
raise Exception('Type does not have elements.')
return result
@property
def translation_unit(self):
"""The TranslationUnit to which this Type is associated."""
# If this triggers an AttributeError, the instance was not properly
# instantiated.
return self._tu
@staticmethod
def from_result(res, fn, args):
assert isinstance(res, Type)
tu = None
for arg in args:
if hasattr(arg, 'translation_unit'):
tu = arg.translation_unit
break
assert tu is not None
res._tu = tu
return res
def get_canonical(self):
"""
Return the canonical type for a Type.
Clang's type system explicitly models typedefs and all the
ways a specific type can be represented. The canonical type
is the underlying type with all the "sugar" removed. For
example, if 'T' is a typedef for 'int', the canonical type for
'T' would be 'int'.
"""
return conf.lib.clang_getCanonicalType(self)
def is_const_qualified(self):
"""Determine whether a Type has the "const" qualifier set.
This does not look through typedefs that may have added "const"
at a different level.
"""
return conf.lib.clang_isConstQualifiedType(self)
def is_volatile_qualified(self):
"""Determine whether a Type has the "volatile" qualifier set.
This does not look through typedefs that may have added "volatile"
at a different level.
"""
return conf.lib.clang_isVolatileQualifiedType(self)
def is_restrict_qualified(self):
"""Determine whether a Type has the "restrict" qualifier set.
This does not look through typedefs that may have added "restrict" at
a different level.
"""
return conf.lib.clang_isRestrictQualifiedType(self)
def is_function_variadic(self):
"""Determine whether this function Type is a variadic function type."""
assert self.kind == TypeKind.FUNCTIONPROTO
return conf.lib.clang_isFunctionTypeVariadic(self)
def is_pod(self):
"""Determine whether this Type represents plain old data (POD)."""
return conf.lib.clang_isPODType(self)
def get_pointee(self):
"""
For pointer types, returns the type of the pointee.
"""
return conf.lib.clang_getPointeeType(self)
def get_declaration(self):
"""
Return the cursor for the declaration of the given type.
"""
return conf.lib.clang_getTypeDeclaration(self)
def get_result(self):
"""
Retrieve the result type associated with a function type.
"""
return conf.lib.clang_getResultType(self)
def get_array_element_type(self):
"""
Retrieve the type of the elements of the array type.
"""
return conf.lib.clang_getArrayElementType(self)
def get_array_size(self):
"""
Retrieve the size of the constant array.
"""
return conf.lib.clang_getArraySize(self)
def get_class_type(self):
"""
Retrieve the class type of the member pointer type.
"""
return conf.lib.clang_Type_getClassType(self)
def get_align(self):
"""
Retrieve the alignment of the record.
"""
return conf.lib.clang_Type_getAlignOf(self)
def get_size(self):
"""
Retrieve the size of the record.
"""
return conf.lib.clang_Type_getSizeOf(self)
def get_offset(self, fieldname):
"""
Retrieve the offset of a field in the record.
"""
return conf.lib.clang_Type_getOffsetOf(self, c_char_p(fieldname))
def get_ref_qualifier(self):
"""
Retrieve the ref-qualifier of the type.
"""
return RefQualifierKind.from_id(
conf.lib.clang_Type_getCXXRefQualifier(self))
def get_fields(self):
"""Return an iterator for accessing the fields of this type."""
def visitor(field, children):
assert field != conf.lib.clang_getNullCursor()
# Create reference to TU so it isn't GC'd before Cursor.
field._tu = self._tu
fields.append(field)
return 1 # continue
fields = []
conf.lib.clang_Type_visitFields(self,
callbacks['fields_visit'](visitor), fields)
return iter(fields)
@property
def spelling(self):
"""Retrieve the spelling of this Type."""
return conf.lib.clang_getTypeSpelling(self)
def __eq__(self, other):
if type(other) != type(self):
return False
return conf.lib.clang_equalTypes(self, other)
def __ne__(self, other):
return not self.__eq__(other)
## CIndex Objects ##
# CIndex objects (derived from ClangObject) are essentially lightweight
# wrappers attached to some underlying object, which is exposed via CIndex as
# a void*.
class ClangObject(object):
"""
A helper for Clang objects. This class helps act as an intermediary for
the ctypes library and the Clang CIndex library.
"""
def __init__(self, obj):
assert isinstance(obj, c_object_p) and obj
self.obj = self._as_parameter_ = obj
def from_param(self):
return self._as_parameter_
class _CXUnsavedFile(Structure):
"""Helper for passing unsaved file arguments."""
_fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)]
# Functions calls through the python interface are rather slow. Fortunately,
# for most symboles, we do not need to perform a function call. Their spelling
# never changes and is consequently provided by this spelling cache.
SpellingCache = {
# 0: CompletionChunk.Kind("Optional"),
# 1: CompletionChunk.Kind("TypedText"),
# 2: CompletionChunk.Kind("Text"),
# 3: CompletionChunk.Kind("Placeholder"),
# 4: CompletionChunk.Kind("Informative"),
# 5 : CompletionChunk.Kind("CurrentParameter"),
6: '(', # CompletionChunk.Kind("LeftParen"),
7: ')', # CompletionChunk.Kind("RightParen"),
8: '[', # CompletionChunk.Kind("LeftBracket"),
9: ']', # CompletionChunk.Kind("RightBracket"),
10: '{', # CompletionChunk.Kind("LeftBrace"),
11: '}', # CompletionChunk.Kind("RightBrace"),
12: '<', # CompletionChunk.Kind("LeftAngle"),
13: '>', # CompletionChunk.Kind("RightAngle"),
14: ', ', # CompletionChunk.Kind("Comma"),
# 15: CompletionChunk.Kind("ResultType"),
16: ':', # CompletionChunk.Kind("Colon"),
17: ';', # CompletionChunk.Kind("SemiColon"),
18: '=', # CompletionChunk.Kind("Equal"),
19: ' ', # CompletionChunk.Kind("HorizontalSpace"),
# 20: CompletionChunk.Kind("VerticalSpace")
}
class CompletionChunk:
class Kind:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return "<ChunkKind: %s>" % self
def __init__(self, completionString, key):
self.cs = completionString
self.key = key
self.__kindNumberCache = -1
def __repr__(self):
return "{'" + self.spelling + "', " + str(self.kind) + "}"
@CachedProperty
def spelling(self):
if self.__kindNumber in SpellingCache:
return SpellingCache[self.__kindNumber]
return conf.lib.clang_getCompletionChunkText(self.cs, self.key).spelling
# We do not use @CachedProperty here, as the manual implementation is
# apparently still significantly faster. Please profile carefully if you
# would like to add CachedProperty back.
@property
def __kindNumber(self):
if self.__kindNumberCache == -1:
self.__kindNumberCache = \
conf.lib.clang_getCompletionChunkKind(self.cs, self.key)
return self.__kindNumberCache
@CachedProperty
def kind(self):
return completionChunkKindMap[self.__kindNumber]
@CachedProperty
def string(self):
res = conf.lib.clang_getCompletionChunkCompletionString(self.cs,
self.key)
if (res):
return CompletionString(res)
else:
None
def isKindOptional(self):
return self.__kindNumber == 0
def isKindTypedText(self):
return self.__kindNumber == 1
def isKindPlaceHolder(self):
return self.__kindNumber == 3
def isKindInformative(self):
return self.__kindNumber == 4
def isKindResultType(self):
return self.__kindNumber == 15
completionChunkKindMap = {
0: CompletionChunk.Kind("Optional"),
1: CompletionChunk.Kind("TypedText"),
2: CompletionChunk.Kind("Text"),
3: CompletionChunk.Kind("Placeholder"),
4: CompletionChunk.Kind("Informative"),
5: CompletionChunk.Kind("CurrentParameter"),
6: CompletionChunk.Kind("LeftParen"),
7: CompletionChunk.Kind("RightParen"),
8: CompletionChunk.Kind("LeftBracket"),
9: CompletionChunk.Kind("RightBracket"),
10: CompletionChunk.Kind("LeftBrace"),
11: CompletionChunk.Kind("RightBrace"),
12: CompletionChunk.Kind("LeftAngle"),
13: CompletionChunk.Kind("RightAngle"),
14: CompletionChunk.Kind("Comma"),
15: CompletionChunk.Kind("ResultType"),
16: CompletionChunk.Kind("Colon"),
17: CompletionChunk.Kind("SemiColon"),
18: CompletionChunk.Kind("Equal"),
19: CompletionChunk.Kind("HorizontalSpace"),
20: CompletionChunk.Kind("VerticalSpace")}
class CompletionString(ClangObject):
class Availability:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return "<Availability: %s>" % self
def __len__(self):
return self.num_chunks
@CachedProperty
def num_chunks(self):
return conf.lib.clang_getNumCompletionChunks(self.obj)
def __getitem__(self, key):
if self.num_chunks <= key:
raise IndexError
return CompletionChunk(self.obj, key)
@property
def priority(self):
return conf.lib.clang_getCompletionPriority(self.obj)
@property
def availability(self):
res = conf.lib.clang_getCompletionAvailability(self.obj)
return availabilityKinds[res]
@property
def briefComment(self):
if conf.function_exists("clang_getCompletionBriefComment"):
return conf.lib.clang_getCompletionBriefComment(self.obj)
return _CXString()
def __repr__(self):
return " | ".join([str(a) for a in self]) \
+ " || Priority: " + str(self.priority) \
+ " || Availability: " + str(self.availability) \
+ " || Brief comment: " + str(self.briefComment.spelling)
availabilityKinds = {
0: CompletionChunk.Kind("Available"),
1: CompletionChunk.Kind("Deprecated"),
2: CompletionChunk.Kind("NotAvailable"),
3: CompletionChunk.Kind("NotAccessible")}
class CodeCompletionResult(Structure):
_fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
def __repr__(self):
return str(CompletionString(self.completionString))
@property
def kind(self):
return CursorKind.from_id(self.cursorKind)
@property
def string(self):
return CompletionString(self.completionString)
class CCRStructure(Structure):
_fields_ = [('results', POINTER(CodeCompletionResult)),
('numResults', c_int)]
def __len__(self):
return self.numResults
def __getitem__(self, key):
if len(self) <= key:
raise IndexError
return self.results[key]
class CodeCompletionResults(ClangObject):
def __init__(self, ptr):
assert isinstance(ptr, POINTER(CCRStructure)) and ptr
self.ptr = self._as_parameter_ = ptr
def from_param(self):
return self._as_parameter_
def __del__(self):
conf.lib.clang_disposeCodeCompleteResults(self)
@property
def results(self):
return self.ptr.contents
@property
def diagnostics(self):
class DiagnosticsItr:
def __init__(self, ccr):
self.ccr= ccr
def __len__(self):
return int(\
conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr))
def __getitem__(self, key):
return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key)
return DiagnosticsItr(self)
class Index(ClangObject):
"""
The Index type provides the primary interface to the Clang CIndex library,
primarily by providing an interface for reading and parsing translation
units.
"""
@staticmethod
def create(excludeDecls=False):
"""
Create a new Index.
Parameters:
excludeDecls -- Exclude local declarations from translation units.
"""
return Index(conf.lib.clang_createIndex(excludeDecls, 0))
def __del__(self):
conf.lib.clang_disposeIndex(self)
def read(self, path):
"""Load a TranslationUnit from the given AST file."""
return TranslationUnit.from_ast_file(path, self)
def parse(self, path, args=None, unsaved_files=None, options = 0):
"""Load the translation unit from the given source code file by running
clang and generating the AST before loading. Additional command line
parameters can be passed to clang via the args parameter.
In-memory contents for files can be provided by passing a list of pairs
to as unsaved_files, the first item should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
If an error was encountered during parsing, a TranslationUnitLoadError
will be raised.
"""
return TranslationUnit.from_source(path, args, unsaved_files, options,
self)
class TranslationUnit(ClangObject):
"""Represents a source code translation unit.
This is one of the main types in the API. Any time you wish to interact
with Clang's representation of a source file, you typically start with a
translation unit.
"""
# Default parsing mode.
PARSE_NONE = 0
# Instruct the parser to create a detailed processing record containing
# metadata not normally retained.
PARSE_DETAILED_PROCESSING_RECORD = 1
# Indicates that the translation unit is incomplete. This is typically used
# when parsing headers.
PARSE_INCOMPLETE = 2
# Instruct the parser to create a pre-compiled preamble for the translation
# unit. This caches the preamble (included files at top of source file).
# This is useful if the translation unit will be reparsed and you don't
# want to incur the overhead of reparsing the preamble.
PARSE_PRECOMPILED_PREAMBLE = 4
# Cache code completion information on parse. This adds time to parsing but
# speeds up code completion.
PARSE_CACHE_COMPLETION_RESULTS = 8
# Flags with values 16 and 32 are deprecated and intentionally omitted.
# Do not parse function bodies. This is useful if you only care about
# searching for declarations/definitions.
PARSE_SKIP_FUNCTION_BODIES = 64
# Used to indicate that brief documentation comments should be included
# into the set of code completions returned from this translation unit.
PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128
@classmethod
def from_source(cls, filename, args=None, unsaved_files=None, options=0,
index=None):
"""Create a TranslationUnit by parsing source.
This is capable of processing source code both from files on the
filesystem as well as in-memory contents.
Command-line arguments that would be passed to clang are specified as
a list via args. These can be used to specify include paths, warnings,
etc. e.g. ["-Wall", "-I/path/to/include"].
In-memory file content can be provided via unsaved_files. This is an
iterable of 2-tuples. The first element is the str filename. The
second element defines the content. Content can be provided as str
source code or as file objects (anything with a read() method). If
a file object is being used, content will be read until EOF and the
read cursor will not be reset to its original position.
options is a bitwise or of TranslationUnit.PARSE_XXX flags which will
control parsing behavior.
index is an Index instance to utilize. If not provided, a new Index
will be created for this TranslationUnit.
To parse source from the filesystem, the filename of the file to parse
is specified by the filename argument. Or, filename could be None and
the args list would contain the filename(s) to parse.
To parse source from an in-memory buffer, set filename to the virtual
filename you wish to associate with this source (e.g. "test.c"). The
contents of that file are then provided in unsaved_files.
If an error occurs, a TranslationUnitLoadError is raised.
Please note that a TranslationUnit with parser errors may be returned.
It is the caller's responsibility to check tu.diagnostics for errors.
Also note that Clang infers the source language from the extension of
the input filename. If you pass in source code containing a C++ class
declaration with the filename "test.c" parsing will fail.
"""
if args is None:
args = []
if unsaved_files is None:
unsaved_files = []
if index is None:
index = Index.create()
args_array = None
if len(args) > 0:
args_array = (c_char_p * len(args))(* args)
unsaved_array = None
if len(unsaved_files) > 0:
unsaved_array = (_CXUnsavedFile * len(unsaved_files))()
for i, (name, contents) in enumerate(unsaved_files):
if hasattr(contents, "read"):
contents = contents.read()
unsaved_array[i].name = name
unsaved_array[i].contents = contents
unsaved_array[i].length = len(contents)
ptr = conf.lib.clang_parseTranslationUnit(index, filename, args_array,
len(args), unsaved_array,
len(unsaved_files), options)
if not ptr:
raise TranslationUnitLoadError("Error parsing translation unit.")
return cls(ptr, index=index)
@classmethod
def from_ast_file(cls, filename, index=None):
"""Create a TranslationUnit instance from a saved AST file.
A previously-saved AST file (provided with -emit-ast or
TranslationUnit.save()) is loaded from the filename specified.
If the file cannot be loaded, a TranslationUnitLoadError will be
raised.
index is optional and is the Index instance to use. If not provided,
a default Index will be created.
"""
if index is None:
index = Index.create()
ptr = conf.lib.clang_createTranslationUnit(index, filename)
if not ptr:
raise TranslationUnitLoadError(filename)
return cls(ptr=ptr, index=index)
def __init__(self, ptr, index):
"""Create a TranslationUnit instance.
TranslationUnits should be created using one of the from_* @classmethod
functions above. __init__ is only called internally.
"""
assert isinstance(index, Index)
ClangObject.__init__(self, ptr)
def __del__(self):
conf.lib.clang_disposeTranslationUnit(self)
@property
def cursor(self):
"""Retrieve the cursor that represents the given translation unit."""
return conf.lib.clang_getTranslationUnitCursor(self)
@property
def spelling(self):
"""Get the original translation unit source file name."""
return conf.lib.clang_getTranslationUnitSpelling(self)
def get_includes(self):
"""
Return an iterable sequence of FileInclusion objects that describe the
sequence of inclusions in a translation unit. The first object in
this sequence is always the input file. Note that this method will not
recursively iterate over header files included through precompiled
headers.
"""
def visitor(fobj, lptr, depth, includes):
if depth > 0:
loc = lptr.contents
includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
# Automatically adapt CIndex/ctype pointers to python objects
includes = []
conf.lib.clang_getInclusions(self,
callbacks['translation_unit_includes'](visitor), includes)
return iter(includes)
def get_file(self, filename):
"""Obtain a File from this translation unit."""
return File.from_name(self, filename)
def get_location(self, filename, position):
"""Obtain a SourceLocation for a file in this translation unit.
The position can be specified by passing:
- Integer file offset. Initial file offset is 0.
- 2-tuple of (line number, column number). Initial file position is
(0, 0)
"""
f = self.get_file(filename)
if isinstance(position, int):
return SourceLocation.from_offset(self, f, position)
return SourceLocation.from_position(self, f, position[0], position[1])
def get_extent(self, filename, locations):
"""Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
- 2 int file offsets via a 2-tuple or list.
- 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
e.g.
get_extent('foo.c', (5, 10))
get_extent('foo.c', ((1, 1), (1, 15)))
"""
f = self.get_file(filename)
if len(locations) < 2:
raise Exception('Must pass object with at least 2 elements')
start_location, end_location = locations
if hasattr(start_location, '__len__'):
start_location = SourceLocation.from_position(self, f,
start_location[0], start_location[1])
elif isinstance(start_location, int):
start_location = SourceLocation.from_offset(self, f,
start_location)
if hasattr(end_location, '__len__'):
end_location = SourceLocation.from_position(self, f,
end_location[0], end_location[1])
elif isinstance(end_location, int):
end_location = SourceLocation.from_offset(self, f, end_location)
assert isinstance(start_location, SourceLocation)
assert isinstance(end_location, SourceLocation)
return SourceRange.from_locations(start_location, end_location)
@property
def diagnostics(self):
"""
Return an iterable (and indexable) object containing the diagnostics.
"""
class DiagIterator:
def __init__(self, tu):
self.tu = tu
def __len__(self):
return int(conf.lib.clang_getNumDiagnostics(self.tu))
def __getitem__(self, key):
diag = conf.lib.clang_getDiagnostic(self.tu, key)
if not diag:
raise IndexError
return Diagnostic(diag)
return DiagIterator(self)
def reparse(self, unsaved_files=None, options=0):
"""
Reparse an already parsed translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
"""
if unsaved_files is None:
unsaved_files = []
unsaved_files_array = 0
if len(unsaved_files):
unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
for i,(name,value) in enumerate(unsaved_files):
if not isinstance(value, str):
# FIXME: It would be great to support an efficient version
# of this, one day.
value = value.read()
print value
if not isinstance(value, str):
raise TypeError,'Unexpected unsaved file contents.'
unsaved_files_array[i].name = name
unsaved_files_array[i].contents = value
unsaved_files_array[i].length = len(value)
ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
unsaved_files_array, options)
def save(self, filename):
"""Saves the TranslationUnit to a file.
This is equivalent to passing -emit-ast to the clang frontend. The
saved file can be loaded back into a TranslationUnit. Or, if it
corresponds to a header, it can be used as a pre-compiled header file.
If an error occurs while saving, a TranslationUnitSaveError is raised.
If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
the constructed TranslationUnit was not valid at time of save. In this
case, the reason(s) why should be available via
TranslationUnit.diagnostics().
filename -- The path to save the translation unit to.
"""
options = conf.lib.clang_defaultSaveOptions(self)
result = int(conf.lib.clang_saveTranslationUnit(self, filename,
options))
if result != 0:
raise TranslationUnitSaveError(result,
'Error saving TranslationUnit.')
def codeComplete(self, path, line, column, unsaved_files=None,
include_macros=False, include_code_patterns=False,
include_brief_comments=False):
"""
Code complete in this translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
"""
options = 0
if include_macros:
options += 1
if include_code_patterns:
options += 2
if include_brief_comments:
options += 4
if unsaved_files is None:
unsaved_files = []
unsaved_files_array = 0
if len(unsaved_files):
unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
for i,(name,value) in enumerate(unsaved_files):
if not isinstance(value, str):
# FIXME: It would be great to support an efficient version
# of this, one day.
value = value.read()
print value
if not isinstance(value, str):
raise TypeError,'Unexpected unsaved file contents.'
unsaved_files_array[i].name = name
unsaved_files_array[i].contents = value
unsaved_files_array[i].length = len(value)
ptr = conf.lib.clang_codeCompleteAt(self, path, line, column,
unsaved_files_array, len(unsaved_files), options)
if ptr:
return CodeCompletionResults(ptr)
return None
def get_tokens(self, locations=None, extent=None):
"""Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both are defined,
behavior is undefined.
"""
if locations is not None:
extent = SourceRange(start=locations[0], end=locations[1])
return TokenGroup.get_tokens(self, extent)
class File(ClangObject):
"""
The File class represents a particular source file that is part of a
translation unit.
"""
@staticmethod
def from_name(translation_unit, file_name):
"""Retrieve a file handle within the given translation unit."""
return File(conf.lib.clang_getFile(translation_unit, file_name))
@property
def name(self):
"""Return the complete file and path name of the file."""
return conf.lib.clang_getCString(conf.lib.clang_getFileName(self))
@property
def time(self):
"""Return the last modification time of the file."""
return conf.lib.clang_getFileTime(self)
def __str__(self):
return self.name
def __repr__(self):
return "<File: %s>" % (self.name)
@staticmethod
def from_cursor_result(res, fn, args):
assert isinstance(res, File)
# Copy a reference to the TranslationUnit to prevent premature GC.
res._tu = args[0]._tu
return res
class FileInclusion(object):
"""
The FileInclusion class represents the inclusion of one source file by
another via a '#include' directive or as the input file for the translation
unit. This class provides information about the included file, the including
file, the location of the '#include' directive and the depth of the included
file in the stack. Note that the input file has depth 0.
"""
def __init__(self, src, tgt, loc, depth):
self.source = src
self.include = tgt
self.location = loc
self.depth = depth
@property
def is_input_file(self):
"""True if the included file is the input file."""
return self.depth == 0
class CompilationDatabaseError(Exception):
"""Represents an error that occurred when working with a CompilationDatabase
Each error is associated to an enumerated value, accessible under
e.cdb_error. Consumers can compare the value with one of the ERROR_
constants in this class.
"""
# An unknown error occurred
ERROR_UNKNOWN = 0
# The database could not be loaded
ERROR_CANNOTLOADDATABASE = 1
def __init__(self, enumeration, message):
assert isinstance(enumeration, int)
if enumeration > 1:
raise Exception("Encountered undefined CompilationDatabase error "
"constant: %d. Please file a bug to have this "
"value supported." % enumeration)
self.cdb_error = enumeration
Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
class CompileCommand(object):
"""Represents the compile command used to build a file"""
def __init__(self, cmd, ccmds):
self.cmd = cmd
# Keep a reference to the originating CompileCommands
# to prevent garbage collection
self.ccmds = ccmds
@property
def directory(self):
"""Get the working directory for this CompileCommand"""
return conf.lib.clang_CompileCommand_getDirectory(self.cmd)
@property
def arguments(self):
"""
Get an iterable object providing each argument in the
command line for the compiler invocation as a _CXString.
Invariant : the first argument is the compiler executable
"""
length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd)
for i in xrange(length):
yield conf.lib.clang_CompileCommand_getArg(self.cmd, i)
class CompileCommands(object):
"""
CompileCommands is an iterable object containing all CompileCommand
that can be used for building a specific file.
"""
def __init__(self, ccmds):
self.ccmds = ccmds
def __del__(self):
conf.lib.clang_CompileCommands_dispose(self.ccmds)
def __len__(self):
return int(conf.lib.clang_CompileCommands_getSize(self.ccmds))
def __getitem__(self, i):
cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i)
if not cc:
raise IndexError
return CompileCommand(cc, self)
@staticmethod
def from_result(res, fn, args):
if not res:
return None
return CompileCommands(res)
class CompilationDatabase(ClangObject):
"""
The CompilationDatabase is a wrapper class around
clang::tooling::CompilationDatabase
It enables querying how a specific source file can be built.
"""
def __del__(self):
conf.lib.clang_CompilationDatabase_dispose(self)
@staticmethod
def from_result(res, fn, args):
if not res:
raise CompilationDatabaseError(0,
"CompilationDatabase loading failed")
return CompilationDatabase(res)
@staticmethod
def fromDirectory(buildDir):
"""Builds a CompilationDatabase from the database found in buildDir"""
errorCode = c_uint()
try:
cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir,
byref(errorCode))
except CompilationDatabaseError as e:
raise CompilationDatabaseError(int(errorCode.value),
"CompilationDatabase loading failed")
return cdb
def getCompileCommands(self, filename):
"""
Get an iterable object providing all the CompileCommands available to
build filename. Returns None if filename is not found in the database.
"""
return conf.lib.clang_CompilationDatabase_getCompileCommands(self,
filename)
def getAllCompileCommands(self):
"""
Get an iterable object providing all the CompileCommands available from
the database.
"""
return conf.lib.clang_CompilationDatabase_getAllCompileCommands(self)
class Token(Structure):
"""Represents a single token from the preprocessor.
Tokens are effectively segments of source code. Source code is first parsed
into tokens before being converted into the AST and Cursors.
Tokens are obtained from parsed TranslationUnit instances. You currently
can't create tokens manually.
"""
_fields_ = [
('int_data', c_uint * 4),
('ptr_data', c_void_p)
]
@property
def spelling(self):
"""The spelling of this token.
This is the textual representation of the token in source.
"""
return conf.lib.clang_getTokenSpelling(self._tu, self)
@property
def kind(self):
"""Obtain the TokenKind of the current token."""
return TokenKind.from_value(conf.lib.clang_getTokenKind(self))
@property
def location(self):
"""The SourceLocation this Token occurs at."""
return conf.lib.clang_getTokenLocation(self._tu, self)
@property
def extent(self):
"""The SourceRange this Token occupies."""
return conf.lib.clang_getTokenExtent(self._tu, self)
@property
def cursor(self):
"""The Cursor this Token corresponds to."""
cursor = Cursor()
conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
return cursor
# Now comes the plumbing to hook up the C library.
# Register callback types in common container.
callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p,
POINTER(SourceLocation), c_uint, py_object)
callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object)
callbacks['fields_visit'] = CFUNCTYPE(c_int, Cursor, py_object)
# Functions strictly alphabetical order.
functionList = [
("clang_annotateTokens",
[TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]),
("clang_CompilationDatabase_dispose",
[c_object_p]),
("clang_CompilationDatabase_fromDirectory",
[c_char_p, POINTER(c_uint)],
c_object_p,
CompilationDatabase.from_result),
("clang_CompilationDatabase_getAllCompileCommands",
[c_object_p],
c_object_p,
CompileCommands.from_result),
("clang_CompilationDatabase_getCompileCommands",
[c_object_p, c_char_p],
c_object_p,
CompileCommands.from_result),
("clang_CompileCommands_dispose",
[c_object_p]),
("clang_CompileCommands_getCommand",
[c_object_p, c_uint],
c_object_p),
("clang_CompileCommands_getSize",
[c_object_p],
c_uint),
("clang_CompileCommand_getArg",
[c_object_p, c_uint],
_CXString,
_CXString.from_result),
("clang_CompileCommand_getDirectory",
[c_object_p],
_CXString,
_CXString.from_result),
("clang_CompileCommand_getNumArgs",
[c_object_p],
c_uint),
("clang_codeCompleteAt",
[TranslationUnit, c_char_p, c_int, c_int, c_void_p, c_int, c_int],
POINTER(CCRStructure)),
("clang_codeCompleteGetDiagnostic",
[CodeCompletionResults, c_int],
Diagnostic),
("clang_codeCompleteGetNumDiagnostics",
[CodeCompletionResults],
c_int),
("clang_createIndex",
[c_int, c_int],
c_object_p),
("clang_createTranslationUnit",
[Index, c_char_p],
c_object_p),
("clang_CXXMethod_isPureVirtual",
[Cursor],
bool),
("clang_CXXMethod_isStatic",
[Cursor],
bool),
("clang_CXXMethod_isVirtual",
[Cursor],
bool),
("clang_defaultSaveOptions",
[TranslationUnit],
c_uint),
("clang_disposeCodeCompleteResults",
[CodeCompletionResults]),
# ("clang_disposeCXTUResourceUsage",
# [CXTUResourceUsage]),
("clang_disposeDiagnostic",
[Diagnostic]),
("clang_disposeIndex",
[Index]),
("clang_disposeString",
[_CXString]),
("clang_disposeTokens",
[TranslationUnit, POINTER(Token), c_uint]),
("clang_disposeTranslationUnit",
[TranslationUnit]),
("clang_equalCursors",
[Cursor, Cursor],
bool),
("clang_equalLocations",
[SourceLocation, SourceLocation],
bool),
("clang_equalRanges",
[SourceRange, SourceRange],
bool),
("clang_equalTypes",
[Type, Type],
bool),
("clang_getArgType",
[Type, c_uint],
Type,
Type.from_result),
("clang_getArrayElementType",
[Type],
Type,
Type.from_result),
("clang_getArraySize",
[Type],
c_longlong),
("clang_getFieldDeclBitWidth",
[Cursor],
c_int),
("clang_getCanonicalCursor",
[Cursor],
Cursor,
Cursor.from_cursor_result),
("clang_getCanonicalType",
[Type],
Type,
Type.from_result),
("clang_getCompletionAvailability",
[c_void_p],
c_int),
("clang_getCompletionBriefComment",
[c_void_p],
_CXString),
("clang_getCompletionChunkCompletionString",
[c_void_p, c_int],
c_object_p),
("clang_getCompletionChunkKind",
[c_void_p, c_int],
c_int),
("clang_getCompletionChunkText",
[c_void_p, c_int],
_CXString),
("clang_getCompletionPriority",
[c_void_p],
c_int),
("clang_getCString",
[_CXString],
c_char_p),
("clang_getCursor",
[TranslationUnit, SourceLocation],
Cursor),
("clang_getCursorDefinition",
[Cursor],
Cursor,
Cursor.from_result),
("clang_getCursorDisplayName",
[Cursor],
_CXString,
_CXString.from_result),
("clang_getCursorExtent",
[Cursor],
SourceRange),
("clang_getCursorLexicalParent",
[Cursor],
Cursor,
Cursor.from_cursor_result),
("clang_getCursorLocation",
[Cursor],
SourceLocation),
("clang_getCursorReferenced",
[Cursor],
Cursor,
Cursor.from_result),
("clang_getCursorReferenceNameRange",
[Cursor, c_uint, c_uint],
SourceRange),
("clang_getCursorSemanticParent",
[Cursor],
Cursor,
Cursor.from_cursor_result),
("clang_getCursorSpelling",
[Cursor],
_CXString,
_CXString.from_result),
("clang_getCursorType",
[Cursor],
Type,
Type.from_result),
("clang_getCursorUSR",
[Cursor],
_CXString,
_CXString.from_result),
("clang_Cursor_getMangling",
[Cursor],
_CXString,
_CXString.from_result),
# ("clang_getCXTUResourceUsage",
# [TranslationUnit],
# CXTUResourceUsage),
("clang_getCXXAccessSpecifier",
[Cursor],
c_uint),
("clang_getDeclObjCTypeEncoding",
[Cursor],
_CXString,
_CXString.from_result),
("clang_getDiagnostic",
[c_object_p, c_uint],
c_object_p),
("clang_getDiagnosticCategory",
[Diagnostic],
c_uint),
("clang_getDiagnosticCategoryText",
[Diagnostic],
_CXString,
_CXString.from_result),
("clang_getDiagnosticFixIt",
[Diagnostic, c_uint, POINTER(SourceRange)],
_CXString,
_CXString.from_result),
("clang_getDiagnosticLocation",
[Diagnostic],
SourceLocation),
("clang_getDiagnosticNumFixIts",
[Diagnostic],
c_uint),
("clang_getDiagnosticNumRanges",
[Diagnostic],
c_uint),
("clang_getDiagnosticOption",
[Diagnostic, POINTER(_CXString)],
_CXString,
_CXString.from_result),
("clang_getDiagnosticRange",
[Diagnostic, c_uint],
SourceRange),
("clang_getDiagnosticSeverity",
[Diagnostic],
c_int),
("clang_getDiagnosticSpelling",
[Diagnostic],
_CXString,
_CXString.from_result),
("clang_getElementType",
[Type],
Type,
Type.from_result),
("clang_getEnumConstantDeclUnsignedValue",
[Cursor],
c_ulonglong),
("clang_getEnumConstantDeclValue",
[Cursor],
c_longlong),
("clang_getEnumDeclIntegerType",
[Cursor],
Type,
Type.from_result),
("clang_getFile",
[TranslationUnit, c_char_p],
c_object_p),
("clang_getFileName",
[File],
_CXString), # TODO go through _CXString.from_result?
("clang_getFileTime",
[File],
c_uint),
("clang_getIBOutletCollectionType",
[Cursor],
Type,
Type.from_result),
("clang_getIncludedFile",
[Cursor],
File,
File.from_cursor_result),
("clang_getInclusions",
[TranslationUnit, callbacks['translation_unit_includes'], py_object]),
("clang_getInstantiationLocation",
[SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint),
POINTER(c_uint)]),
("clang_getLocation",
[TranslationUnit, File, c_uint, c_uint],
SourceLocation),
("clang_getLocationForOffset",
[TranslationUnit, File, c_uint],
SourceLocation),
("clang_getNullCursor",
None,
Cursor),
("clang_getNumArgTypes",
[Type],
c_uint),
("clang_getNumCompletionChunks",
[c_void_p],
c_int),
("clang_getNumDiagnostics",
[c_object_p],
c_uint),
("clang_getNumElements",
[Type],
c_longlong),
("clang_getNumOverloadedDecls",
[Cursor],
c_uint),
("clang_getOverloadedDecl",
[Cursor, c_uint],
Cursor,
Cursor.from_cursor_result),
("clang_getPointeeType",
[Type],
Type,
Type.from_result),
("clang_getRange",
[SourceLocation, SourceLocation],
SourceRange),
("clang_getRangeEnd",
[SourceRange],
SourceLocation),
("clang_getRangeStart",
[SourceRange],
SourceLocation),
("clang_getResultType",
[Type],
Type,
Type.from_result),
("clang_getSpecializedCursorTemplate",
[Cursor],
Cursor,
Cursor.from_cursor_result),
("clang_getTemplateCursorKind",
[Cursor],
c_uint),
("clang_getTokenExtent",
[TranslationUnit, Token],
SourceRange),
("clang_getTokenKind",
[Token],
c_uint),
("clang_getTokenLocation",
[TranslationUnit, Token],
SourceLocation),
("clang_getTokenSpelling",
[TranslationUnit, Token],
_CXString,
_CXString.from_result),
("clang_getTranslationUnitCursor",
[TranslationUnit],
Cursor,
Cursor.from_result),
("clang_getTranslationUnitSpelling",
[TranslationUnit],
_CXString,
_CXString.from_result),
("clang_getTUResourceUsageName",
[c_uint],
c_char_p),
("clang_getTypeDeclaration",
[Type],
Cursor,
Cursor.from_result),
("clang_getTypedefDeclUnderlyingType",
[Cursor],
Type,
Type.from_result),
("clang_getTypeKindSpelling",
[c_uint],
_CXString,
_CXString.from_result),
("clang_getTypeSpelling",
[Type],
_CXString,
_CXString.from_result),
("clang_hashCursor",
[Cursor],
c_uint),
("clang_isAttribute",
[CursorKind],
bool),
("clang_isConstQualifiedType",
[Type],
bool),
("clang_isCursorDefinition",
[Cursor],
bool),
("clang_isDeclaration",
[CursorKind],
bool),
("clang_isExpression",
[CursorKind],
bool),
("clang_isFileMultipleIncludeGuarded",
[TranslationUnit, File],
bool),
("clang_isFunctionTypeVariadic",
[Type],
bool),
("clang_isInvalid",
[CursorKind],
bool),
("clang_isPODType",
[Type],
bool),
("clang_isPreprocessing",
[CursorKind],
bool),
("clang_isReference",
[CursorKind],
bool),
("clang_isRestrictQualifiedType",
[Type],
bool),
("clang_isStatement",
[CursorKind],
bool),
("clang_isTranslationUnit",
[CursorKind],
bool),
("clang_isUnexposed",
[CursorKind],
bool),
("clang_isVirtualBase",
[Cursor],
bool),
("clang_isVolatileQualifiedType",
[Type],
bool),
("clang_parseTranslationUnit",
[Index, c_char_p, c_void_p, c_int, c_void_p, c_int, c_int],
c_object_p),
("clang_reparseTranslationUnit",
[TranslationUnit, c_int, c_void_p, c_int],
c_int),
("clang_saveTranslationUnit",
[TranslationUnit, c_char_p, c_uint],
c_int),
("clang_tokenize",
[TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]),
("clang_visitChildren",
[Cursor, callbacks['cursor_visit'], py_object],
c_uint),
("clang_Cursor_getNumArguments",
[Cursor],
c_int),
("clang_Cursor_getArgument",
[Cursor, c_uint],
Cursor,
Cursor.from_result),
("clang_Cursor_getNumTemplateArguments",
[Cursor],
c_int),
("clang_Cursor_getTemplateArgumentKind",
[Cursor, c_uint],
TemplateArgumentKind.from_id),
("clang_Cursor_getTemplateArgumentType",
[Cursor, c_uint],
Type,
Type.from_result),
("clang_Cursor_getTemplateArgumentValue",
[Cursor, c_uint],
c_longlong),
("clang_Cursor_getTemplateArgumentUnsignedValue",
[Cursor, c_uint],
c_ulonglong),
("clang_Cursor_isAnonymous",
[Cursor],
bool),
("clang_Cursor_isBitField",
[Cursor],
bool),
("clang_Cursor_getBriefCommentText",
[Cursor],
_CXString,
_CXString.from_result),
("clang_Cursor_getRawCommentText",
[Cursor],
_CXString,
_CXString.from_result),
("clang_Cursor_getOffsetOfField",
[Cursor],
c_longlong),
("clang_Type_getAlignOf",
[Type],
c_longlong),
("clang_Type_getClassType",
[Type],
Type,
Type.from_result),
("clang_Type_getOffsetOf",
[Type, c_char_p],
c_longlong),
("clang_Type_getSizeOf",
[Type],
c_longlong),
("clang_Type_getCXXRefQualifier",
[Type],
c_uint),
("clang_Type_visitFields",
[Type, callbacks['fields_visit'], py_object],
c_uint),
]
class LibclangError(Exception):
def __init__(self, message):
self.m = message
def __str__(self):
return self.m
def register_function(lib, item, ignore_errors):
# A function may not exist, if these bindings are used with an older or
# incompatible version of libclang.so.
try:
func = getattr(lib, item[0])
except AttributeError as e:
msg = str(e) + ". Please ensure that your python bindings are "\
"compatible with your libclang.so version."
if ignore_errors:
return
raise LibclangError(msg)
if len(item) >= 2:
func.argtypes = item[1]
if len(item) >= 3:
func.restype = item[2]
if len(item) == 4:
func.errcheck = item[3]
def register_functions(lib, ignore_errors):
"""Register function prototypes with a libclang library instance.
This must be called as part of library instantiation so Python knows how
to call out to the shared library.
"""
def register(item):
return register_function(lib, item, ignore_errors)
map(register, functionList)
class Config:
library_path = None
library_file = None
compatibility_check = True
loaded = False
@staticmethod
def set_library_path(path):
"""Set the path in which to search for libclang"""
if Config.loaded:
raise Exception("library path must be set before before using " \
"any other functionalities in libclang.")
Config.library_path = path
@staticmethod
def set_library_file(filename):
"""Set the exact location of libclang"""
if Config.loaded:
raise Exception("library file must be set before before using " \
"any other functionalities in libclang.")
Config.library_file = filename
@staticmethod
def set_compatibility_check(check_status):
""" Perform compatibility check when loading libclang
The python bindings are only tested and evaluated with the version of
libclang they are provided with. To ensure correct behavior a (limited)
compatibility check is performed when loading the bindings. This check
will throw an exception, as soon as it fails.
In case these bindings are used with an older version of libclang, parts
that have been stable between releases may still work. Users of the
python bindings can disable the compatibility check. This will cause
the python bindings to load, even though they are written for a newer
version of libclang. Failures now arise if unsupported or incompatible
features are accessed. The user is required to test themselves if the
features they are using are available and compatible between different
libclang versions.
"""
if Config.loaded:
raise Exception("compatibility_check must be set before before " \
"using any other functionalities in libclang.")
Config.compatibility_check = check_status
@CachedProperty
def lib(self):
lib = self.get_cindex_library()
register_functions(lib, not Config.compatibility_check)
Config.loaded = True
return lib
def get_filename(self):
if Config.library_file:
return Config.library_file
import platform
name = platform.system()
if name == 'Darwin':
file = 'libclang.dylib'
elif name == 'Windows':
file = 'libclang.dll'
else:
file = 'libclang.so'
if Config.library_path:
file = Config.library_path + '/' + file
return file
def get_cindex_library(self):
try:
library = cdll.LoadLibrary(self.get_filename())
except OSError as e:
msg = str(e) + ". To provide a path to libclang use " \
"Config.set_library_path() or " \
"Config.set_library_file()."
raise LibclangError(msg)
return library
def function_exists(self, name):
try:
getattr(self.lib, name)
except AttributeError:
return False
return True
def register_enumerations():
for name, value in clang.enumerations.TokenKinds:
TokenKind.register(value, name)
conf = Config()
register_enumerations()
__all__ = [
'Config',
'CodeCompletionResults',
'CompilationDatabase',
'CompileCommands',
'CompileCommand',
'CursorKind',
'Cursor',
'Diagnostic',
'File',
'FixIt',
'Index',
'SourceLocation',
'SourceRange',
'TokenKind',
'Token',
'TranslationUnitLoadError',
'TranslationUnit',
'TypeKind',
'Type',
]
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python | repos/DirectXShaderCompiler/tools/clang/bindings/python/clang/__init__.py | #===- __init__.py - Clang Python Bindings --------------------*- python -*--===#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#===------------------------------------------------------------------------===#
r"""
Clang Library Bindings
======================
This package provides access to the Clang compiler and libraries.
The available modules are:
cindex
Bindings for the Clang indexing library.
"""
__all__ = ['cindex']
|
0 | repos/DirectXShaderCompiler/tools/clang/bindings/python | repos/DirectXShaderCompiler/tools/clang/bindings/python/clang/enumerations.py | #===- enumerations.py - Python Enumerations ------------------*- python -*--===#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#===------------------------------------------------------------------------===#
"""
Clang Enumerations
==================
This module provides static definitions of enumerations that exist in libclang.
Enumerations are typically defined as a list of tuples. The exported values are
typically munged into other types or classes at module load time.
All enumerations are centrally defined in this file so they are all grouped
together and easier to audit. And, maybe even one day this file will be
automatically generated by scanning the libclang headers!
"""
# Maps to CXTokenKind. Note that libclang maintains a separate set of token
# enumerations from the C++ API.
TokenKinds = [
('PUNCTUATION', 0),
('KEYWORD', 1),
('IDENTIFIER', 2),
('LITERAL', 3),
('COMMENT', 4),
]
__all__ = ['TokenKinds']
|
0 | repos/DirectXShaderCompiler/tools/clang | repos/DirectXShaderCompiler/tools/clang/include/CMakeLists.txt | add_subdirectory(clang)
|
0 | repos/DirectXShaderCompiler/tools/clang/include | repos/DirectXShaderCompiler/tools/clang/include/clang-c/BuildSystem.h | /*==-- clang-c/BuildSystem.h - Utilities for use by build systems -*- C -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This header provides various utilities for use by build systems. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_CLANG_C_BUILDSYSTEM_H
#define LLVM_CLANG_C_BUILDSYSTEM_H
#include "clang-c/Platform.h"
#include "clang-c/CXErrorCode.h"
#include "clang-c/CXString.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \defgroup BUILD_SYSTEM Build system utilities
* @{
*/
/**
* \brief Return the timestamp for use with Clang's
* \c -fbuild-session-timestamp= option.
*/
CINDEX_LINKAGE unsigned long long clang_getBuildSessionTimestamp(void);
/**
* \brief Object encapsulating information about overlaying virtual
* file/directories over the real file system.
*/
typedef struct CXVirtualFileOverlayImpl *CXVirtualFileOverlay;
/**
* \brief Create a \c CXVirtualFileOverlay object.
* Must be disposed with \c clang_VirtualFileOverlay_dispose().
*
* \param options is reserved, always pass 0.
*/
CINDEX_LINKAGE CXVirtualFileOverlay
clang_VirtualFileOverlay_create(unsigned options);
/**
* \brief Map an absolute virtual file path to an absolute real one.
* The virtual path must be canonicalized (not contain "."/"..").
* \returns 0 for success, non-zero to indicate an error.
*/
CINDEX_LINKAGE enum CXErrorCode
clang_VirtualFileOverlay_addFileMapping(CXVirtualFileOverlay,
const char *virtualPath,
const char *realPath);
/**
* \brief Set the case sensitivity for the \c CXVirtualFileOverlay object.
* The \c CXVirtualFileOverlay object is case-sensitive by default, this
* option can be used to override the default.
* \returns 0 for success, non-zero to indicate an error.
*/
CINDEX_LINKAGE enum CXErrorCode
clang_VirtualFileOverlay_setCaseSensitivity(CXVirtualFileOverlay,
int caseSensitive);
/**
* \brief Write out the \c CXVirtualFileOverlay object to a char buffer.
*
* \param options is reserved, always pass 0.
* \param out_buffer_ptr pointer to receive the buffer pointer, which should be
* disposed using \c clang_free().
* \param out_buffer_size pointer to receive the buffer size.
* \returns 0 for success, non-zero to indicate an error.
*/
CINDEX_LINKAGE enum CXErrorCode
clang_VirtualFileOverlay_writeToBuffer(CXVirtualFileOverlay, unsigned options,
char **out_buffer_ptr,
unsigned *out_buffer_size);
/**
* \brief free memory allocated by libclang, such as the buffer returned by
* \c CXVirtualFileOverlay() or \c clang_ModuleMapDescriptor_writeToBuffer().
*
* \param buffer memory pointer to free.
*/
CINDEX_LINKAGE void clang_free(void *buffer);
/**
* \brief Dispose a \c CXVirtualFileOverlay object.
*/
CINDEX_LINKAGE void clang_VirtualFileOverlay_dispose(CXVirtualFileOverlay);
/**
* \brief Object encapsulating information about a module.map file.
*/
typedef struct CXModuleMapDescriptorImpl *CXModuleMapDescriptor;
/**
* \brief Create a \c CXModuleMapDescriptor object.
* Must be disposed with \c clang_ModuleMapDescriptor_dispose().
*
* \param options is reserved, always pass 0.
*/
CINDEX_LINKAGE CXModuleMapDescriptor
clang_ModuleMapDescriptor_create(unsigned options);
/**
* \brief Sets the framework module name that the module.map describes.
* \returns 0 for success, non-zero to indicate an error.
*/
CINDEX_LINKAGE enum CXErrorCode
clang_ModuleMapDescriptor_setFrameworkModuleName(CXModuleMapDescriptor,
const char *name);
/**
* \brief Sets the umbrealla header name that the module.map describes.
* \returns 0 for success, non-zero to indicate an error.
*/
CINDEX_LINKAGE enum CXErrorCode
clang_ModuleMapDescriptor_setUmbrellaHeader(CXModuleMapDescriptor,
const char *name);
/**
* \brief Write out the \c CXModuleMapDescriptor object to a char buffer.
*
* \param options is reserved, always pass 0.
* \param out_buffer_ptr pointer to receive the buffer pointer, which should be
* disposed using \c clang_free().
* \param out_buffer_size pointer to receive the buffer size.
* \returns 0 for success, non-zero to indicate an error.
*/
CINDEX_LINKAGE enum CXErrorCode
clang_ModuleMapDescriptor_writeToBuffer(CXModuleMapDescriptor, unsigned options,
char **out_buffer_ptr,
unsigned *out_buffer_size);
/**
* \brief Dispose a \c CXModuleMapDescriptor object.
*/
CINDEX_LINKAGE void clang_ModuleMapDescriptor_dispose(CXModuleMapDescriptor);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* CLANG_C_BUILD_SYSTEM_H */
|
0 | repos/DirectXShaderCompiler/tools/clang/include | repos/DirectXShaderCompiler/tools/clang/include/clang-c/CXCompilationDatabase.h | /*===-- clang-c/CXCompilationDatabase.h - Compilation database ---*- C -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This header provides a public inferface to use CompilationDatabase without *|
|* the full Clang C++ API. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_CLANG_C_CXCOMPILATIONDATABASE_H
#define LLVM_CLANG_C_CXCOMPILATIONDATABASE_H
#include "clang-c/Platform.h"
#include "clang-c/CXString.h"
#ifdef __cplusplus
extern "C" {
#endif
/** \defgroup COMPILATIONDB CompilationDatabase functions
* \ingroup CINDEX
*
* @{
*/
/**
* A compilation database holds all information used to compile files in a
* project. For each file in the database, it can be queried for the working
* directory or the command line used for the compiler invocation.
*
* Must be freed by \c clang_CompilationDatabase_dispose
*/
typedef void * CXCompilationDatabase;
/**
* \brief Contains the results of a search in the compilation database
*
* When searching for the compile command for a file, the compilation db can
* return several commands, as the file may have been compiled with
* different options in different places of the project. This choice of compile
* commands is wrapped in this opaque data structure. It must be freed by
* \c clang_CompileCommands_dispose.
*/
typedef void * CXCompileCommands;
/**
* \brief Represents the command line invocation to compile a specific file.
*/
typedef void * CXCompileCommand;
/**
* \brief Error codes for Compilation Database
*/
typedef enum {
/*
* \brief No error occurred
*/
CXCompilationDatabase_NoError = 0,
/*
* \brief Database can not be loaded
*/
CXCompilationDatabase_CanNotLoadDatabase = 1
} CXCompilationDatabase_Error;
/**
* \brief Creates a compilation database from the database found in directory
* buildDir. For example, CMake can output a compile_commands.json which can
* be used to build the database.
*
* It must be freed by \c clang_CompilationDatabase_dispose.
*/
CINDEX_LINKAGE CXCompilationDatabase
clang_CompilationDatabase_fromDirectory(const char *BuildDir,
CXCompilationDatabase_Error *ErrorCode);
/**
* \brief Free the given compilation database
*/
CINDEX_LINKAGE void
clang_CompilationDatabase_dispose(CXCompilationDatabase);
/**
* \brief Find the compile commands used for a file. The compile commands
* must be freed by \c clang_CompileCommands_dispose.
*/
CINDEX_LINKAGE CXCompileCommands
clang_CompilationDatabase_getCompileCommands(CXCompilationDatabase,
const char *CompleteFileName);
/**
* \brief Get all the compile commands in the given compilation database.
*/
CINDEX_LINKAGE CXCompileCommands
clang_CompilationDatabase_getAllCompileCommands(CXCompilationDatabase);
/**
* \brief Free the given CompileCommands
*/
CINDEX_LINKAGE void clang_CompileCommands_dispose(CXCompileCommands);
/**
* \brief Get the number of CompileCommand we have for a file
*/
CINDEX_LINKAGE unsigned
clang_CompileCommands_getSize(CXCompileCommands);
/**
* \brief Get the I'th CompileCommand for a file
*
* Note : 0 <= i < clang_CompileCommands_getSize(CXCompileCommands)
*/
CINDEX_LINKAGE CXCompileCommand
clang_CompileCommands_getCommand(CXCompileCommands, unsigned I);
/**
* \brief Get the working directory where the CompileCommand was executed from
*/
CINDEX_LINKAGE CXString
clang_CompileCommand_getDirectory(CXCompileCommand);
/**
* \brief Get the number of arguments in the compiler invocation.
*
*/
CINDEX_LINKAGE unsigned
clang_CompileCommand_getNumArgs(CXCompileCommand);
/**
* \brief Get the I'th argument value in the compiler invocations
*
* Invariant :
* - argument 0 is the compiler executable
*/
CINDEX_LINKAGE CXString
clang_CompileCommand_getArg(CXCompileCommand, unsigned I);
/**
* \brief Get the number of source mappings for the compiler invocation.
*/
CINDEX_LINKAGE unsigned
clang_CompileCommand_getNumMappedSources(CXCompileCommand);
/**
* \brief Get the I'th mapped source path for the compiler invocation.
*/
CINDEX_LINKAGE CXString
clang_CompileCommand_getMappedSourcePath(CXCompileCommand, unsigned I);
/**
* \brief Get the I'th mapped source content for the compiler invocation.
*/
CINDEX_LINKAGE CXString
clang_CompileCommand_getMappedSourceContent(CXCompileCommand, unsigned I);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include | repos/DirectXShaderCompiler/tools/clang/include/clang-c/CXErrorCode.h | /*===-- clang-c/CXErrorCode.h - C Index Error Codes --------------*- C -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This header provides the CXErrorCode enumerators. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_CLANG_C_CXERRORCODE_H
#define LLVM_CLANG_C_CXERRORCODE_H
#include "clang-c/Platform.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Error codes returned by libclang routines.
*
* Zero (\c CXError_Success) is the only error code indicating success. Other
* error codes, including not yet assigned non-zero values, indicate errors.
*/
enum CXErrorCode {
/**
* \brief No error.
*/
CXError_Success = 0,
/**
* \brief A generic error code, no further details are available.
*
* Errors of this kind can get their own specific error codes in future
* libclang versions.
*/
CXError_Failure = 1,
/**
* \brief libclang crashed while performing the requested operation.
*/
CXError_Crashed = 2,
/**
* \brief The function detected that the arguments violate the function
* contract.
*/
CXError_InvalidArguments = 3,
/**
* \brief An AST deserialization error has occurred.
*/
CXError_ASTReadError = 4
};
#ifdef __cplusplus
}
#endif
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include | repos/DirectXShaderCompiler/tools/clang/include/clang-c/module.modulemap | module Clang_C {
umbrella "."
module * { export * }
}
|
0 | repos/DirectXShaderCompiler/tools/clang/include | repos/DirectXShaderCompiler/tools/clang/include/clang-c/Platform.h | /*===-- clang-c/Platform.h - C Index platform decls -------------*- C -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This header provides platform specific macros (dllimport, deprecated, ...) *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_CLANG_C_PLATFORM_H
#define LLVM_CLANG_C_PLATFORM_H
#ifdef __cplusplus
extern "C" {
#endif
/* MSVC DLL import/export. */
#ifndef CINDEX_LINKAGE
#ifdef _MSC_VER
#ifdef _CINDEX_LIB_
#define CINDEX_LINKAGE __declspec(dllexport)
#else
#define CINDEX_LINKAGE __declspec(dllimport)
#endif
#else
#define CINDEX_LINKAGE
#endif
#endif
// HLSL Change starts.
// This includes the LIBCLANG_CC inclusion in this file to be explicit
// about the calling convenion in use.
#ifndef LIBCLANG_CC
#ifdef _MSC_VER
// DLL APIs should use the standard call convention like other WINAPI APIs.
#define LIBCLANG_CC __stdcall
#else
#define LIBCLANG_CC
#endif
#endif
// HLSL Change ends.
#ifdef __GNUC__
#define CINDEX_DEPRECATED __attribute__((deprecated))
#else
#ifdef _MSC_VER
#define CINDEX_DEPRECATED __declspec(deprecated)
#else
#define CINDEX_DEPRECATED
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include | repos/DirectXShaderCompiler/tools/clang/include/clang-c/Index.h | /*===-- clang-c/Index.h - Indexing Public C Interface -------------*- C -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This header provides a public inferface to a Clang library for extracting *|
|* high-level symbol information from source files without exposing the full *|
|* Clang C++ API. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_CLANG_C_INDEX_H
#define LLVM_CLANG_C_INDEX_H
#include <time.h>
#include "clang-c/Platform.h"
#include "clang-c/CXErrorCode.h"
#include "clang-c/CXString.h"
#include "clang-c/BuildSystem.h"
/**
* \brief The version constants for the libclang API.
* CINDEX_VERSION_MINOR should increase when there are API additions.
* CINDEX_VERSION_MAJOR is intended for "major" source/ABI breaking changes.
*
* The policy about the libclang API was always to keep it source and ABI
* compatible, thus CINDEX_VERSION_MAJOR is expected to remain stable.
*/
#define CINDEX_VERSION_MAJOR 0
#define CINDEX_VERSION_MINOR 30
#define CINDEX_VERSION_ENCODE(major, minor) ( \
((major) * 10000) \
+ ((minor) * 1))
#define CINDEX_VERSION CINDEX_VERSION_ENCODE( \
CINDEX_VERSION_MAJOR, \
CINDEX_VERSION_MINOR )
#define CINDEX_VERSION_STRINGIZE_(major, minor) \
#major"."#minor
#define CINDEX_VERSION_STRINGIZE(major, minor) \
CINDEX_VERSION_STRINGIZE_(major, minor)
#define CINDEX_VERSION_STRING CINDEX_VERSION_STRINGIZE( \
CINDEX_VERSION_MAJOR, \
CINDEX_VERSION_MINOR)
#ifdef __cplusplus
extern "C" {
#endif
/** \defgroup CINDEX libclang: C Interface to Clang
*
* The C Interface to Clang provides a relatively small API that exposes
* facilities for parsing source code into an abstract syntax tree (AST),
* loading already-parsed ASTs, traversing the AST, associating
* physical source locations with elements within the AST, and other
* facilities that support Clang-based development tools.
*
* This C interface to Clang will never provide all of the information
* representation stored in Clang's C++ AST, nor should it: the intent is to
* maintain an API that is relatively stable from one release to the next,
* providing only the basic functionality needed to support development tools.
*
* To avoid namespace pollution, data types are prefixed with "CX" and
* functions are prefixed with "clang_".
*
* @{
*/
/**
* \brief An "index" that consists of a set of translation units that would
* typically be linked together into an executable or library.
*/
typedef void *CXIndex;
/**
* \brief A single translation unit, which resides in an index.
*/
typedef struct CXTranslationUnitImpl *CXTranslationUnit;
/**
* \brief Opaque pointer representing client data that will be passed through
* to various callbacks and visitors.
*/
typedef void *CXClientData;
/**
* \brief Provides the contents of a file that has not yet been saved to disk.
*
* Each CXUnsavedFile instance provides the name of a file on the
* system along with the current contents of that file that have not
* yet been saved to disk.
*/
struct CXUnsavedFile {
/**
* \brief The file whose contents have not yet been saved.
*
* This file must already exist in the file system.
*/
const char *Filename;
/**
* \brief A buffer containing the unsaved contents of this file.
*/
const char *Contents;
/**
* \brief The length of the unsaved contents of this buffer.
*/
unsigned long Length;
};
/**
* \brief Describes the availability of a particular entity, which indicates
* whether the use of this entity will result in a warning or error due to
* it being deprecated or unavailable.
*/
enum CXAvailabilityKind {
/**
* \brief The entity is available.
*/
CXAvailability_Available,
/**
* \brief The entity is available, but has been deprecated (and its use is
* not recommended).
*/
CXAvailability_Deprecated,
/**
* \brief The entity is not available; any use of it will be an error.
*/
CXAvailability_NotAvailable,
/**
* \brief The entity is available, but not accessible; any use of it will be
* an error.
*/
CXAvailability_NotAccessible
};
/**
* \brief Describes a version number of the form major.minor.subminor.
*/
typedef struct CXVersion {
/**
* \brief The major version number, e.g., the '10' in '10.7.3'. A negative
* value indicates that there is no version number at all.
*/
int Major;
/**
* \brief The minor version number, e.g., the '7' in '10.7.3'. This value
* will be negative if no minor version number was provided, e.g., for
* version '10'.
*/
int Minor;
/**
* \brief The subminor version number, e.g., the '3' in '10.7.3'. This value
* will be negative if no minor or subminor version number was provided,
* e.g., in version '10' or '10.7'.
*/
int Subminor;
} CXVersion;
/**
* \brief Provides a shared context for creating translation units.
*
* It provides two options:
*
* - excludeDeclarationsFromPCH: When non-zero, allows enumeration of "local"
* declarations (when loading any new translation units). A "local" declaration
* is one that belongs in the translation unit itself and not in a precompiled
* header that was used by the translation unit. If zero, all declarations
* will be enumerated.
*
* Here is an example:
*
* \code
* // excludeDeclsFromPCH = 1, displayDiagnostics=1
* Idx = clang_createIndex(1, 1);
*
* // IndexTest.pch was produced with the following command:
* // "clang -x c IndexTest.h -emit-ast -o IndexTest.pch"
* TU = clang_createTranslationUnit(Idx, "IndexTest.pch");
*
* // This will load all the symbols from 'IndexTest.pch'
* clang_visitChildren(clang_getTranslationUnitCursor(TU),
* TranslationUnitVisitor, 0);
* clang_disposeTranslationUnit(TU);
*
* // This will load all the symbols from 'IndexTest.c', excluding symbols
* // from 'IndexTest.pch'.
* char *args[] = { "-Xclang", "-include-pch=IndexTest.pch" };
* TU = clang_createTranslationUnitFromSourceFile(Idx, "IndexTest.c", 2, args,
* 0, 0);
* clang_visitChildren(clang_getTranslationUnitCursor(TU),
* TranslationUnitVisitor, 0);
* clang_disposeTranslationUnit(TU);
* \endcode
*
* This process of creating the 'pch', loading it separately, and using it (via
* -include-pch) allows 'excludeDeclsFromPCH' to remove redundant callbacks
* (which gives the indexer the same performance benefit as the compiler).
*/
CINDEX_LINKAGE CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
int displayDiagnostics);
// HLSL Change Starts
// void* should be a hlsl::DxcLangExtensionsHelperApply* object.
CINDEX_LINKAGE void LIBCLANG_CC clang_index_setLangHelper(CXIndex index, void*);
// HLSL Change Ends
/**
* \brief Destroy the given index.
*
* The index must not be destroyed until all of the translation units created
* within that index have been destroyed.
*/
CINDEX_LINKAGE void clang_disposeIndex(CXIndex index);
typedef enum {
/**
* \brief Used to indicate that no special CXIndex options are needed.
*/
CXGlobalOpt_None = 0x0,
/**
* \brief Used to indicate that threads that libclang creates for indexing
* purposes should use background priority.
*
* Affects #clang_indexSourceFile, #clang_indexTranslationUnit,
* #clang_parseTranslationUnit, #clang_saveTranslationUnit.
*/
CXGlobalOpt_ThreadBackgroundPriorityForIndexing = 0x1,
/**
* \brief Used to indicate that threads that libclang creates for editing
* purposes should use background priority.
*
* Affects #clang_reparseTranslationUnit, #clang_codeCompleteAt,
* #clang_annotateTokens
*/
CXGlobalOpt_ThreadBackgroundPriorityForEditing = 0x2,
/**
* \brief Used to indicate that all threads that libclang creates should use
* background priority.
*/
CXGlobalOpt_ThreadBackgroundPriorityForAll =
CXGlobalOpt_ThreadBackgroundPriorityForIndexing |
CXGlobalOpt_ThreadBackgroundPriorityForEditing
} CXGlobalOptFlags;
/**
* \brief Sets general options associated with a CXIndex.
*
* For example:
* \code
* CXIndex idx = ...;
* clang_CXIndex_setGlobalOptions(idx,
* clang_CXIndex_getGlobalOptions(idx) |
* CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
* \endcode
*
* \param options A bitmask of options, a bitwise OR of CXGlobalOpt_XXX flags.
*/
CINDEX_LINKAGE void clang_CXIndex_setGlobalOptions(CXIndex, unsigned options);
/**
* \brief Gets the general options associated with a CXIndex.
*
* \returns A bitmask of options, a bitwise OR of CXGlobalOpt_XXX flags that
* are associated with the given CXIndex object.
*/
CINDEX_LINKAGE unsigned clang_CXIndex_getGlobalOptions(CXIndex);
/**
* \defgroup CINDEX_FILES File manipulation routines
*
* @{
*/
/**
* \brief A particular source file that is part of a translation unit.
*/
typedef void *CXFile;
/**
* \brief Retrieve the complete file and path name of the given file.
*/
CINDEX_LINKAGE CXString clang_getFileName(CXFile SFile);
/**
* \brief Retrieve the last modification time of the given file.
*/
CINDEX_LINKAGE time_t clang_getFileTime(CXFile SFile);
/**
* \brief Uniquely identifies a CXFile, that refers to the same underlying file,
* across an indexing session.
*/
typedef struct {
unsigned long long data[3];
} CXFileUniqueID;
/**
* \brief Retrieve the unique ID for the given \c file.
*
* \param file the file to get the ID for.
* \param outID stores the returned CXFileUniqueID.
* \returns If there was a failure getting the unique ID, returns non-zero,
* otherwise returns 0.
*/
CINDEX_LINKAGE int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID);
/**
* \brief Determine whether the given header is guarded against
* multiple inclusions, either with the conventional
* \#ifndef/\#define/\#endif macro guards or with \#pragma once.
*/
CINDEX_LINKAGE unsigned
clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file);
/**
* \brief Retrieve a file handle within the given translation unit.
*
* \param tu the translation unit
*
* \param file_name the name of the file.
*
* \returns the file handle for the named file in the translation unit \p tu,
* or a NULL file handle if the file was not a part of this translation unit.
*/
CINDEX_LINKAGE CXFile clang_getFile(CXTranslationUnit tu,
const char *file_name);
/**
* \brief Returns non-zero if the \c file1 and \c file2 point to the same file,
* or they are both NULL.
*/
CINDEX_LINKAGE int clang_File_isEqual(CXFile file1, CXFile file2);
/**
* @}
*/
/**
* \defgroup CINDEX_LOCATIONS Physical source locations
*
* Clang represents physical source locations in its abstract syntax tree in
* great detail, with file, line, and column information for the majority of
* the tokens parsed in the source code. These data types and functions are
* used to represent source location information, either for a particular
* point in the program or for a range of points in the program, and extract
* specific location information from those data types.
*
* @{
*/
/**
* \brief Identifies a specific source location within a translation
* unit.
*
* Use clang_getExpansionLocation() or clang_getSpellingLocation()
* to map a source location to a particular file, line, and column.
*/
typedef struct {
const void *ptr_data[2];
unsigned int_data;
} CXSourceLocation;
/**
* \brief Identifies a half-open character range in the source code.
*
* Use clang_getRangeStart() and clang_getRangeEnd() to retrieve the
* starting and end locations from a source range, respectively.
*/
typedef struct {
const void *ptr_data[2];
unsigned begin_int_data;
unsigned end_int_data;
} CXSourceRange;
/**
* \brief Retrieve a NULL (invalid) source location.
*/
CINDEX_LINKAGE CXSourceLocation clang_getNullLocation(void);
/**
* \brief Determine whether two source locations, which must refer into
* the same translation unit, refer to exactly the same point in the source
* code.
*
* \returns non-zero if the source locations refer to the same location, zero
* if they refer to different locations.
*/
CINDEX_LINKAGE unsigned clang_equalLocations(CXSourceLocation loc1,
CXSourceLocation loc2);
/**
* \brief Retrieves the source location associated with a given file/line/column
* in a particular translation unit.
*/
CINDEX_LINKAGE CXSourceLocation clang_getLocation(CXTranslationUnit tu,
CXFile file,
unsigned line,
unsigned column);
/**
* \brief Retrieves the source location associated with a given character offset
* in a particular translation unit.
*/
CINDEX_LINKAGE CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
CXFile file,
unsigned offset);
/**
* \brief Returns non-zero if the given source location is in a system header.
*/
CINDEX_LINKAGE int clang_Location_isInSystemHeader(CXSourceLocation location);
/**
* \brief Returns non-zero if the given source location is in the main file of
* the corresponding translation unit.
*/
CINDEX_LINKAGE int clang_Location_isFromMainFile(CXSourceLocation location);
/**
* \brief Retrieve a NULL (invalid) source range.
*/
CINDEX_LINKAGE CXSourceRange clang_getNullRange(void);
/**
* \brief Retrieve a source range given the beginning and ending source
* locations.
*/
CINDEX_LINKAGE CXSourceRange clang_getRange(CXSourceLocation begin,
CXSourceLocation end);
/**
* \brief Determine whether two ranges are equivalent.
*
* \returns non-zero if the ranges are the same, zero if they differ.
*/
CINDEX_LINKAGE unsigned clang_equalRanges(CXSourceRange range1,
CXSourceRange range2);
/**
* \brief Returns non-zero if \p range is null.
*/
CINDEX_LINKAGE int clang_Range_isNull(CXSourceRange range);
/**
* \brief Retrieve the file, line, column, and offset represented by
* the given source location.
*
* If the location refers into a macro expansion, retrieves the
* location of the macro expansion.
*
* \param location the location within a source file that will be decomposed
* into its parts.
*
* \param file [out] if non-NULL, will be set to the file to which the given
* source location points.
*
* \param line [out] if non-NULL, will be set to the line to which the given
* source location points.
*
* \param column [out] if non-NULL, will be set to the column to which the given
* source location points.
*
* \param offset [out] if non-NULL, will be set to the offset into the
* buffer to which the given source location points.
*/
CINDEX_LINKAGE void clang_getExpansionLocation(CXSourceLocation location,
CXFile *file,
unsigned *line,
unsigned *column,
unsigned *offset);
/**
* \brief Retrieve the file, line, column, and offset represented by
* the given source location, as specified in a # line directive.
*
* Example: given the following source code in a file somefile.c
*
* \code
* #123 "dummy.c" 1
*
* static int func(void)
* {
* return 0;
* }
* \endcode
*
* the location information returned by this function would be
*
* File: dummy.c Line: 124 Column: 12
*
* whereas clang_getExpansionLocation would have returned
*
* File: somefile.c Line: 3 Column: 12
*
* \param location the location within a source file that will be decomposed
* into its parts.
*
* \param filename [out] if non-NULL, will be set to the filename of the
* source location. Note that filenames returned will be for "virtual" files,
* which don't necessarily exist on the machine running clang - e.g. when
* parsing preprocessed output obtained from a different environment. If
* a non-NULL value is passed in, remember to dispose of the returned value
* using \c clang_disposeString() once you've finished with it. For an invalid
* source location, an empty string is returned.
*
* \param line [out] if non-NULL, will be set to the line number of the
* source location. For an invalid source location, zero is returned.
*
* \param column [out] if non-NULL, will be set to the column number of the
* source location. For an invalid source location, zero is returned.
*/
CINDEX_LINKAGE void clang_getPresumedLocation(CXSourceLocation location,
CXString *filename,
unsigned *line,
unsigned *column);
/**
* \brief Legacy API to retrieve the file, line, column, and offset represented
* by the given source location.
*
* This interface has been replaced by the newer interface
* #clang_getExpansionLocation(). See that interface's documentation for
* details.
*/
CINDEX_LINKAGE void clang_getInstantiationLocation(CXSourceLocation location,
CXFile *file,
unsigned *line,
unsigned *column,
unsigned *offset);
/**
* \brief Retrieve the file, line, column, and offset represented by
* the given source location.
*
* If the location refers into a macro instantiation, return where the
* location was originally spelled in the source file.
*
* \param location the location within a source file that will be decomposed
* into its parts.
*
* \param file [out] if non-NULL, will be set to the file to which the given
* source location points.
*
* \param line [out] if non-NULL, will be set to the line to which the given
* source location points.
*
* \param column [out] if non-NULL, will be set to the column to which the given
* source location points.
*
* \param offset [out] if non-NULL, will be set to the offset into the
* buffer to which the given source location points.
*/
CINDEX_LINKAGE void clang_getSpellingLocation(CXSourceLocation location,
CXFile *file,
unsigned *line,
unsigned *column,
unsigned *offset);
/**
* \brief Retrieve the file, line, column, and offset represented by
* the given source location.
*
* If the location refers into a macro expansion, return where the macro was
* expanded or where the macro argument was written, if the location points at
* a macro argument.
*
* \param location the location within a source file that will be decomposed
* into its parts.
*
* \param file [out] if non-NULL, will be set to the file to which the given
* source location points.
*
* \param line [out] if non-NULL, will be set to the line to which the given
* source location points.
*
* \param column [out] if non-NULL, will be set to the column to which the given
* source location points.
*
* \param offset [out] if non-NULL, will be set to the offset into the
* buffer to which the given source location points.
*/
CINDEX_LINKAGE void clang_getFileLocation(CXSourceLocation location,
CXFile *file,
unsigned *line,
unsigned *column,
unsigned *offset);
/**
* \brief Retrieve a source location representing the first character within a
* source range.
*/
CINDEX_LINKAGE CXSourceLocation clang_getRangeStart(CXSourceRange range);
/**
* \brief Retrieve a source location representing the last character within a
* source range.
*/
CINDEX_LINKAGE CXSourceLocation clang_getRangeEnd(CXSourceRange range);
/**
* \brief Identifies an array of ranges.
*/
typedef struct {
/** \brief The number of ranges in the \c ranges array. */
unsigned count;
/**
* \brief An array of \c CXSourceRanges.
*/
CXSourceRange *ranges;
} CXSourceRangeList;
/**
* \brief Retrieve all ranges that were skipped by the preprocessor.
*
* The preprocessor will skip lines when they are surrounded by an
* if/ifdef/ifndef directive whose condition does not evaluate to true.
*/
CINDEX_LINKAGE CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit tu,
CXFile file);
/**
* \brief Destroy the given \c CXSourceRangeList.
*/
CINDEX_LINKAGE void clang_disposeSourceRangeList(CXSourceRangeList *ranges);
/**
* @}
*/
/**
* \defgroup CINDEX_DIAG Diagnostic reporting
*
* @{
*/
/**
* \brief Describes the severity of a particular diagnostic.
*/
enum CXDiagnosticSeverity {
/**
* \brief A diagnostic that has been suppressed, e.g., by a command-line
* option.
*/
CXDiagnostic_Ignored = 0,
/**
* \brief This diagnostic is a note that should be attached to the
* previous (non-note) diagnostic.
*/
CXDiagnostic_Note = 1,
/**
* \brief This diagnostic indicates suspicious code that may not be
* wrong.
*/
CXDiagnostic_Warning = 2,
/**
* \brief This diagnostic indicates that the code is ill-formed.
*/
CXDiagnostic_Error = 3,
/**
* \brief This diagnostic indicates that the code is ill-formed such
* that future parser recovery is unlikely to produce useful
* results.
*/
CXDiagnostic_Fatal = 4
};
/**
* \brief A single diagnostic, containing the diagnostic's severity,
* location, text, source ranges, and fix-it hints.
*/
typedef void *CXDiagnostic;
/**
* \brief A group of CXDiagnostics.
*/
typedef void *CXDiagnosticSet;
/**
* \brief Determine the number of diagnostics in a CXDiagnosticSet.
*/
CINDEX_LINKAGE unsigned clang_getNumDiagnosticsInSet(CXDiagnosticSet Diags);
/**
* \brief Retrieve a diagnostic associated with the given CXDiagnosticSet.
*
* \param Diags the CXDiagnosticSet to query.
* \param Index the zero-based diagnostic number to retrieve.
*
* \returns the requested diagnostic. This diagnostic must be freed
* via a call to \c clang_disposeDiagnostic().
*/
CINDEX_LINKAGE CXDiagnostic clang_getDiagnosticInSet(CXDiagnosticSet Diags,
unsigned Index);
/**
* \brief Describes the kind of error that occurred (if any) in a call to
* \c clang_loadDiagnostics.
*/
enum CXLoadDiag_Error {
/**
* \brief Indicates that no error occurred.
*/
CXLoadDiag_None = 0,
/**
* \brief Indicates that an unknown error occurred while attempting to
* deserialize diagnostics.
*/
CXLoadDiag_Unknown = 1,
/**
* \brief Indicates that the file containing the serialized diagnostics
* could not be opened.
*/
CXLoadDiag_CannotLoad = 2,
/**
* \brief Indicates that the serialized diagnostics file is invalid or
* corrupt.
*/
CXLoadDiag_InvalidFile = 3
};
/**
* \brief Deserialize a set of diagnostics from a Clang diagnostics bitcode
* file.
*
* \param file The name of the file to deserialize.
* \param error A pointer to a enum value recording if there was a problem
* deserializing the diagnostics.
* \param errorString A pointer to a CXString for recording the error string
* if the file was not successfully loaded.
*
* \returns A loaded CXDiagnosticSet if successful, and NULL otherwise. These
* diagnostics should be released using clang_disposeDiagnosticSet().
*/
CINDEX_LINKAGE CXDiagnosticSet clang_loadDiagnostics(const char *file,
enum CXLoadDiag_Error *error,
CXString *errorString);
/**
* \brief Release a CXDiagnosticSet and all of its contained diagnostics.
*/
CINDEX_LINKAGE void clang_disposeDiagnosticSet(CXDiagnosticSet Diags);
/**
* \brief Retrieve the child diagnostics of a CXDiagnostic.
*
* This CXDiagnosticSet does not need to be released by
* clang_disposeDiagnosticSet.
*/
CINDEX_LINKAGE CXDiagnosticSet clang_getChildDiagnostics(CXDiagnostic D);
/**
* \brief Determine the number of diagnostics produced for the given
* translation unit.
*/
CINDEX_LINKAGE unsigned clang_getNumDiagnostics(CXTranslationUnit Unit);
/**
* \brief Retrieve a diagnostic associated with the given translation unit.
*
* \param Unit the translation unit to query.
* \param Index the zero-based diagnostic number to retrieve.
*
* \returns the requested diagnostic. This diagnostic must be freed
* via a call to \c clang_disposeDiagnostic().
*/
CINDEX_LINKAGE CXDiagnostic clang_getDiagnostic(CXTranslationUnit Unit,
unsigned Index);
/**
* \brief Retrieve the complete set of diagnostics associated with a
* translation unit.
*
* \param Unit the translation unit to query.
*/
CINDEX_LINKAGE CXDiagnosticSet
clang_getDiagnosticSetFromTU(CXTranslationUnit Unit);
/**
* \brief Destroy a diagnostic.
*/
CINDEX_LINKAGE void clang_disposeDiagnostic(CXDiagnostic Diagnostic);
/**
* \brief Options to control the display of diagnostics.
*
* The values in this enum are meant to be combined to customize the
* behavior of \c clang_formatDiagnostic().
*/
enum CXDiagnosticDisplayOptions {
/**
* \brief Display the source-location information where the
* diagnostic was located.
*
* When set, diagnostics will be prefixed by the file, line, and
* (optionally) column to which the diagnostic refers. For example,
*
* \code
* test.c:28: warning: extra tokens at end of #endif directive
* \endcode
*
* This option corresponds to the clang flag \c -fshow-source-location.
*/
CXDiagnostic_DisplaySourceLocation = 0x01,
/**
* \brief If displaying the source-location information of the
* diagnostic, also include the column number.
*
* This option corresponds to the clang flag \c -fshow-column.
*/
CXDiagnostic_DisplayColumn = 0x02,
/**
* \brief If displaying the source-location information of the
* diagnostic, also include information about source ranges in a
* machine-parsable format.
*
* This option corresponds to the clang flag
* \c -fdiagnostics-print-source-range-info.
*/
CXDiagnostic_DisplaySourceRanges = 0x04,
/**
* \brief Display the option name associated with this diagnostic, if any.
*
* The option name displayed (e.g., -Wconversion) will be placed in brackets
* after the diagnostic text. This option corresponds to the clang flag
* \c -fdiagnostics-show-option.
*/
CXDiagnostic_DisplayOption = 0x08,
/**
* \brief Display the category number associated with this diagnostic, if any.
*
* The category number is displayed within brackets after the diagnostic text.
* This option corresponds to the clang flag
* \c -fdiagnostics-show-category=id.
*/
CXDiagnostic_DisplayCategoryId = 0x10,
/**
* \brief Display the category name associated with this diagnostic, if any.
*
* The category name is displayed within brackets after the diagnostic text.
* This option corresponds to the clang flag
* \c -fdiagnostics-show-category=name.
*/
CXDiagnostic_DisplayCategoryName = 0x20
, CXDiagnostic_DisplaySeverity = 0x200 // HLSL Change: new flag to control severity
};
/**
* \brief Format the given diagnostic in a manner that is suitable for display.
*
* This routine will format the given diagnostic to a string, rendering
* the diagnostic according to the various options given. The
* \c clang_defaultDiagnosticDisplayOptions() function returns the set of
* options that most closely mimics the behavior of the clang compiler.
*
* \param Diagnostic The diagnostic to print.
*
* \param Options A set of options that control the diagnostic display,
* created by combining \c CXDiagnosticDisplayOptions values.
*
* \returns A new string containing for formatted diagnostic.
*/
CINDEX_LINKAGE CXString clang_formatDiagnostic(CXDiagnostic Diagnostic,
unsigned Options);
/**
* \brief Retrieve the set of display options most similar to the
* default behavior of the clang compiler.
*
* \returns A set of display options suitable for use with \c
* clang_formatDiagnostic().
*/
CINDEX_LINKAGE unsigned clang_defaultDiagnosticDisplayOptions(void);
/**
* \brief Determine the severity of the given diagnostic.
*/
CINDEX_LINKAGE enum CXDiagnosticSeverity
clang_getDiagnosticSeverity(CXDiagnostic);
/**
* \brief Retrieve the source location of the given diagnostic.
*
* This location is where Clang would print the caret ('^') when
* displaying the diagnostic on the command line.
*/
CINDEX_LINKAGE CXSourceLocation clang_getDiagnosticLocation(CXDiagnostic);
/**
* \brief Retrieve the text of the given diagnostic.
*/
CINDEX_LINKAGE CXString clang_getDiagnosticSpelling(CXDiagnostic);
/**
* \brief Retrieve the name of the command-line option that enabled this
* diagnostic.
*
* \param Diag The diagnostic to be queried.
*
* \param Disable If non-NULL, will be set to the option that disables this
* diagnostic (if any).
*
* \returns A string that contains the command-line option used to enable this
* warning, such as "-Wconversion" or "-pedantic".
*/
CINDEX_LINKAGE CXString clang_getDiagnosticOption(CXDiagnostic Diag,
CXString *Disable);
/**
* \brief Retrieve the category number for this diagnostic.
*
* Diagnostics can be categorized into groups along with other, related
* diagnostics (e.g., diagnostics under the same warning flag). This routine
* retrieves the category number for the given diagnostic.
*
* \returns The number of the category that contains this diagnostic, or zero
* if this diagnostic is uncategorized.
*/
CINDEX_LINKAGE unsigned clang_getDiagnosticCategory(CXDiagnostic);
/**
* \brief Retrieve the name of a particular diagnostic category. This
* is now deprecated. Use clang_getDiagnosticCategoryText()
* instead.
*
* \param Category A diagnostic category number, as returned by
* \c clang_getDiagnosticCategory().
*
* \returns The name of the given diagnostic category.
*/
CINDEX_DEPRECATED CINDEX_LINKAGE
CXString clang_getDiagnosticCategoryName(unsigned Category);
/**
* \brief Retrieve the diagnostic category text for a given diagnostic.
*
* \returns The text of the given diagnostic category.
*/
CINDEX_LINKAGE CXString clang_getDiagnosticCategoryText(CXDiagnostic);
/**
* \brief Determine the number of source ranges associated with the given
* diagnostic.
*/
CINDEX_LINKAGE unsigned clang_getDiagnosticNumRanges(CXDiagnostic);
/**
* \brief Retrieve a source range associated with the diagnostic.
*
* A diagnostic's source ranges highlight important elements in the source
* code. On the command line, Clang displays source ranges by
* underlining them with '~' characters.
*
* \param Diagnostic the diagnostic whose range is being extracted.
*
* \param Range the zero-based index specifying which range to
*
* \returns the requested source range.
*/
CINDEX_LINKAGE CXSourceRange clang_getDiagnosticRange(CXDiagnostic Diagnostic,
unsigned Range);
/**
* \brief Determine the number of fix-it hints associated with the
* given diagnostic.
*/
CINDEX_LINKAGE unsigned clang_getDiagnosticNumFixIts(CXDiagnostic Diagnostic);
/**
* \brief Retrieve the replacement information for a given fix-it.
*
* Fix-its are described in terms of a source range whose contents
* should be replaced by a string. This approach generalizes over
* three kinds of operations: removal of source code (the range covers
* the code to be removed and the replacement string is empty),
* replacement of source code (the range covers the code to be
* replaced and the replacement string provides the new code), and
* insertion (both the start and end of the range point at the
* insertion location, and the replacement string provides the text to
* insert).
*
* \param Diagnostic The diagnostic whose fix-its are being queried.
*
* \param FixIt The zero-based index of the fix-it.
*
* \param ReplacementRange The source range whose contents will be
* replaced with the returned replacement string. Note that source
* ranges are half-open ranges [a, b), so the source code should be
* replaced from a and up to (but not including) b.
*
* \returns A string containing text that should be replace the source
* code indicated by the \c ReplacementRange.
*/
CINDEX_LINKAGE CXString clang_getDiagnosticFixIt(CXDiagnostic Diagnostic,
unsigned FixIt,
CXSourceRange *ReplacementRange);
/**
* @}
*/
/**
* \defgroup CINDEX_TRANSLATION_UNIT Translation unit manipulation
*
* The routines in this group provide the ability to create and destroy
* translation units from files, either by parsing the contents of the files or
* by reading in a serialized representation of a translation unit.
*
* @{
*/
/**
* \brief Get the original translation unit source file name.
*/
CINDEX_LINKAGE CXString
clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit);
/**
* \brief Return the CXTranslationUnit for a given source file and the provided
* command line arguments one would pass to the compiler.
*
* Note: The 'source_filename' argument is optional. If the caller provides a
* NULL pointer, the name of the source file is expected to reside in the
* specified command line arguments.
*
* Note: When encountered in 'clang_command_line_args', the following options
* are ignored:
*
* '-c'
* '-emit-ast'
* '-fsyntax-only'
* '-o \<output file>' (both '-o' and '\<output file>' are ignored)
*
* \param CIdx The index object with which the translation unit will be
* associated.
*
* \param source_filename The name of the source file to load, or NULL if the
* source file is included in \p clang_command_line_args.
*
* \param num_clang_command_line_args The number of command-line arguments in
* \p clang_command_line_args.
*
* \param clang_command_line_args The command-line arguments that would be
* passed to the \c clang executable if it were being invoked out-of-process.
* These command-line options will be parsed and will affect how the translation
* unit is parsed. Note that the following options are ignored: '-c',
* '-emit-ast', '-fsyntax-only' (which is the default), and '-o \<output file>'.
*
* \param num_unsaved_files the number of unsaved file entries in \p
* unsaved_files.
*
* \param unsaved_files the files that have not yet been saved to disk
* but may be required for code completion, including the contents of
* those files. The contents and name of these files (as specified by
* CXUnsavedFile) are copied when necessary, so the client only needs to
* guarantee their validity until the call to this function returns.
*/
CINDEX_LINKAGE CXTranslationUnit clang_createTranslationUnitFromSourceFile(
CXIndex CIdx,
const char *source_filename,
int num_clang_command_line_args,
const char * const *clang_command_line_args,
unsigned num_unsaved_files,
struct CXUnsavedFile *unsaved_files);
/**
* \brief Same as \c clang_createTranslationUnit2, but returns
* the \c CXTranslationUnit instead of an error code. In case of an error this
* routine returns a \c NULL \c CXTranslationUnit, without further detailed
* error codes.
*/
CINDEX_LINKAGE CXTranslationUnit clang_createTranslationUnit(
CXIndex CIdx,
const char *ast_filename);
/**
* \brief Create a translation unit from an AST file (\c -emit-ast).
*
* \param[out] out_TU A non-NULL pointer to store the created
* \c CXTranslationUnit.
*
* \returns Zero on success, otherwise returns an error code.
*/
CINDEX_LINKAGE enum CXErrorCode clang_createTranslationUnit2(
CXIndex CIdx,
const char *ast_filename,
CXTranslationUnit *out_TU);
/**
* \brief Flags that control the creation of translation units.
*
* The enumerators in this enumeration type are meant to be bitwise
* ORed together to specify which options should be used when
* constructing the translation unit.
*/
enum CXTranslationUnit_Flags {
/**
* \brief Used to indicate that no special translation-unit options are
* needed.
*/
CXTranslationUnit_None = 0x0,
/**
* \brief Used to indicate that the parser should construct a "detailed"
* preprocessing record, including all macro definitions and instantiations.
*
* Constructing a detailed preprocessing record requires more memory
* and time to parse, since the information contained in the record
* is usually not retained. However, it can be useful for
* applications that require more detailed information about the
* behavior of the preprocessor.
*/
CXTranslationUnit_DetailedPreprocessingRecord = 0x01,
/**
* \brief Used to indicate that the translation unit is incomplete.
*
* When a translation unit is considered "incomplete", semantic
* analysis that is typically performed at the end of the
* translation unit will be suppressed. For example, this suppresses
* the completion of tentative declarations in C and of
* instantiation of implicitly-instantiation function templates in
* C++. This option is typically used when parsing a header with the
* intent of producing a precompiled header.
*/
CXTranslationUnit_Incomplete = 0x02,
/**
* \brief Used to indicate that the translation unit should be built with an
* implicit precompiled header for the preamble.
*
* An implicit precompiled header is used as an optimization when a
* particular translation unit is likely to be reparsed many times
* when the sources aren't changing that often. In this case, an
* implicit precompiled header will be built containing all of the
* initial includes at the top of the main file (what we refer to as
* the "preamble" of the file). In subsequent parses, if the
* preamble or the files in it have not changed, \c
* clang_reparseTranslationUnit() will re-use the implicit
* precompiled header to improve parsing performance.
*/
CXTranslationUnit_PrecompiledPreamble = 0x04,
/**
* \brief Used to indicate that the translation unit should cache some
* code-completion results with each reparse of the source file.
*
* Caching of code-completion results is a performance optimization that
* introduces some overhead to reparsing but improves the performance of
* code-completion operations.
*/
CXTranslationUnit_CacheCompletionResults = 0x08,
/**
* \brief Used to indicate that the translation unit will be serialized with
* \c clang_saveTranslationUnit.
*
* This option is typically used when parsing a header with the intent of
* producing a precompiled header.
*/
CXTranslationUnit_ForSerialization = 0x10,
/**
* \brief DEPRECATED: Enabled chained precompiled preambles in C++.
*
* Note: this is a *temporary* option that is available only while
* we are testing C++ precompiled preamble support. It is deprecated.
*/
CXTranslationUnit_CXXChainedPCH = 0x20,
/**
* \brief Used to indicate that function/method bodies should be skipped while
* parsing.
*
* This option can be used to search for declarations/definitions while
* ignoring the usages.
*/
CXTranslationUnit_SkipFunctionBodies = 0x40,
/**
* \brief Used to indicate that brief documentation comments should be
* included into the set of code completions returned from this translation
* unit.
*/
CXTranslationUnit_IncludeBriefCommentsInCodeCompletion = 0x80,
CXTranslationUnit_UseCallerThread = 0x800, // HLSL Change - add a flag
};
/**
* \brief Returns the set of flags that is suitable for parsing a translation
* unit that is being edited.
*
* The set of flags returned provide options for \c clang_parseTranslationUnit()
* to indicate that the translation unit is likely to be reparsed many times,
* either explicitly (via \c clang_reparseTranslationUnit()) or implicitly
* (e.g., by code completion (\c clang_codeCompletionAt())). The returned flag
* set contains an unspecified set of optimizations (e.g., the precompiled
* preamble) geared toward improving the performance of these routines. The
* set of optimizations enabled may change from one version to the next.
*/
CINDEX_LINKAGE unsigned clang_defaultEditingTranslationUnitOptions(void);
/**
* \brief Same as \c clang_parseTranslationUnit2, but returns
* the \c CXTranslationUnit instead of an error code. In case of an error this
* routine returns a \c NULL \c CXTranslationUnit, without further detailed
* error codes.
*/
CINDEX_LINKAGE CXTranslationUnit
clang_parseTranslationUnit(CXIndex CIdx,
const char *source_filename,
const char *const *command_line_args,
int num_command_line_args,
struct CXUnsavedFile *unsaved_files,
unsigned num_unsaved_files,
unsigned options);
/**
* \brief Parse the given source file and the translation unit corresponding
* to that file.
*
* This routine is the main entry point for the Clang C API, providing the
* ability to parse a source file into a translation unit that can then be
* queried by other functions in the API. This routine accepts a set of
* command-line arguments so that the compilation can be configured in the same
* way that the compiler is configured on the command line.
*
* \param CIdx The index object with which the translation unit will be
* associated.
*
* \param source_filename The name of the source file to load, or NULL if the
* source file is included in \c command_line_args.
*
* \param command_line_args The command-line arguments that would be
* passed to the \c clang executable if it were being invoked out-of-process.
* These command-line options will be parsed and will affect how the translation
* unit is parsed. Note that the following options are ignored: '-c',
* '-emit-ast', '-fsyntax-only' (which is the default), and '-o \<output file>'.
*
* \param num_command_line_args The number of command-line arguments in
* \c command_line_args.
*
* \param unsaved_files the files that have not yet been saved to disk
* but may be required for parsing, including the contents of
* those files. The contents and name of these files (as specified by
* CXUnsavedFile) are copied when necessary, so the client only needs to
* guarantee their validity until the call to this function returns.
*
* \param num_unsaved_files the number of unsaved file entries in \p
* unsaved_files.
*
* \param options A bitmask of options that affects how the translation unit
* is managed but not its compilation. This should be a bitwise OR of the
* CXTranslationUnit_XXX flags.
*
* \param[out] out_TU A non-NULL pointer to store the created
* \c CXTranslationUnit, describing the parsed code and containing any
* diagnostics produced by the compiler.
*
* \returns Zero on success, otherwise returns an error code.
*/
CINDEX_LINKAGE enum CXErrorCode
clang_parseTranslationUnit2(CXIndex CIdx,
const char *source_filename,
const char *const *command_line_args,
int num_command_line_args,
struct CXUnsavedFile *unsaved_files,
unsigned num_unsaved_files,
unsigned options,
CXTranslationUnit *out_TU);
/**
* \brief Flags that control how translation units are saved.
*
* The enumerators in this enumeration type are meant to be bitwise
* ORed together to specify which options should be used when
* saving the translation unit.
*/
enum CXSaveTranslationUnit_Flags {
/**
* \brief Used to indicate that no special saving options are needed.
*/
CXSaveTranslationUnit_None = 0x0
};
/**
* \brief Returns the set of flags that is suitable for saving a translation
* unit.
*
* The set of flags returned provide options for
* \c clang_saveTranslationUnit() by default. The returned flag
* set contains an unspecified set of options that save translation units with
* the most commonly-requested data.
*/
CINDEX_LINKAGE unsigned clang_defaultSaveOptions(CXTranslationUnit TU);
/**
* \brief Describes the kind of error that occurred (if any) in a call to
* \c clang_saveTranslationUnit().
*/
enum CXSaveError {
/**
* \brief Indicates that no error occurred while saving a translation unit.
*/
CXSaveError_None = 0,
/**
* \brief Indicates that an unknown error occurred while attempting to save
* the file.
*
* This error typically indicates that file I/O failed when attempting to
* write the file.
*/
CXSaveError_Unknown = 1,
/**
* \brief Indicates that errors during translation prevented this attempt
* to save the translation unit.
*
* Errors that prevent the translation unit from being saved can be
* extracted using \c clang_getNumDiagnostics() and \c clang_getDiagnostic().
*/
CXSaveError_TranslationErrors = 2,
/**
* \brief Indicates that the translation unit to be saved was somehow
* invalid (e.g., NULL).
*/
CXSaveError_InvalidTU = 3
};
/**
* \brief Saves a translation unit into a serialized representation of
* that translation unit on disk.
*
* Any translation unit that was parsed without error can be saved
* into a file. The translation unit can then be deserialized into a
* new \c CXTranslationUnit with \c clang_createTranslationUnit() or,
* if it is an incomplete translation unit that corresponds to a
* header, used as a precompiled header when parsing other translation
* units.
*
* \param TU The translation unit to save.
*
* \param FileName The file to which the translation unit will be saved.
*
* \param options A bitmask of options that affects how the translation unit
* is saved. This should be a bitwise OR of the
* CXSaveTranslationUnit_XXX flags.
*
* \returns A value that will match one of the enumerators of the CXSaveError
* enumeration. Zero (CXSaveError_None) indicates that the translation unit was
* saved successfully, while a non-zero value indicates that a problem occurred.
*/
CINDEX_LINKAGE int clang_saveTranslationUnit(CXTranslationUnit TU,
const char *FileName,
unsigned options);
/**
* \brief Destroy the specified CXTranslationUnit object.
*/
CINDEX_LINKAGE void clang_disposeTranslationUnit(CXTranslationUnit);
/**
* \brief Flags that control the reparsing of translation units.
*
* The enumerators in this enumeration type are meant to be bitwise
* ORed together to specify which options should be used when
* reparsing the translation unit.
*/
enum CXReparse_Flags {
/**
* \brief Used to indicate that no special reparsing options are needed.
*/
CXReparse_None = 0x0
};
/**
* \brief Returns the set of flags that is suitable for reparsing a translation
* unit.
*
* The set of flags returned provide options for
* \c clang_reparseTranslationUnit() by default. The returned flag
* set contains an unspecified set of optimizations geared toward common uses
* of reparsing. The set of optimizations enabled may change from one version
* to the next.
*/
CINDEX_LINKAGE unsigned clang_defaultReparseOptions(CXTranslationUnit TU);
/**
* \brief Reparse the source files that produced this translation unit.
*
* This routine can be used to re-parse the source files that originally
* created the given translation unit, for example because those source files
* have changed (either on disk or as passed via \p unsaved_files). The
* source code will be reparsed with the same command-line options as it
* was originally parsed.
*
* Reparsing a translation unit invalidates all cursors and source locations
* that refer into that translation unit. This makes reparsing a translation
* unit semantically equivalent to destroying the translation unit and then
* creating a new translation unit with the same command-line arguments.
* However, it may be more efficient to reparse a translation
* unit using this routine.
*
* \param TU The translation unit whose contents will be re-parsed. The
* translation unit must originally have been built with
* \c clang_createTranslationUnitFromSourceFile().
*
* \param num_unsaved_files The number of unsaved file entries in \p
* unsaved_files.
*
* \param unsaved_files The files that have not yet been saved to disk
* but may be required for parsing, including the contents of
* those files. The contents and name of these files (as specified by
* CXUnsavedFile) are copied when necessary, so the client only needs to
* guarantee their validity until the call to this function returns.
*
* \param options A bitset of options composed of the flags in CXReparse_Flags.
* The function \c clang_defaultReparseOptions() produces a default set of
* options recommended for most uses, based on the translation unit.
*
* \returns 0 if the sources could be reparsed. A non-zero error code will be
* returned if reparsing was impossible, such that the translation unit is
* invalid. In such cases, the only valid call for \c TU is
* \c clang_disposeTranslationUnit(TU). The error codes returned by this
* routine are described by the \c CXErrorCode enum.
*/
CINDEX_LINKAGE int clang_reparseTranslationUnit(CXTranslationUnit TU,
unsigned num_unsaved_files,
struct CXUnsavedFile *unsaved_files,
unsigned options);
/**
* \brief Categorizes how memory is being used by a translation unit.
*/
enum CXTUResourceUsageKind {
CXTUResourceUsage_AST = 1,
CXTUResourceUsage_Identifiers = 2,
CXTUResourceUsage_Selectors = 3,
CXTUResourceUsage_GlobalCompletionResults = 4,
CXTUResourceUsage_SourceManagerContentCache = 5,
CXTUResourceUsage_AST_SideTables = 6,
CXTUResourceUsage_SourceManager_Membuffer_Malloc = 7,
CXTUResourceUsage_SourceManager_Membuffer_MMap = 8,
CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc = 9,
CXTUResourceUsage_ExternalASTSource_Membuffer_MMap = 10,
CXTUResourceUsage_Preprocessor = 11,
CXTUResourceUsage_PreprocessingRecord = 12,
CXTUResourceUsage_SourceManager_DataStructures = 13,
CXTUResourceUsage_Preprocessor_HeaderSearch = 14,
CXTUResourceUsage_MEMORY_IN_BYTES_BEGIN = CXTUResourceUsage_AST,
CXTUResourceUsage_MEMORY_IN_BYTES_END =
CXTUResourceUsage_Preprocessor_HeaderSearch,
CXTUResourceUsage_First = CXTUResourceUsage_AST,
CXTUResourceUsage_Last = CXTUResourceUsage_Preprocessor_HeaderSearch
};
/**
* \brief Returns the human-readable null-terminated C string that represents
* the name of the memory category. This string should never be freed.
*/
CINDEX_LINKAGE
const char *clang_getTUResourceUsageName(enum CXTUResourceUsageKind kind);
typedef struct CXTUResourceUsageEntry {
/* \brief The memory usage category. */
enum CXTUResourceUsageKind kind;
/* \brief Amount of resources used.
The units will depend on the resource kind. */
unsigned long amount;
} CXTUResourceUsageEntry;
/**
* \brief The memory usage of a CXTranslationUnit, broken into categories.
*/
typedef struct CXTUResourceUsage {
/* \brief Private data member, used for queries. */
void *data;
/* \brief The number of entries in the 'entries' array. */
unsigned numEntries;
/* \brief An array of key-value pairs, representing the breakdown of memory
usage. */
CXTUResourceUsageEntry *entries;
} CXTUResourceUsage;
/**
* \brief Return the memory usage of a translation unit. This object
* should be released with clang_disposeCXTUResourceUsage().
*/
CINDEX_LINKAGE CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU);
CINDEX_LINKAGE void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage);
/**
* @}
*/
/**
* \brief Describes the kind of entity that a cursor refers to.
*/
enum CXCursorKind {
/* Declarations */
/**
* \brief A declaration whose specific kind is not exposed via this
* interface.
*
* Unexposed declarations have the same operations as any other kind
* of declaration; one can extract their location information,
* spelling, find their definitions, etc. However, the specific kind
* of the declaration is not reported.
*/
CXCursor_UnexposedDecl = 1,
/** \brief A C or C++ struct. */
CXCursor_StructDecl = 2,
/** \brief A C or C++ union. */
CXCursor_UnionDecl = 3,
/** \brief A C++ class. */
CXCursor_ClassDecl = 4,
/** \brief An enumeration. */
CXCursor_EnumDecl = 5,
/**
* \brief A field (in C) or non-static data member (in C++) in a
* struct, union, or C++ class.
*/
CXCursor_FieldDecl = 6,
/** \brief An enumerator constant. */
CXCursor_EnumConstantDecl = 7,
/** \brief A function. */
CXCursor_FunctionDecl = 8,
/** \brief A variable. */
CXCursor_VarDecl = 9,
/** \brief A function or method parameter. */
CXCursor_ParmDecl = 10,
/** \brief An Objective-C \@interface. */
CXCursor_ObjCInterfaceDecl = 11,
/** \brief An Objective-C \@interface for a category. */
CXCursor_ObjCCategoryDecl = 12,
/** \brief An Objective-C \@protocol declaration. */
CXCursor_ObjCProtocolDecl = 13,
/** \brief An Objective-C \@property declaration. */
CXCursor_ObjCPropertyDecl = 14,
/** \brief An Objective-C instance variable. */
CXCursor_ObjCIvarDecl = 15,
/** \brief An Objective-C instance method. */
CXCursor_ObjCInstanceMethodDecl = 16,
/** \brief An Objective-C class method. */
CXCursor_ObjCClassMethodDecl = 17,
/** \brief An Objective-C \@implementation. */
CXCursor_ObjCImplementationDecl = 18,
/** \brief An Objective-C \@implementation for a category. */
CXCursor_ObjCCategoryImplDecl = 19,
/** \brief A typedef */
CXCursor_TypedefDecl = 20,
/** \brief A C++ class method. */
CXCursor_CXXMethod = 21,
/** \brief A C++ namespace. */
CXCursor_Namespace = 22,
/** \brief A linkage specification, e.g. 'extern "C"'. */
CXCursor_LinkageSpec = 23,
/** \brief A C++ constructor. */
CXCursor_Constructor = 24,
/** \brief A C++ destructor. */
CXCursor_Destructor = 25,
/** \brief A C++ conversion function. */
CXCursor_ConversionFunction = 26,
/** \brief A C++ template type parameter. */
CXCursor_TemplateTypeParameter = 27,
/** \brief A C++ non-type template parameter. */
CXCursor_NonTypeTemplateParameter = 28,
/** \brief A C++ template template parameter. */
CXCursor_TemplateTemplateParameter = 29,
/** \brief A C++ function template. */
CXCursor_FunctionTemplate = 30,
/** \brief A C++ class template. */
CXCursor_ClassTemplate = 31,
/** \brief A C++ class template partial specialization. */
CXCursor_ClassTemplatePartialSpecialization = 32,
/** \brief A C++ namespace alias declaration. */
CXCursor_NamespaceAlias = 33,
/** \brief A C++ using directive. */
CXCursor_UsingDirective = 34,
/** \brief A C++ using declaration. */
CXCursor_UsingDeclaration = 35,
/** \brief A C++ alias declaration */
CXCursor_TypeAliasDecl = 36,
/** \brief An Objective-C \@synthesize definition. */
CXCursor_ObjCSynthesizeDecl = 37,
/** \brief An Objective-C \@dynamic definition. */
CXCursor_ObjCDynamicDecl = 38,
/** \brief An access specifier. */
CXCursor_CXXAccessSpecifier = 39,
CXCursor_FirstDecl = CXCursor_UnexposedDecl,
CXCursor_LastDecl = CXCursor_CXXAccessSpecifier,
/* References */
CXCursor_FirstRef = 40, /* Decl references */
CXCursor_ObjCSuperClassRef = 40,
CXCursor_ObjCProtocolRef = 41,
CXCursor_ObjCClassRef = 42,
/**
* \brief A reference to a type declaration.
*
* A type reference occurs anywhere where a type is named but not
* declared. For example, given:
*
* \code
* typedef unsigned size_type;
* size_type size;
* \endcode
*
* The typedef is a declaration of size_type (CXCursor_TypedefDecl),
* while the type of the variable "size" is referenced. The cursor
* referenced by the type of size is the typedef for size_type.
*/
CXCursor_TypeRef = 43,
CXCursor_CXXBaseSpecifier = 44,
/**
* \brief A reference to a class template, function template, template
* template parameter, or class template partial specialization.
*/
CXCursor_TemplateRef = 45,
/**
* \brief A reference to a namespace or namespace alias.
*/
CXCursor_NamespaceRef = 46,
/**
* \brief A reference to a member of a struct, union, or class that occurs in
* some non-expression context, e.g., a designated initializer.
*/
CXCursor_MemberRef = 47,
/**
* \brief A reference to a labeled statement.
*
* This cursor kind is used to describe the jump to "start_over" in the
* goto statement in the following example:
*
* \code
* start_over:
* ++counter;
*
* goto start_over;
* \endcode
*
* A label reference cursor refers to a label statement.
*/
CXCursor_LabelRef = 48,
/**
* \brief A reference to a set of overloaded functions or function templates
* that has not yet been resolved to a specific function or function template.
*
* An overloaded declaration reference cursor occurs in C++ templates where
* a dependent name refers to a function. For example:
*
* \code
* template<typename T> void swap(T&, T&);
*
* struct X { ... };
* void swap(X&, X&);
*
* template<typename T>
* void reverse(T* first, T* last) {
* while (first < last - 1) {
* swap(*first, *--last);
* ++first;
* }
* }
*
* struct Y { };
* void swap(Y&, Y&);
* \endcode
*
* Here, the identifier "swap" is associated with an overloaded declaration
* reference. In the template definition, "swap" refers to either of the two
* "swap" functions declared above, so both results will be available. At
* instantiation time, "swap" may also refer to other functions found via
* argument-dependent lookup (e.g., the "swap" function at the end of the
* example).
*
* The functions \c clang_getNumOverloadedDecls() and
* \c clang_getOverloadedDecl() can be used to retrieve the definitions
* referenced by this cursor.
*/
CXCursor_OverloadedDeclRef = 49,
/**
* \brief A reference to a variable that occurs in some non-expression
* context, e.g., a C++ lambda capture list.
*/
CXCursor_VariableRef = 50,
CXCursor_LastRef = CXCursor_VariableRef,
/* Error conditions */
CXCursor_FirstInvalid = 70,
CXCursor_InvalidFile = 70,
CXCursor_NoDeclFound = 71,
CXCursor_NotImplemented = 72,
CXCursor_InvalidCode = 73,
CXCursor_LastInvalid = CXCursor_InvalidCode,
/* Expressions */
CXCursor_FirstExpr = 100,
/**
* \brief An expression whose specific kind is not exposed via this
* interface.
*
* Unexposed expressions have the same operations as any other kind
* of expression; one can extract their location information,
* spelling, children, etc. However, the specific kind of the
* expression is not reported.
*/
CXCursor_UnexposedExpr = 100,
/**
* \brief An expression that refers to some value declaration, such
* as a function, variable, or enumerator.
*/
CXCursor_DeclRefExpr = 101,
/**
* \brief An expression that refers to a member of a struct, union,
* class, Objective-C class, etc.
*/
CXCursor_MemberRefExpr = 102,
/** \brief An expression that calls a function. */
CXCursor_CallExpr = 103,
/** \brief An expression that sends a message to an Objective-C
object or class. */
CXCursor_ObjCMessageExpr = 104,
/** \brief An expression that represents a block literal. */
CXCursor_BlockExpr = 105,
/** \brief An integer literal.
*/
CXCursor_IntegerLiteral = 106,
/** \brief A floating point number literal.
*/
CXCursor_FloatingLiteral = 107,
/** \brief An imaginary number literal.
*/
CXCursor_ImaginaryLiteral = 108,
/** \brief A string literal.
*/
CXCursor_StringLiteral = 109,
/** \brief A character literal.
*/
CXCursor_CharacterLiteral = 110,
/** \brief A parenthesized expression, e.g. "(1)".
*
* This AST node is only formed if full location information is requested.
*/
CXCursor_ParenExpr = 111,
/** \brief This represents the unary-expression's (except sizeof and
* alignof).
*/
CXCursor_UnaryOperator = 112,
/** \brief [C99 6.5.2.1] Array Subscripting.
*/
CXCursor_ArraySubscriptExpr = 113,
/** \brief A builtin binary operation expression such as "x + y" or
* "x <= y".
*/
CXCursor_BinaryOperator = 114,
/** \brief Compound assignment such as "+=".
*/
CXCursor_CompoundAssignOperator = 115,
/** \brief The ?: ternary operator.
*/
CXCursor_ConditionalOperator = 116,
/** \brief An explicit cast in C (C99 6.5.4) or a C-style cast in C++
* (C++ [expr.cast]), which uses the syntax (Type)expr.
*
* For example: (int)f.
*/
CXCursor_CStyleCastExpr = 117,
/** \brief [C99 6.5.2.5]
*/
CXCursor_CompoundLiteralExpr = 118,
/** \brief Describes an C or C++ initializer list.
*/
CXCursor_InitListExpr = 119,
/** \brief The GNU address of label extension, representing &&label.
*/
CXCursor_AddrLabelExpr = 120,
/** \brief This is the GNU Statement Expression extension: ({int X=4; X;})
*/
CXCursor_StmtExpr = 121,
/** \brief Represents a C11 generic selection.
*/
CXCursor_GenericSelectionExpr = 122,
/** \brief Implements the GNU __null extension, which is a name for a null
* pointer constant that has integral type (e.g., int or long) and is the same
* size and alignment as a pointer.
*
* The __null extension is typically only used by system headers, which define
* NULL as __null in C++ rather than using 0 (which is an integer that may not
* match the size of a pointer).
*/
CXCursor_GNUNullExpr = 123,
/** \brief C++'s static_cast<> expression.
*/
CXCursor_CXXStaticCastExpr = 124,
/** \brief C++'s dynamic_cast<> expression.
*/
CXCursor_CXXDynamicCastExpr = 125,
/** \brief C++'s reinterpret_cast<> expression.
*/
CXCursor_CXXReinterpretCastExpr = 126,
/** \brief C++'s const_cast<> expression.
*/
CXCursor_CXXConstCastExpr = 127,
/** \brief Represents an explicit C++ type conversion that uses "functional"
* notion (C++ [expr.type.conv]).
*
* Example:
* \code
* x = int(0.5);
* \endcode
*/
CXCursor_CXXFunctionalCastExpr = 128,
/** \brief A C++ typeid expression (C++ [expr.typeid]).
*/
CXCursor_CXXTypeidExpr = 129,
/** \brief [C++ 2.13.5] C++ Boolean Literal.
*/
CXCursor_CXXBoolLiteralExpr = 130,
/** \brief [C++0x 2.14.7] C++ Pointer Literal.
*/
CXCursor_CXXNullPtrLiteralExpr = 131,
/** \brief Represents the "this" expression in C++
*/
CXCursor_CXXThisExpr = 132,
/** \brief [C++ 15] C++ Throw Expression.
*
* This handles 'throw' and 'throw' assignment-expression. When
* assignment-expression isn't present, Op will be null.
*/
CXCursor_CXXThrowExpr = 133,
/** \brief A new expression for memory allocation and constructor calls, e.g:
* "new CXXNewExpr(foo)".
*/
CXCursor_CXXNewExpr = 134,
/** \brief A delete expression for memory deallocation and destructor calls,
* e.g. "delete[] pArray".
*/
CXCursor_CXXDeleteExpr = 135,
/** \brief A unary expression.
*/
CXCursor_UnaryExpr = 136,
/** \brief An Objective-C string literal i.e. @"foo".
*/
CXCursor_ObjCStringLiteral = 137,
/** \brief An Objective-C \@encode expression.
*/
CXCursor_ObjCEncodeExpr = 138,
/** \brief An Objective-C \@selector expression.
*/
CXCursor_ObjCSelectorExpr = 139,
/** \brief An Objective-C \@protocol expression.
*/
CXCursor_ObjCProtocolExpr = 140,
/** \brief An Objective-C "bridged" cast expression, which casts between
* Objective-C pointers and C pointers, transferring ownership in the process.
*
* \code
* NSString *str = (__bridge_transfer NSString *)CFCreateString();
* \endcode
*/
CXCursor_ObjCBridgedCastExpr = 141,
/** \brief Represents a C++0x pack expansion that produces a sequence of
* expressions.
*
* A pack expansion expression contains a pattern (which itself is an
* expression) followed by an ellipsis. For example:
*
* \code
* template<typename F, typename ...Types>
* void forward(F f, Types &&...args) {
* f(static_cast<Types&&>(args)...);
* }
* \endcode
*/
CXCursor_PackExpansionExpr = 142,
/** \brief Represents an expression that computes the length of a parameter
* pack.
*
* \code
* template<typename ...Types>
* struct count {
* static const unsigned value = sizeof...(Types);
* };
* \endcode
*/
CXCursor_SizeOfPackExpr = 143,
/* \brief Represents a C++ lambda expression that produces a local function
* object.
*
* \code
* void abssort(float *x, unsigned N) {
* std::sort(x, x + N,
* [](float a, float b) {
* return std::abs(a) < std::abs(b);
* });
* }
* \endcode
*/
CXCursor_LambdaExpr = 144,
/** \brief Objective-c Boolean Literal.
*/
CXCursor_ObjCBoolLiteralExpr = 145,
/** \brief Represents the "self" expression in an Objective-C method.
*/
CXCursor_ObjCSelfExpr = 146,
CXCursor_LastExpr = CXCursor_ObjCSelfExpr,
/* Statements */
CXCursor_FirstStmt = 200,
/**
* \brief A statement whose specific kind is not exposed via this
* interface.
*
* Unexposed statements have the same operations as any other kind of
* statement; one can extract their location information, spelling,
* children, etc. However, the specific kind of the statement is not
* reported.
*/
CXCursor_UnexposedStmt = 200,
/** \brief A labelled statement in a function.
*
* This cursor kind is used to describe the "start_over:" label statement in
* the following example:
*
* \code
* start_over:
* ++counter;
* \endcode
*
*/
CXCursor_LabelStmt = 201,
/** \brief A group of statements like { stmt stmt }.
*
* This cursor kind is used to describe compound statements, e.g. function
* bodies.
*/
CXCursor_CompoundStmt = 202,
/** \brief A case statement.
*/
CXCursor_CaseStmt = 203,
/** \brief A default statement.
*/
CXCursor_DefaultStmt = 204,
/** \brief An if statement
*/
CXCursor_IfStmt = 205,
/** \brief A switch statement.
*/
CXCursor_SwitchStmt = 206,
/** \brief A while statement.
*/
CXCursor_WhileStmt = 207,
/** \brief A do statement.
*/
CXCursor_DoStmt = 208,
/** \brief A for statement.
*/
CXCursor_ForStmt = 209,
/** \brief A goto statement.
*/
CXCursor_GotoStmt = 210,
/** \brief An indirect goto statement.
*/
CXCursor_IndirectGotoStmt = 211,
/** \brief A continue statement.
*/
CXCursor_ContinueStmt = 212,
/** \brief A break statement.
*/
CXCursor_BreakStmt = 213,
/** \brief A return statement.
*/
CXCursor_ReturnStmt = 214,
/** \brief A GCC inline assembly statement extension.
*/
CXCursor_GCCAsmStmt = 215,
CXCursor_AsmStmt = CXCursor_GCCAsmStmt,
/** \brief Objective-C's overall \@try-\@catch-\@finally statement.
*/
CXCursor_ObjCAtTryStmt = 216,
/** \brief Objective-C's \@catch statement.
*/
CXCursor_ObjCAtCatchStmt = 217,
/** \brief Objective-C's \@finally statement.
*/
CXCursor_ObjCAtFinallyStmt = 218,
/** \brief Objective-C's \@throw statement.
*/
CXCursor_ObjCAtThrowStmt = 219,
/** \brief Objective-C's \@synchronized statement.
*/
CXCursor_ObjCAtSynchronizedStmt = 220,
/** \brief Objective-C's autorelease pool statement.
*/
CXCursor_ObjCAutoreleasePoolStmt = 221,
/** \brief Objective-C's collection statement.
*/
CXCursor_ObjCForCollectionStmt = 222,
/** \brief C++'s catch statement.
*/
CXCursor_CXXCatchStmt = 223,
/** \brief C++'s try statement.
*/
CXCursor_CXXTryStmt = 224,
/** \brief C++'s for (* : *) statement.
*/
CXCursor_CXXForRangeStmt = 225,
/** \brief Windows Structured Exception Handling's try statement.
*/
CXCursor_SEHTryStmt = 226,
/** \brief Windows Structured Exception Handling's except statement.
*/
CXCursor_SEHExceptStmt = 227,
/** \brief Windows Structured Exception Handling's finally statement.
*/
CXCursor_SEHFinallyStmt = 228,
/** \brief A MS inline assembly statement extension.
*/
CXCursor_MSAsmStmt = 229,
/** \brief The null statement ";": C99 6.8.3p3.
*
* This cursor kind is used to describe the null statement.
*/
CXCursor_NullStmt = 230,
/** \brief Adaptor class for mixing declarations with statements and
* expressions.
*/
CXCursor_DeclStmt = 231,
/** \brief OpenMP parallel directive.
*/
CXCursor_OMPParallelDirective = 232,
/** \brief OpenMP SIMD directive.
*/
CXCursor_OMPSimdDirective = 233,
/** \brief OpenMP for directive.
*/
CXCursor_OMPForDirective = 234,
/** \brief OpenMP sections directive.
*/
CXCursor_OMPSectionsDirective = 235,
/** \brief OpenMP section directive.
*/
CXCursor_OMPSectionDirective = 236,
/** \brief OpenMP single directive.
*/
CXCursor_OMPSingleDirective = 237,
/** \brief OpenMP parallel for directive.
*/
CXCursor_OMPParallelForDirective = 238,
/** \brief OpenMP parallel sections directive.
*/
CXCursor_OMPParallelSectionsDirective = 239,
/** \brief OpenMP task directive.
*/
CXCursor_OMPTaskDirective = 240,
/** \brief OpenMP master directive.
*/
CXCursor_OMPMasterDirective = 241,
/** \brief OpenMP critical directive.
*/
CXCursor_OMPCriticalDirective = 242,
/** \brief OpenMP taskyield directive.
*/
CXCursor_OMPTaskyieldDirective = 243,
/** \brief OpenMP barrier directive.
*/
CXCursor_OMPBarrierDirective = 244,
/** \brief OpenMP taskwait directive.
*/
CXCursor_OMPTaskwaitDirective = 245,
/** \brief OpenMP flush directive.
*/
CXCursor_OMPFlushDirective = 246,
/** \brief Windows Structured Exception Handling's leave statement.
*/
CXCursor_SEHLeaveStmt = 247,
/** \brief OpenMP ordered directive.
*/
CXCursor_OMPOrderedDirective = 248,
/** \brief OpenMP atomic directive.
*/
CXCursor_OMPAtomicDirective = 249,
/** \brief OpenMP for SIMD directive.
*/
CXCursor_OMPForSimdDirective = 250,
/** \brief OpenMP parallel for SIMD directive.
*/
CXCursor_OMPParallelForSimdDirective = 251,
/** \brief OpenMP target directive.
*/
CXCursor_OMPTargetDirective = 252,
/** \brief OpenMP teams directive.
*/
CXCursor_OMPTeamsDirective = 253,
/** \brief OpenMP taskgroup directive.
*/
CXCursor_OMPTaskgroupDirective = 254,
/** \brief OpenMP cancellation point directive.
*/
CXCursor_OMPCancellationPointDirective = 255,
/** \brief OpenMP cancel directive.
*/
CXCursor_OMPCancelDirective = 256,
CXCursor_LastStmt = CXCursor_OMPCancelDirective,
/**
* \brief Cursor that represents the translation unit itself.
*
* The translation unit cursor exists primarily to act as the root
* cursor for traversing the contents of a translation unit.
*/
CXCursor_TranslationUnit = 300,
/* Attributes */
CXCursor_FirstAttr = 400,
/**
* \brief An attribute whose specific kind is not exposed via this
* interface.
*/
CXCursor_UnexposedAttr = 400,
CXCursor_IBActionAttr = 401,
CXCursor_IBOutletAttr = 402,
CXCursor_IBOutletCollectionAttr = 403,
CXCursor_CXXFinalAttr = 404,
CXCursor_CXXOverrideAttr = 405,
CXCursor_AnnotateAttr = 406,
CXCursor_AsmLabelAttr = 407,
CXCursor_PackedAttr = 408,
CXCursor_PureAttr = 409,
CXCursor_ConstAttr = 410,
CXCursor_NoDuplicateAttr = 411,
CXCursor_CUDAConstantAttr = 412,
CXCursor_CUDADeviceAttr = 413,
CXCursor_CUDAGlobalAttr = 414,
CXCursor_CUDAHostAttr = 415,
CXCursor_CUDASharedAttr = 416,
CXCursor_LastAttr = CXCursor_CUDASharedAttr,
/* Preprocessing */
CXCursor_PreprocessingDirective = 500,
CXCursor_MacroDefinition = 501,
CXCursor_MacroExpansion = 502,
CXCursor_MacroInstantiation = CXCursor_MacroExpansion,
CXCursor_InclusionDirective = 503,
CXCursor_FirstPreprocessing = CXCursor_PreprocessingDirective,
CXCursor_LastPreprocessing = CXCursor_InclusionDirective,
/* Extra Declarations */
/**
* \brief A module import declaration.
*/
CXCursor_ModuleImportDecl = 600,
CXCursor_FirstExtraDecl = CXCursor_ModuleImportDecl,
CXCursor_LastExtraDecl = CXCursor_ModuleImportDecl,
/**
* \brief A code completion overload candidate.
*/
CXCursor_OverloadCandidate = 700
};
/**
* \brief A cursor representing some element in the abstract syntax tree for
* a translation unit.
*
* The cursor abstraction unifies the different kinds of entities in a
* program--declaration, statements, expressions, references to declarations,
* etc.--under a single "cursor" abstraction with a common set of operations.
* Common operation for a cursor include: getting the physical location in
* a source file where the cursor points, getting the name associated with a
* cursor, and retrieving cursors for any child nodes of a particular cursor.
*
* Cursors can be produced in two specific ways.
* clang_getTranslationUnitCursor() produces a cursor for a translation unit,
* from which one can use clang_visitChildren() to explore the rest of the
* translation unit. clang_getCursor() maps from a physical source location
* to the entity that resides at that location, allowing one to map from the
* source code into the AST.
*/
typedef struct {
enum CXCursorKind kind;
int xdata;
const void *data[3];
} CXCursor;
/**
* \defgroup CINDEX_CURSOR_MANIP Cursor manipulations
*
* @{
*/
/**
* \brief Retrieve the NULL cursor, which represents no entity.
*/
CINDEX_LINKAGE CXCursor clang_getNullCursor(void);
/**
* \brief Retrieve the cursor that represents the given translation unit.
*
* The translation unit cursor can be used to start traversing the
* various declarations within the given translation unit.
*/
CINDEX_LINKAGE CXCursor clang_getTranslationUnitCursor(CXTranslationUnit);
/**
* \brief Determine whether two cursors are equivalent.
*/
CINDEX_LINKAGE unsigned clang_equalCursors(CXCursor, CXCursor);
/**
* \brief Returns non-zero if \p cursor is null.
*/
CINDEX_LINKAGE int clang_Cursor_isNull(CXCursor cursor);
/**
* \brief Compute a hash value for the given cursor.
*/
CINDEX_LINKAGE unsigned clang_hashCursor(CXCursor);
/**
* \brief Retrieve the kind of the given cursor.
*/
CINDEX_LINKAGE enum CXCursorKind clang_getCursorKind(CXCursor);
/**
* \brief Determine whether the given cursor kind represents a declaration.
*/
CINDEX_LINKAGE unsigned clang_isDeclaration(enum CXCursorKind);
/**
* \brief Determine whether the given cursor kind represents a simple
* reference.
*
* Note that other kinds of cursors (such as expressions) can also refer to
* other cursors. Use clang_getCursorReferenced() to determine whether a
* particular cursor refers to another entity.
*/
CINDEX_LINKAGE unsigned clang_isReference(enum CXCursorKind);
/**
* \brief Determine whether the given cursor kind represents an expression.
*/
CINDEX_LINKAGE unsigned clang_isExpression(enum CXCursorKind);
/**
* \brief Determine whether the given cursor kind represents a statement.
*/
CINDEX_LINKAGE unsigned clang_isStatement(enum CXCursorKind);
/**
* \brief Determine whether the given cursor kind represents an attribute.
*/
CINDEX_LINKAGE unsigned clang_isAttribute(enum CXCursorKind);
/**
* \brief Determine whether the given cursor kind represents an invalid
* cursor.
*/
CINDEX_LINKAGE unsigned clang_isInvalid(enum CXCursorKind);
/**
* \brief Determine whether the given cursor kind represents a translation
* unit.
*/
CINDEX_LINKAGE unsigned clang_isTranslationUnit(enum CXCursorKind);
/***
* \brief Determine whether the given cursor represents a preprocessing
* element, such as a preprocessor directive or macro instantiation.
*/
CINDEX_LINKAGE unsigned clang_isPreprocessing(enum CXCursorKind);
/***
* \brief Determine whether the given cursor represents a currently
* unexposed piece of the AST (e.g., CXCursor_UnexposedStmt).
*/
CINDEX_LINKAGE unsigned clang_isUnexposed(enum CXCursorKind);
/**
* \brief Describe the linkage of the entity referred to by a cursor.
*/
enum CXLinkageKind {
/** \brief This value indicates that no linkage information is available
* for a provided CXCursor. */
CXLinkage_Invalid,
/**
* \brief This is the linkage for variables, parameters, and so on that
* have automatic storage. This covers normal (non-extern) local variables.
*/
CXLinkage_NoLinkage,
/** \brief This is the linkage for static variables and static functions. */
CXLinkage_Internal,
/** \brief This is the linkage for entities with external linkage that live
* in C++ anonymous namespaces.*/
CXLinkage_UniqueExternal,
/** \brief This is the linkage for entities with true, external linkage. */
CXLinkage_External
};
/**
* \brief Determine the linkage of the entity referred to by a given cursor.
*/
CINDEX_LINKAGE enum CXLinkageKind clang_getCursorLinkage(CXCursor cursor);
/**
* \brief Determine the availability of the entity that this cursor refers to,
* taking the current target platform into account.
*
* \param cursor The cursor to query.
*
* \returns The availability of the cursor.
*/
CINDEX_LINKAGE enum CXAvailabilityKind
clang_getCursorAvailability(CXCursor cursor);
/**
* Describes the availability of a given entity on a particular platform, e.g.,
* a particular class might only be available on Mac OS 10.7 or newer.
*/
typedef struct CXPlatformAvailability {
/**
* \brief A string that describes the platform for which this structure
* provides availability information.
*
* Possible values are "ios" or "macosx".
*/
CXString Platform;
/**
* \brief The version number in which this entity was introduced.
*/
CXVersion Introduced;
/**
* \brief The version number in which this entity was deprecated (but is
* still available).
*/
CXVersion Deprecated;
/**
* \brief The version number in which this entity was obsoleted, and therefore
* is no longer available.
*/
CXVersion Obsoleted;
/**
* \brief Whether the entity is unconditionally unavailable on this platform.
*/
int Unavailable;
/**
* \brief An optional message to provide to a user of this API, e.g., to
* suggest replacement APIs.
*/
CXString Message;
} CXPlatformAvailability;
/**
* \brief Determine the availability of the entity that this cursor refers to
* on any platforms for which availability information is known.
*
* \param cursor The cursor to query.
*
* \param always_deprecated If non-NULL, will be set to indicate whether the
* entity is deprecated on all platforms.
*
* \param deprecated_message If non-NULL, will be set to the message text
* provided along with the unconditional deprecation of this entity. The client
* is responsible for deallocating this string.
*
* \param always_unavailable If non-NULL, will be set to indicate whether the
* entity is unavailable on all platforms.
*
* \param unavailable_message If non-NULL, will be set to the message text
* provided along with the unconditional unavailability of this entity. The
* client is responsible for deallocating this string.
*
* \param availability If non-NULL, an array of CXPlatformAvailability instances
* that will be populated with platform availability information, up to either
* the number of platforms for which availability information is available (as
* returned by this function) or \c availability_size, whichever is smaller.
*
* \param availability_size The number of elements available in the
* \c availability array.
*
* \returns The number of platforms (N) for which availability information is
* available (which is unrelated to \c availability_size).
*
* Note that the client is responsible for calling
* \c clang_disposeCXPlatformAvailability to free each of the
* platform-availability structures returned. There are
* \c min(N, availability_size) such structures.
*/
CINDEX_LINKAGE int
clang_getCursorPlatformAvailability(CXCursor cursor,
int *always_deprecated,
CXString *deprecated_message,
int *always_unavailable,
CXString *unavailable_message,
CXPlatformAvailability *availability,
int availability_size);
/**
* \brief Free the memory associated with a \c CXPlatformAvailability structure.
*/
CINDEX_LINKAGE void
clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability);
/**
* \brief Describe the "language" of the entity referred to by a cursor.
*/
enum CXLanguageKind {
CXLanguage_Invalid = 0,
CXLanguage_C,
CXLanguage_ObjC,
CXLanguage_CPlusPlus
};
/**
* \brief Determine the "language" of the entity referred to by a given cursor.
*/
CINDEX_LINKAGE enum CXLanguageKind clang_getCursorLanguage(CXCursor cursor);
/**
* \brief Returns the translation unit that a cursor originated from.
*/
CINDEX_LINKAGE CXTranslationUnit clang_Cursor_getTranslationUnit(CXCursor);
/**
* \brief A fast container representing a set of CXCursors.
*/
typedef struct CXCursorSetImpl *CXCursorSet;
/**
* \brief Creates an empty CXCursorSet.
*/
CINDEX_LINKAGE CXCursorSet clang_createCXCursorSet(void);
/**
* \brief Disposes a CXCursorSet and releases its associated memory.
*/
CINDEX_LINKAGE void clang_disposeCXCursorSet(CXCursorSet cset);
/**
* \brief Queries a CXCursorSet to see if it contains a specific CXCursor.
*
* \returns non-zero if the set contains the specified cursor.
*/
CINDEX_LINKAGE unsigned clang_CXCursorSet_contains(CXCursorSet cset,
CXCursor cursor);
/**
* \brief Inserts a CXCursor into a CXCursorSet.
*
* \returns zero if the CXCursor was already in the set, and non-zero otherwise.
*/
CINDEX_LINKAGE unsigned clang_CXCursorSet_insert(CXCursorSet cset,
CXCursor cursor);
/**
* \brief Determine the semantic parent of the given cursor.
*
* The semantic parent of a cursor is the cursor that semantically contains
* the given \p cursor. For many declarations, the lexical and semantic parents
* are equivalent (the lexical parent is returned by
* \c clang_getCursorLexicalParent()). They diverge when declarations or
* definitions are provided out-of-line. For example:
*
* \code
* class C {
* void f();
* };
*
* void C::f() { }
* \endcode
*
* In the out-of-line definition of \c C::f, the semantic parent is
* the class \c C, of which this function is a member. The lexical parent is
* the place where the declaration actually occurs in the source code; in this
* case, the definition occurs in the translation unit. In general, the
* lexical parent for a given entity can change without affecting the semantics
* of the program, and the lexical parent of different declarations of the
* same entity may be different. Changing the semantic parent of a declaration,
* on the other hand, can have a major impact on semantics, and redeclarations
* of a particular entity should all have the same semantic context.
*
* In the example above, both declarations of \c C::f have \c C as their
* semantic context, while the lexical context of the first \c C::f is \c C
* and the lexical context of the second \c C::f is the translation unit.
*
* For global declarations, the semantic parent is the translation unit.
*/
CINDEX_LINKAGE CXCursor clang_getCursorSemanticParent(CXCursor cursor);
/**
* \brief Determine the lexical parent of the given cursor.
*
* The lexical parent of a cursor is the cursor in which the given \p cursor
* was actually written. For many declarations, the lexical and semantic parents
* are equivalent (the semantic parent is returned by
* \c clang_getCursorSemanticParent()). They diverge when declarations or
* definitions are provided out-of-line. For example:
*
* \code
* class C {
* void f();
* };
*
* void C::f() { }
* \endcode
*
* In the out-of-line definition of \c C::f, the semantic parent is
* the class \c C, of which this function is a member. The lexical parent is
* the place where the declaration actually occurs in the source code; in this
* case, the definition occurs in the translation unit. In general, the
* lexical parent for a given entity can change without affecting the semantics
* of the program, and the lexical parent of different declarations of the
* same entity may be different. Changing the semantic parent of a declaration,
* on the other hand, can have a major impact on semantics, and redeclarations
* of a particular entity should all have the same semantic context.
*
* In the example above, both declarations of \c C::f have \c C as their
* semantic context, while the lexical context of the first \c C::f is \c C
* and the lexical context of the second \c C::f is the translation unit.
*
* For declarations written in the global scope, the lexical parent is
* the translation unit.
*/
CINDEX_LINKAGE CXCursor clang_getCursorLexicalParent(CXCursor cursor);
/**
* \brief Determine the set of methods that are overridden by the given
* method.
*
* In both Objective-C and C++, a method (aka virtual member function,
* in C++) can override a virtual method in a base class. For
* Objective-C, a method is said to override any method in the class's
* base class, its protocols, or its categories' protocols, that has the same
* selector and is of the same kind (class or instance).
* If no such method exists, the search continues to the class's superclass,
* its protocols, and its categories, and so on. A method from an Objective-C
* implementation is considered to override the same methods as its
* corresponding method in the interface.
*
* For C++, a virtual member function overrides any virtual member
* function with the same signature that occurs in its base
* classes. With multiple inheritance, a virtual member function can
* override several virtual member functions coming from different
* base classes.
*
* In all cases, this function determines the immediate overridden
* method, rather than all of the overridden methods. For example, if
* a method is originally declared in a class A, then overridden in B
* (which in inherits from A) and also in C (which inherited from B),
* then the only overridden method returned from this function when
* invoked on C's method will be B's method. The client may then
* invoke this function again, given the previously-found overridden
* methods, to map out the complete method-override set.
*
* \param cursor A cursor representing an Objective-C or C++
* method. This routine will compute the set of methods that this
* method overrides.
*
* \param overridden A pointer whose pointee will be replaced with a
* pointer to an array of cursors, representing the set of overridden
* methods. If there are no overridden methods, the pointee will be
* set to NULL. The pointee must be freed via a call to
* \c clang_disposeOverriddenCursors().
*
* \param num_overridden A pointer to the number of overridden
* functions, will be set to the number of overridden functions in the
* array pointed to by \p overridden.
*/
CINDEX_LINKAGE void clang_getOverriddenCursors(CXCursor cursor,
CXCursor **overridden,
unsigned *num_overridden);
/**
* \brief Free the set of overridden cursors returned by \c
* clang_getOverriddenCursors().
*/
CINDEX_LINKAGE void clang_disposeOverriddenCursors(CXCursor *overridden);
/**
* \brief Retrieve the file that is included by the given inclusion directive
* cursor.
*/
CINDEX_LINKAGE CXFile clang_getIncludedFile(CXCursor cursor);
/**
* @}
*/
/**
* \defgroup CINDEX_CURSOR_SOURCE Mapping between cursors and source code
*
* Cursors represent a location within the Abstract Syntax Tree (AST). These
* routines help map between cursors and the physical locations where the
* described entities occur in the source code. The mapping is provided in
* both directions, so one can map from source code to the AST and back.
*
* @{
*/
/**
* \brief Map a source location to the cursor that describes the entity at that
* location in the source code.
*
* clang_getCursor() maps an arbitrary source location within a translation
* unit down to the most specific cursor that describes the entity at that
* location. For example, given an expression \c x + y, invoking
* clang_getCursor() with a source location pointing to "x" will return the
* cursor for "x"; similarly for "y". If the cursor points anywhere between
* "x" or "y" (e.g., on the + or the whitespace around it), clang_getCursor()
* will return a cursor referring to the "+" expression.
*
* \returns a cursor representing the entity at the given source location, or
* a NULL cursor if no such entity can be found.
*/
CINDEX_LINKAGE CXCursor clang_getCursor(CXTranslationUnit, CXSourceLocation);
/**
* \brief Retrieve the physical location of the source constructor referenced
* by the given cursor.
*
* The location of a declaration is typically the location of the name of that
* declaration, where the name of that declaration would occur if it is
* unnamed, or some keyword that introduces that particular declaration.
* The location of a reference is where that reference occurs within the
* source code.
*/
CINDEX_LINKAGE CXSourceLocation clang_getCursorLocation(CXCursor);
/**
* \brief Retrieve the physical extent of the source construct referenced by
* the given cursor.
*
* The extent of a cursor starts with the file/line/column pointing at the
* first character within the source construct that the cursor refers to and
* ends with the last character within that source construct. For a
* declaration, the extent covers the declaration itself. For a reference,
* the extent covers the location of the reference (e.g., where the referenced
* entity was actually used).
*/
CINDEX_LINKAGE CXSourceRange clang_getCursorExtent(CXCursor);
/**
* @}
*/
/**
* \defgroup CINDEX_TYPES Type information for CXCursors
*
* @{
*/
/**
* \brief Describes the kind of type
*/
enum CXTypeKind {
/**
* \brief Represents an invalid type (e.g., where no type is available).
*/
CXType_Invalid = 0,
/**
* \brief A type whose specific kind is not exposed via this
* interface.
*/
CXType_Unexposed = 1,
/* Builtin types */
CXType_Void = 2,
CXType_Bool = 3,
CXType_Char_U = 4,
CXType_UChar = 5,
CXType_Char16 = 6,
CXType_Char32 = 7,
CXType_UShort = 8,
CXType_UInt = 9,
CXType_ULong = 10,
CXType_ULongLong = 11,
CXType_UInt128 = 12,
CXType_Char_S = 13,
CXType_SChar = 14,
CXType_WChar = 15,
CXType_Short = 16,
CXType_Int = 17,
CXType_Long = 18,
CXType_LongLong = 19,
CXType_Int128 = 20,
CXType_Float = 21,
CXType_Double = 22,
CXType_LongDouble = 23,
CXType_NullPtr = 24,
CXType_Overload = 25,
CXType_Dependent = 26,
CXType_ObjCId = 27,
CXType_ObjCClass = 28,
CXType_ObjCSel = 29,
CXType_FirstBuiltin = CXType_Void,
CXType_LastBuiltin = CXType_ObjCSel,
CXType_Complex = 100,
CXType_Pointer = 101,
CXType_BlockPointer = 102,
CXType_LValueReference = 103,
CXType_RValueReference = 104,
CXType_Record = 105,
CXType_Enum = 106,
CXType_Typedef = 107,
CXType_ObjCInterface = 108,
CXType_ObjCObjectPointer = 109,
CXType_FunctionNoProto = 110,
CXType_FunctionProto = 111,
CXType_ConstantArray = 112,
CXType_Vector = 113,
CXType_IncompleteArray = 114,
CXType_VariableArray = 115,
CXType_DependentSizedArray = 116,
CXType_MemberPointer = 117
};
/**
* \brief Describes the calling convention of a function type
*/
enum CXCallingConv {
CXCallingConv_Default = 0,
CXCallingConv_C = 1,
CXCallingConv_X86StdCall = 2,
CXCallingConv_X86FastCall = 3,
CXCallingConv_X86ThisCall = 4,
CXCallingConv_X86Pascal = 5,
CXCallingConv_AAPCS = 6,
CXCallingConv_AAPCS_VFP = 7,
/* Value 8 was PnaclCall, but it was never used, so it could safely be re-used. */
CXCallingConv_IntelOclBicc = 9,
CXCallingConv_X86_64Win64 = 10,
CXCallingConv_X86_64SysV = 11,
CXCallingConv_X86VectorCall = 12,
CXCallingConv_Invalid = 100,
CXCallingConv_Unexposed = 200
};
/**
* \brief The type of an element in the abstract syntax tree.
*
*/
typedef struct {
enum CXTypeKind kind;
void *data[2];
} CXType;
/**
* \brief Retrieve the type of a CXCursor (if any).
*/
CINDEX_LINKAGE CXType clang_getCursorType(CXCursor C);
/**
* \brief Pretty-print the underlying type using the rules of the
* language of the translation unit from which it came.
*
* If the type is invalid, an empty string is returned.
*/
CINDEX_LINKAGE CXString clang_getTypeSpelling(CXType CT);
/**
* \brief Retrieve the underlying type of a typedef declaration.
*
* If the cursor does not reference a typedef declaration, an invalid type is
* returned.
*/
CINDEX_LINKAGE CXType clang_getTypedefDeclUnderlyingType(CXCursor C);
/**
* \brief Retrieve the integer type of an enum declaration.
*
* If the cursor does not reference an enum declaration, an invalid type is
* returned.
*/
CINDEX_LINKAGE CXType clang_getEnumDeclIntegerType(CXCursor C);
/**
* \brief Retrieve the integer value of an enum constant declaration as a signed
* long long.
*
* If the cursor does not reference an enum constant declaration, LLONG_MIN is returned.
* Since this is also potentially a valid constant value, the kind of the cursor
* must be verified before calling this function.
*/
CINDEX_LINKAGE long long clang_getEnumConstantDeclValue(CXCursor C);
/**
* \brief Retrieve the integer value of an enum constant declaration as an unsigned
* long long.
*
* If the cursor does not reference an enum constant declaration, ULLONG_MAX is returned.
* Since this is also potentially a valid constant value, the kind of the cursor
* must be verified before calling this function.
*/
CINDEX_LINKAGE unsigned long long clang_getEnumConstantDeclUnsignedValue(CXCursor C);
/**
* \brief Retrieve the bit width of a bit field declaration as an integer.
*
* If a cursor that is not a bit field declaration is passed in, -1 is returned.
*/
CINDEX_LINKAGE int clang_getFieldDeclBitWidth(CXCursor C);
/**
* \brief Retrieve the number of non-variadic arguments associated with a given
* cursor.
*
* The number of arguments can be determined for calls as well as for
* declarations of functions or methods. For other cursors -1 is returned.
*/
CINDEX_LINKAGE int clang_Cursor_getNumArguments(CXCursor C);
/**
* \brief Retrieve the argument cursor of a function or method.
*
* The argument cursor can be determined for calls as well as for declarations
* of functions or methods. For other cursors and for invalid indices, an
* invalid cursor is returned.
*/
CINDEX_LINKAGE CXCursor clang_Cursor_getArgument(CXCursor C, unsigned i);
/**
* \brief Describes the kind of a template argument.
*
* See the definition of llvm::clang::TemplateArgument::ArgKind for full
* element descriptions.
*/
enum CXTemplateArgumentKind {
CXTemplateArgumentKind_Null,
CXTemplateArgumentKind_Type,
CXTemplateArgumentKind_Declaration,
CXTemplateArgumentKind_NullPtr,
CXTemplateArgumentKind_Integral,
CXTemplateArgumentKind_Template,
CXTemplateArgumentKind_TemplateExpansion,
CXTemplateArgumentKind_Expression,
CXTemplateArgumentKind_Pack,
/* Indicates an error case, preventing the kind from being deduced. */
CXTemplateArgumentKind_Invalid
};
/**
*\brief Returns the number of template args of a function decl representing a
* template specialization.
*
* If the argument cursor cannot be converted into a template function
* declaration, -1 is returned.
*
* For example, for the following declaration and specialization:
* template <typename T, int kInt, bool kBool>
* void foo() { ... }
*
* template <>
* void foo<float, -7, true>();
*
* The value 3 would be returned from this call.
*/
CINDEX_LINKAGE int clang_Cursor_getNumTemplateArguments(CXCursor C);
/**
* \brief Retrieve the kind of the I'th template argument of the CXCursor C.
*
* If the argument CXCursor does not represent a FunctionDecl, an invalid
* template argument kind is returned.
*
* For example, for the following declaration and specialization:
* template <typename T, int kInt, bool kBool>
* void foo() { ... }
*
* template <>
* void foo<float, -7, true>();
*
* For I = 0, 1, and 2, Type, Integral, and Integral will be returned,
* respectively.
*/
CINDEX_LINKAGE enum CXTemplateArgumentKind clang_Cursor_getTemplateArgumentKind(
CXCursor C, unsigned I);
/**
* \brief Retrieve a CXType representing the type of a TemplateArgument of a
* function decl representing a template specialization.
*
* If the argument CXCursor does not represent a FunctionDecl whose I'th
* template argument has a kind of CXTemplateArgKind_Integral, an invalid type
* is returned.
*
* For example, for the following declaration and specialization:
* template <typename T, int kInt, bool kBool>
* void foo() { ... }
*
* template <>
* void foo<float, -7, true>();
*
* If called with I = 0, "float", will be returned.
* Invalid types will be returned for I == 1 or 2.
*/
CINDEX_LINKAGE CXType clang_Cursor_getTemplateArgumentType(CXCursor C,
unsigned I);
/**
* \brief Retrieve the value of an Integral TemplateArgument (of a function
* decl representing a template specialization) as a signed long long.
*
* It is undefined to call this function on a CXCursor that does not represent a
* FunctionDecl or whose I'th template argument is not an integral value.
*
* For example, for the following declaration and specialization:
* template <typename T, int kInt, bool kBool>
* void foo() { ... }
*
* template <>
* void foo<float, -7, true>();
*
* If called with I = 1 or 2, -7 or true will be returned, respectively.
* For I == 0, this function's behavior is undefined.
*/
CINDEX_LINKAGE long long clang_Cursor_getTemplateArgumentValue(CXCursor C,
unsigned I);
/**
* \brief Retrieve the value of an Integral TemplateArgument (of a function
* decl representing a template specialization) as an unsigned long long.
*
* It is undefined to call this function on a CXCursor that does not represent a
* FunctionDecl or whose I'th template argument is not an integral value.
*
* For example, for the following declaration and specialization:
* template <typename T, int kInt, bool kBool>
* void foo() { ... }
*
* template <>
* void foo<float, 2147483649, true>();
*
* If called with I = 1 or 2, 2147483649 or true will be returned, respectively.
* For I == 0, this function's behavior is undefined.
*/
CINDEX_LINKAGE unsigned long long clang_Cursor_getTemplateArgumentUnsignedValue(
CXCursor C, unsigned I);
/**
* \brief Determine whether two CXTypes represent the same type.
*
* \returns non-zero if the CXTypes represent the same type and
* zero otherwise.
*/
CINDEX_LINKAGE unsigned clang_equalTypes(CXType A, CXType B);
/**
* \brief Return the canonical type for a CXType.
*
* Clang's type system explicitly models typedefs and all the ways
* a specific type can be represented. The canonical type is the underlying
* type with all the "sugar" removed. For example, if 'T' is a typedef
* for 'int', the canonical type for 'T' would be 'int'.
*/
CINDEX_LINKAGE CXType clang_getCanonicalType(CXType T);
/**
* \brief Determine whether a CXType has the "const" qualifier set,
* without looking through typedefs that may have added "const" at a
* different level.
*/
CINDEX_LINKAGE unsigned clang_isConstQualifiedType(CXType T);
/**
* \brief Determine whether a CXType has the "volatile" qualifier set,
* without looking through typedefs that may have added "volatile" at
* a different level.
*/
CINDEX_LINKAGE unsigned clang_isVolatileQualifiedType(CXType T);
/**
* \brief Determine whether a CXType has the "restrict" qualifier set,
* without looking through typedefs that may have added "restrict" at a
* different level.
*/
CINDEX_LINKAGE unsigned clang_isRestrictQualifiedType(CXType T);
/**
* \brief For pointer types, returns the type of the pointee.
*/
CINDEX_LINKAGE CXType clang_getPointeeType(CXType T);
/**
* \brief Return the cursor for the declaration of the given type.
*/
CINDEX_LINKAGE CXCursor clang_getTypeDeclaration(CXType T);
/**
* Returns the Objective-C type encoding for the specified declaration.
*/
CINDEX_LINKAGE CXString clang_getDeclObjCTypeEncoding(CXCursor C);
/**
* \brief Retrieve the spelling of a given CXTypeKind.
*/
CINDEX_LINKAGE CXString clang_getTypeKindSpelling(enum CXTypeKind K);
/**
* \brief Retrieve the calling convention associated with a function type.
*
* If a non-function type is passed in, CXCallingConv_Invalid is returned.
*/
CINDEX_LINKAGE enum CXCallingConv clang_getFunctionTypeCallingConv(CXType T);
/**
* \brief Retrieve the return type associated with a function type.
*
* If a non-function type is passed in, an invalid type is returned.
*/
CINDEX_LINKAGE CXType clang_getResultType(CXType T);
/**
* \brief Retrieve the number of non-variadic parameters associated with a
* function type.
*
* If a non-function type is passed in, -1 is returned.
*/
CINDEX_LINKAGE int clang_getNumArgTypes(CXType T);
/**
* \brief Retrieve the type of a parameter of a function type.
*
* If a non-function type is passed in or the function does not have enough
* parameters, an invalid type is returned.
*/
CINDEX_LINKAGE CXType clang_getArgType(CXType T, unsigned i);
/**
* \brief Return 1 if the CXType is a variadic function type, and 0 otherwise.
*/
CINDEX_LINKAGE unsigned clang_isFunctionTypeVariadic(CXType T);
/**
* \brief Retrieve the return type associated with a given cursor.
*
* This only returns a valid type if the cursor refers to a function or method.
*/
CINDEX_LINKAGE CXType clang_getCursorResultType(CXCursor C);
/**
* \brief Return 1 if the CXType is a POD (plain old data) type, and 0
* otherwise.
*/
CINDEX_LINKAGE unsigned clang_isPODType(CXType T);
/**
* \brief Return the element type of an array, complex, or vector type.
*
* If a type is passed in that is not an array, complex, or vector type,
* an invalid type is returned.
*/
CINDEX_LINKAGE CXType clang_getElementType(CXType T);
/**
* \brief Return the number of elements of an array or vector type.
*
* If a type is passed in that is not an array or vector type,
* -1 is returned.
*/
CINDEX_LINKAGE long long clang_getNumElements(CXType T);
/**
* \brief Return the element type of an array type.
*
* If a non-array type is passed in, an invalid type is returned.
*/
CINDEX_LINKAGE CXType clang_getArrayElementType(CXType T);
/**
* \brief Return the array size of a constant array.
*
* If a non-array type is passed in, -1 is returned.
*/
CINDEX_LINKAGE long long clang_getArraySize(CXType T);
/**
* \brief List the possible error codes for \c clang_Type_getSizeOf,
* \c clang_Type_getAlignOf, \c clang_Type_getOffsetOf and
* \c clang_Cursor_getOffsetOf.
*
* A value of this enumeration type can be returned if the target type is not
* a valid argument to sizeof, alignof or offsetof.
*/
enum CXTypeLayoutError {
/**
* \brief Type is of kind CXType_Invalid.
*/
CXTypeLayoutError_Invalid = -1,
/**
* \brief The type is an incomplete Type.
*/
CXTypeLayoutError_Incomplete = -2,
/**
* \brief The type is a dependent Type.
*/
CXTypeLayoutError_Dependent = -3,
/**
* \brief The type is not a constant size type.
*/
CXTypeLayoutError_NotConstantSize = -4,
/**
* \brief The Field name is not valid for this record.
*/
CXTypeLayoutError_InvalidFieldName = -5
};
/**
* \brief Return the alignment of a type in bytes as per C++[expr.alignof]
* standard.
*
* If the type declaration is invalid, CXTypeLayoutError_Invalid is returned.
* If the type declaration is an incomplete type, CXTypeLayoutError_Incomplete
* is returned.
* If the type declaration is a dependent type, CXTypeLayoutError_Dependent is
* returned.
* If the type declaration is not a constant size type,
* CXTypeLayoutError_NotConstantSize is returned.
*/
CINDEX_LINKAGE long long clang_Type_getAlignOf(CXType T);
/**
* \brief Return the class type of an member pointer type.
*
* If a non-member-pointer type is passed in, an invalid type is returned.
*/
CINDEX_LINKAGE CXType clang_Type_getClassType(CXType T);
/**
* \brief Return the size of a type in bytes as per C++[expr.sizeof] standard.
*
* If the type declaration is invalid, CXTypeLayoutError_Invalid is returned.
* If the type declaration is an incomplete type, CXTypeLayoutError_Incomplete
* is returned.
* If the type declaration is a dependent type, CXTypeLayoutError_Dependent is
* returned.
*/
CINDEX_LINKAGE long long clang_Type_getSizeOf(CXType T);
/**
* \brief Return the offset of a field named S in a record of type T in bits
* as it would be returned by __offsetof__ as per C++11[18.2p4]
*
* If the cursor is not a record field declaration, CXTypeLayoutError_Invalid
* is returned.
* If the field's type declaration is an incomplete type,
* CXTypeLayoutError_Incomplete is returned.
* If the field's type declaration is a dependent type,
* CXTypeLayoutError_Dependent is returned.
* If the field's name S is not found,
* CXTypeLayoutError_InvalidFieldName is returned.
*/
CINDEX_LINKAGE long long clang_Type_getOffsetOf(CXType T, const char *S);
/**
* \brief Return the offset of the field represented by the Cursor.
*
* If the cursor is not a field declaration, -1 is returned.
* If the cursor semantic parent is not a record field declaration,
* CXTypeLayoutError_Invalid is returned.
* If the field's type declaration is an incomplete type,
* CXTypeLayoutError_Incomplete is returned.
* If the field's type declaration is a dependent type,
* CXTypeLayoutError_Dependent is returned.
* If the field's name S is not found,
* CXTypeLayoutError_InvalidFieldName is returned.
*/
CINDEX_LINKAGE long long clang_Cursor_getOffsetOfField(CXCursor C);
/**
* \brief Determine whether the given cursor represents an anonymous record
* declaration.
*/
CINDEX_LINKAGE unsigned clang_Cursor_isAnonymous(CXCursor C);
enum CXRefQualifierKind {
/** \brief No ref-qualifier was provided. */
CXRefQualifier_None = 0,
/** \brief An lvalue ref-qualifier was provided (\c &). */
CXRefQualifier_LValue,
/** \brief An rvalue ref-qualifier was provided (\c &&). */
CXRefQualifier_RValue
};
/**
* \brief Returns the number of template arguments for given class template
* specialization, or -1 if type \c T is not a class template specialization.
*
* Variadic argument packs count as only one argument, and can not be inspected
* further.
*/
CINDEX_LINKAGE int clang_Type_getNumTemplateArguments(CXType T);
/**
* \brief Returns the type template argument of a template class specialization
* at given index.
*
* This function only returns template type arguments and does not handle
* template template arguments or variadic packs.
*/
CINDEX_LINKAGE CXType clang_Type_getTemplateArgumentAsType(CXType T, unsigned i);
/**
* \brief Retrieve the ref-qualifier kind of a function or method.
*
* The ref-qualifier is returned for C++ functions or methods. For other types
* or non-C++ declarations, CXRefQualifier_None is returned.
*/
CINDEX_LINKAGE enum CXRefQualifierKind clang_Type_getCXXRefQualifier(CXType T);
/**
* \brief Returns non-zero if the cursor specifies a Record member that is a
* bitfield.
*/
CINDEX_LINKAGE unsigned clang_Cursor_isBitField(CXCursor C);
/**
* \brief Returns 1 if the base class specified by the cursor with kind
* CX_CXXBaseSpecifier is virtual.
*/
CINDEX_LINKAGE unsigned clang_isVirtualBase(CXCursor);
/**
* \brief Represents the C++ access control level to a base class for a
* cursor with kind CX_CXXBaseSpecifier.
*/
enum CX_CXXAccessSpecifier {
CX_CXXInvalidAccessSpecifier,
CX_CXXPublic,
CX_CXXProtected,
CX_CXXPrivate
};
/**
* \brief Returns the access control level for the referenced object.
*
* If the cursor refers to a C++ declaration, its access control level within its
* parent scope is returned. Otherwise, if the cursor refers to a base specifier or
* access specifier, the specifier itself is returned.
*/
CINDEX_LINKAGE enum CX_CXXAccessSpecifier clang_getCXXAccessSpecifier(CXCursor);
/**
* \brief Represents the storage classes as declared in the source. CX_SC_Invalid
* was added for the case that the passed cursor in not a declaration.
*/
enum CX_StorageClass {
CX_SC_Invalid,
CX_SC_None,
CX_SC_Extern,
CX_SC_Static,
CX_SC_PrivateExtern,
CX_SC_OpenCLWorkGroupLocal,
CX_SC_Auto,
CX_SC_Register
};
/**
* \brief Returns the storage class for a function or variable declaration.
*
* If the passed in Cursor is not a function or variable declaration,
* CX_SC_Invalid is returned else the storage class.
*/
CINDEX_LINKAGE enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor);
/**
* \brief Determine the number of overloaded declarations referenced by a
* \c CXCursor_OverloadedDeclRef cursor.
*
* \param cursor The cursor whose overloaded declarations are being queried.
*
* \returns The number of overloaded declarations referenced by \c cursor. If it
* is not a \c CXCursor_OverloadedDeclRef cursor, returns 0.
*/
CINDEX_LINKAGE unsigned clang_getNumOverloadedDecls(CXCursor cursor);
/**
* \brief Retrieve a cursor for one of the overloaded declarations referenced
* by a \c CXCursor_OverloadedDeclRef cursor.
*
* \param cursor The cursor whose overloaded declarations are being queried.
*
* \param index The zero-based index into the set of overloaded declarations in
* the cursor.
*
* \returns A cursor representing the declaration referenced by the given
* \c cursor at the specified \c index. If the cursor does not have an
* associated set of overloaded declarations, or if the index is out of bounds,
* returns \c clang_getNullCursor();
*/
CINDEX_LINKAGE CXCursor clang_getOverloadedDecl(CXCursor cursor,
unsigned index);
/**
* @}
*/
/**
* \defgroup CINDEX_ATTRIBUTES Information for attributes
*
* @{
*/
/**
* \brief For cursors representing an iboutletcollection attribute,
* this function returns the collection element type.
*
*/
CINDEX_LINKAGE CXType clang_getIBOutletCollectionType(CXCursor);
/**
* @}
*/
/**
* \defgroup CINDEX_CURSOR_TRAVERSAL Traversing the AST with cursors
*
* These routines provide the ability to traverse the abstract syntax tree
* using cursors.
*
* @{
*/
/**
* \brief Describes how the traversal of the children of a particular
* cursor should proceed after visiting a particular child cursor.
*
* A value of this enumeration type should be returned by each
* \c CXCursorVisitor to indicate how clang_visitChildren() proceed.
*/
enum CXChildVisitResult {
/**
* \brief Terminates the cursor traversal.
*/
CXChildVisit_Break,
/**
* \brief Continues the cursor traversal with the next sibling of
* the cursor just visited, without visiting its children.
*/
CXChildVisit_Continue,
/**
* \brief Recursively traverse the children of this cursor, using
* the same visitor and client data.
*/
CXChildVisit_Recurse
};
/**
* \brief Visitor invoked for each cursor found by a traversal.
*
* This visitor function will be invoked for each cursor found by
* clang_visitCursorChildren(). Its first argument is the cursor being
* visited, its second argument is the parent visitor for that cursor,
* and its third argument is the client data provided to
* clang_visitCursorChildren().
*
* The visitor should return one of the \c CXChildVisitResult values
* to direct clang_visitCursorChildren().
*/
typedef enum CXChildVisitResult (*CXCursorVisitor)(CXCursor cursor,
CXCursor parent,
CXClientData client_data);
/**
* \brief Visit the children of a particular cursor.
*
* This function visits all the direct children of the given cursor,
* invoking the given \p visitor function with the cursors of each
* visited child. The traversal may be recursive, if the visitor returns
* \c CXChildVisit_Recurse. The traversal may also be ended prematurely, if
* the visitor returns \c CXChildVisit_Break.
*
* \param parent the cursor whose child may be visited. All kinds of
* cursors can be visited, including invalid cursors (which, by
* definition, have no children).
*
* \param visitor the visitor function that will be invoked for each
* child of \p parent.
*
* \param client_data pointer data supplied by the client, which will
* be passed to the visitor each time it is invoked.
*
* \returns a non-zero value if the traversal was terminated
* prematurely by the visitor returning \c CXChildVisit_Break.
*/
CINDEX_LINKAGE unsigned clang_visitChildren(CXCursor parent,
CXCursorVisitor visitor,
CXClientData client_data);
#ifdef __has_feature
# if __has_feature(blocks)
/**
* \brief Visitor invoked for each cursor found by a traversal.
*
* This visitor block will be invoked for each cursor found by
* clang_visitChildrenWithBlock(). Its first argument is the cursor being
* visited, its second argument is the parent visitor for that cursor.
*
* The visitor should return one of the \c CXChildVisitResult values
* to direct clang_visitChildrenWithBlock().
*/
typedef enum CXChildVisitResult
(^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
/**
* Visits the children of a cursor using the specified block. Behaves
* identically to clang_visitChildren() in all other respects.
*/
unsigned clang_visitChildrenWithBlock(CXCursor parent,
CXCursorVisitorBlock block);
# endif
#endif
/**
* @}
*/
/**
* \defgroup CINDEX_CURSOR_XREF Cross-referencing in the AST
*
* These routines provide the ability to determine references within and
* across translation units, by providing the names of the entities referenced
* by cursors, follow reference cursors to the declarations they reference,
* and associate declarations with their definitions.
*
* @{
*/
/**
* \brief Retrieve a Unified Symbol Resolution (USR) for the entity referenced
* by the given cursor.
*
* A Unified Symbol Resolution (USR) is a string that identifies a particular
* entity (function, class, variable, etc.) within a program. USRs can be
* compared across translation units to determine, e.g., when references in
* one translation refer to an entity defined in another translation unit.
*/
CINDEX_LINKAGE CXString clang_getCursorUSR(CXCursor);
/**
* \brief Construct a USR for a specified Objective-C class.
*/
CINDEX_LINKAGE CXString clang_constructUSR_ObjCClass(const char *class_name);
/**
* \brief Construct a USR for a specified Objective-C category.
*/
CINDEX_LINKAGE CXString
clang_constructUSR_ObjCCategory(const char *class_name,
const char *category_name);
/**
* \brief Construct a USR for a specified Objective-C protocol.
*/
CINDEX_LINKAGE CXString
clang_constructUSR_ObjCProtocol(const char *protocol_name);
/**
* \brief Construct a USR for a specified Objective-C instance variable and
* the USR for its containing class.
*/
CINDEX_LINKAGE CXString clang_constructUSR_ObjCIvar(const char *name,
CXString classUSR);
/**
* \brief Construct a USR for a specified Objective-C method and
* the USR for its containing class.
*/
CINDEX_LINKAGE CXString clang_constructUSR_ObjCMethod(const char *name,
unsigned isInstanceMethod,
CXString classUSR);
/**
* \brief Construct a USR for a specified Objective-C property and the USR
* for its containing class.
*/
CINDEX_LINKAGE CXString clang_constructUSR_ObjCProperty(const char *property,
CXString classUSR);
/**
* \brief Retrieve a name for the entity referenced by this cursor.
*/
CINDEX_LINKAGE CXString clang_getCursorSpelling(CXCursor);
// HLSL Change Starts
enum CXCursorFormatting {
CXCursorFormatting_Default = 0x0, // Default rules, language-insensitive formatting.
CXCursorFormatting_UseLanguageOptions = 0x1, // Language-sensitive formatting.
CXCursorFormatting_SuppressSpecifiers = 0x2, // Supresses type specifiers.
CXCursorFormatting_SuppressTagKeyword = 0x4, // Suppressed tag keyword (eg, 'class').
CXCursorFormatting_IncludeNamespaceKeyword = 0x8, // Include namespace keyword.
};
CINDEX_LINKAGE CXString LIBCLANG_CC clang_getCursorSpellingWithFormatting(CXCursor, unsigned);
// HLSL Change Stops
/**
* \brief Retrieve a range for a piece that forms the cursors spelling name.
* Most of the times there is only one range for the complete spelling but for
* Objective-C methods and Objective-C message expressions, there are multiple
* pieces for each selector identifier.
*
* \param pieceIndex the index of the spelling name piece. If this is greater
* than the actual number of pieces, it will return a NULL (invalid) range.
*
* \param options Reserved.
*/
CINDEX_LINKAGE CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor,
unsigned pieceIndex,
unsigned options);
/**
* \brief Retrieve the display name for the entity referenced by this cursor.
*
* The display name contains extra information that helps identify the cursor,
* such as the parameters of a function or template or the arguments of a
* class template specialization.
*/
CINDEX_LINKAGE CXString clang_getCursorDisplayName(CXCursor);
/** \brief For a cursor that is a reference, retrieve a cursor representing the
* entity that it references.
*
* Reference cursors refer to other entities in the AST. For example, an
* Objective-C superclass reference cursor refers to an Objective-C class.
* This function produces the cursor for the Objective-C class from the
* cursor for the superclass reference. If the input cursor is a declaration or
* definition, it returns that declaration or definition unchanged.
* Otherwise, returns the NULL cursor.
*/
CINDEX_LINKAGE CXCursor clang_getCursorReferenced(CXCursor);
/**
* \brief For a cursor that is either a reference to or a declaration
* of some entity, retrieve a cursor that describes the definition of
* that entity.
*
* Some entities can be declared multiple times within a translation
* unit, but only one of those declarations can also be a
* definition. For example, given:
*
* \code
* int f(int, int);
* int g(int x, int y) { return f(x, y); }
* int f(int a, int b) { return a + b; }
* int f(int, int);
* \endcode
*
* there are three declarations of the function "f", but only the
* second one is a definition. The clang_getCursorDefinition()
* function will take any cursor pointing to a declaration of "f"
* (the first or fourth lines of the example) or a cursor referenced
* that uses "f" (the call to "f' inside "g") and will return a
* declaration cursor pointing to the definition (the second "f"
* declaration).
*
* If given a cursor for which there is no corresponding definition,
* e.g., because there is no definition of that entity within this
* translation unit, returns a NULL cursor.
*/
CINDEX_LINKAGE CXCursor clang_getCursorDefinition(CXCursor);
/**
* \brief Determine whether the declaration pointed to by this cursor
* is also a definition of that entity.
*/
CINDEX_LINKAGE unsigned clang_isCursorDefinition(CXCursor);
/**
* \brief Retrieve the canonical cursor corresponding to the given cursor.
*
* In the C family of languages, many kinds of entities can be declared several
* times within a single translation unit. For example, a structure type can
* be forward-declared (possibly multiple times) and later defined:
*
* \code
* struct X;
* struct X;
* struct X {
* int member;
* };
* \endcode
*
* The declarations and the definition of \c X are represented by three
* different cursors, all of which are declarations of the same underlying
* entity. One of these cursor is considered the "canonical" cursor, which
* is effectively the representative for the underlying entity. One can
* determine if two cursors are declarations of the same underlying entity by
* comparing their canonical cursors.
*
* \returns The canonical cursor for the entity referred to by the given cursor.
*/
CINDEX_LINKAGE CXCursor clang_getCanonicalCursor(CXCursor);
/**
* \brief If the cursor points to a selector identifier in an Objective-C
* method or message expression, this returns the selector index.
*
* After getting a cursor with #clang_getCursor, this can be called to
* determine if the location points to a selector identifier.
*
* \returns The selector index if the cursor is an Objective-C method or message
* expression and the cursor is pointing to a selector identifier, or -1
* otherwise.
*/
CINDEX_LINKAGE int clang_Cursor_getObjCSelectorIndex(CXCursor);
/**
* \brief Given a cursor pointing to a C++ method call or an Objective-C
* message, returns non-zero if the method/message is "dynamic", meaning:
*
* For a C++ method: the call is virtual.
* For an Objective-C message: the receiver is an object instance, not 'super'
* or a specific class.
*
* If the method/message is "static" or the cursor does not point to a
* method/message, it will return zero.
*/
CINDEX_LINKAGE int clang_Cursor_isDynamicCall(CXCursor C);
/**
* \brief Given a cursor pointing to an Objective-C message, returns the CXType
* of the receiver.
*/
CINDEX_LINKAGE CXType clang_Cursor_getReceiverType(CXCursor C);
/**
* \brief Property attributes for a \c CXCursor_ObjCPropertyDecl.
*/
typedef enum {
CXObjCPropertyAttr_noattr = 0x00,
CXObjCPropertyAttr_readonly = 0x01,
CXObjCPropertyAttr_getter = 0x02,
CXObjCPropertyAttr_assign = 0x04,
CXObjCPropertyAttr_readwrite = 0x08,
CXObjCPropertyAttr_retain = 0x10,
CXObjCPropertyAttr_copy = 0x20,
CXObjCPropertyAttr_nonatomic = 0x40,
CXObjCPropertyAttr_setter = 0x80,
CXObjCPropertyAttr_atomic = 0x100,
CXObjCPropertyAttr_weak = 0x200,
CXObjCPropertyAttr_strong = 0x400,
CXObjCPropertyAttr_unsafe_unretained = 0x800
} CXObjCPropertyAttrKind;
/**
* \brief Given a cursor that represents a property declaration, return the
* associated property attributes. The bits are formed from
* \c CXObjCPropertyAttrKind.
*
* \param reserved Reserved for future use, pass 0.
*/
CINDEX_LINKAGE unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C,
unsigned reserved);
/**
* \brief 'Qualifiers' written next to the return and parameter types in
* Objective-C method declarations.
*/
typedef enum {
CXObjCDeclQualifier_None = 0x0,
CXObjCDeclQualifier_In = 0x1,
CXObjCDeclQualifier_Inout = 0x2,
CXObjCDeclQualifier_Out = 0x4,
CXObjCDeclQualifier_Bycopy = 0x8,
CXObjCDeclQualifier_Byref = 0x10,
CXObjCDeclQualifier_Oneway = 0x20
} CXObjCDeclQualifierKind;
/**
* \brief Given a cursor that represents an Objective-C method or parameter
* declaration, return the associated Objective-C qualifiers for the return
* type or the parameter respectively. The bits are formed from
* CXObjCDeclQualifierKind.
*/
CINDEX_LINKAGE unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C);
/**
* \brief Given a cursor that represents an Objective-C method or property
* declaration, return non-zero if the declaration was affected by "@optional".
* Returns zero if the cursor is not such a declaration or it is "@required".
*/
CINDEX_LINKAGE unsigned clang_Cursor_isObjCOptional(CXCursor C);
/**
* \brief Returns non-zero if the given cursor is a variadic function or method.
*/
CINDEX_LINKAGE unsigned clang_Cursor_isVariadic(CXCursor C);
/**
* \brief Given a cursor that represents a declaration, return the associated
* comment's source range. The range may include multiple consecutive comments
* with whitespace in between.
*/
CINDEX_LINKAGE CXSourceRange clang_Cursor_getCommentRange(CXCursor C);
/**
* \brief Given a cursor that represents a declaration, return the associated
* comment text, including comment markers.
*/
CINDEX_LINKAGE CXString clang_Cursor_getRawCommentText(CXCursor C);
/**
* \brief Given a cursor that represents a documentable entity (e.g.,
* declaration), return the associated \\brief paragraph; otherwise return the
* first paragraph.
*/
CINDEX_LINKAGE CXString clang_Cursor_getBriefCommentText(CXCursor C);
/**
* @}
*/
/** \defgroup CINDEX_MANGLE Name Mangling API Functions
*
* @{
*/
/**
* \brief Retrieve the CXString representing the mangled name of the cursor.
*/
CINDEX_LINKAGE CXString clang_Cursor_getMangling(CXCursor);
/**
* @}
*/
/**
* \defgroup CINDEX_MODULE Module introspection
*
* The functions in this group provide access to information about modules.
*
* @{
*/
typedef void *CXModule;
/**
* \brief Given a CXCursor_ModuleImportDecl cursor, return the associated module.
*/
CINDEX_LINKAGE CXModule clang_Cursor_getModule(CXCursor C);
/**
* \brief Given a CXFile header file, return the module that contains it, if one
* exists.
*/
CINDEX_LINKAGE CXModule clang_getModuleForFile(CXTranslationUnit, CXFile);
/**
* \param Module a module object.
*
* \returns the module file where the provided module object came from.
*/
CINDEX_LINKAGE CXFile clang_Module_getASTFile(CXModule Module);
/**
* \param Module a module object.
*
* \returns the parent of a sub-module or NULL if the given module is top-level,
* e.g. for 'std.vector' it will return the 'std' module.
*/
CINDEX_LINKAGE CXModule clang_Module_getParent(CXModule Module);
/**
* \param Module a module object.
*
* \returns the name of the module, e.g. for the 'std.vector' sub-module it
* will return "vector".
*/
CINDEX_LINKAGE CXString clang_Module_getName(CXModule Module);
/**
* \param Module a module object.
*
* \returns the full name of the module, e.g. "std.vector".
*/
CINDEX_LINKAGE CXString clang_Module_getFullName(CXModule Module);
/**
* \param Module a module object.
*
* \returns non-zero if the module is a system one.
*/
CINDEX_LINKAGE int clang_Module_isSystem(CXModule Module);
/**
* \param Module a module object.
*
* \returns the number of top level headers associated with this module.
*/
CINDEX_LINKAGE unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit,
CXModule Module);
/**
* \param Module a module object.
*
* \param Index top level header index (zero-based).
*
* \returns the specified top level header associated with the module.
*/
CINDEX_LINKAGE
CXFile clang_Module_getTopLevelHeader(CXTranslationUnit,
CXModule Module, unsigned Index);
/**
* @}
*/
/**
* \defgroup CINDEX_CPP C++ AST introspection
*
* The routines in this group provide access information in the ASTs specific
* to C++ language features.
*
* @{
*/
/**
* \brief Determine if a C++ member function or member function template is
* pure virtual.
*/
CINDEX_LINKAGE unsigned clang_CXXMethod_isPureVirtual(CXCursor C);
/**
* \brief Determine if a C++ member function or member function template is
* declared 'static'.
*/
CINDEX_LINKAGE unsigned clang_CXXMethod_isStatic(CXCursor C);
/**
* \brief Determine if a C++ member function or member function template is
* explicitly declared 'virtual' or if it overrides a virtual method from
* one of the base classes.
*/
CINDEX_LINKAGE unsigned clang_CXXMethod_isVirtual(CXCursor C);
/**
* \brief Determine if a C++ member function or member function template is
* declared 'const'.
*/
CINDEX_LINKAGE unsigned clang_CXXMethod_isConst(CXCursor C);
/**
* \brief Given a cursor that represents a template, determine
* the cursor kind of the specializations would be generated by instantiating
* the template.
*
* This routine can be used to determine what flavor of function template,
* class template, or class template partial specialization is stored in the
* cursor. For example, it can describe whether a class template cursor is
* declared with "struct", "class" or "union".
*
* \param C The cursor to query. This cursor should represent a template
* declaration.
*
* \returns The cursor kind of the specializations that would be generated
* by instantiating the template \p C. If \p C is not a template, returns
* \c CXCursor_NoDeclFound.
*/
CINDEX_LINKAGE enum CXCursorKind clang_getTemplateCursorKind(CXCursor C);
/**
* \brief Given a cursor that may represent a specialization or instantiation
* of a template, retrieve the cursor that represents the template that it
* specializes or from which it was instantiated.
*
* This routine determines the template involved both for explicit
* specializations of templates and for implicit instantiations of the template,
* both of which are referred to as "specializations". For a class template
* specialization (e.g., \c std::vector<bool>), this routine will return
* either the primary template (\c std::vector) or, if the specialization was
* instantiated from a class template partial specialization, the class template
* partial specialization. For a class template partial specialization and a
* function template specialization (including instantiations), this
* this routine will return the specialized template.
*
* For members of a class template (e.g., member functions, member classes, or
* static data members), returns the specialized or instantiated member.
* Although not strictly "templates" in the C++ language, members of class
* templates have the same notions of specializations and instantiations that
* templates do, so this routine treats them similarly.
*
* \param C A cursor that may be a specialization of a template or a member
* of a template.
*
* \returns If the given cursor is a specialization or instantiation of a
* template or a member thereof, the template or member that it specializes or
* from which it was instantiated. Otherwise, returns a NULL cursor.
*/
CINDEX_LINKAGE CXCursor clang_getSpecializedCursorTemplate(CXCursor C);
/**
* \brief Given a cursor that references something else, return the source range
* covering that reference.
*
* \param C A cursor pointing to a member reference, a declaration reference, or
* an operator call.
* \param NameFlags A bitset with three independent flags:
* CXNameRange_WantQualifier, CXNameRange_WantTemplateArgs, and
* CXNameRange_WantSinglePiece.
* \param PieceIndex For contiguous names or when passing the flag
* CXNameRange_WantSinglePiece, only one piece with index 0 is
* available. When the CXNameRange_WantSinglePiece flag is not passed for a
* non-contiguous names, this index can be used to retrieve the individual
* pieces of the name. See also CXNameRange_WantSinglePiece.
*
* \returns The piece of the name pointed to by the given cursor. If there is no
* name, or if the PieceIndex is out-of-range, a null-cursor will be returned.
*/
CINDEX_LINKAGE CXSourceRange clang_getCursorReferenceNameRange(CXCursor C,
unsigned NameFlags,
unsigned PieceIndex);
enum CXNameRefFlags {
/**
* \brief Include the nested-name-specifier, e.g. Foo:: in x.Foo::y, in the
* range.
*/
CXNameRange_WantQualifier = 0x1,
/**
* \brief Include the explicit template arguments, e.g. \<int> in x.f<int>,
* in the range.
*/
CXNameRange_WantTemplateArgs = 0x2,
/**
* \brief If the name is non-contiguous, return the full spanning range.
*
* Non-contiguous names occur in Objective-C when a selector with two or more
* parameters is used, or in C++ when using an operator:
* \code
* [object doSomething:here withValue:there]; // Objective-C
* return some_vector[1]; // C++
* \endcode
*/
CXNameRange_WantSinglePiece = 0x4
};
/**
* @}
*/
/**
* \defgroup CINDEX_LEX Token extraction and manipulation
*
* The routines in this group provide access to the tokens within a
* translation unit, along with a semantic mapping of those tokens to
* their corresponding cursors.
*
* @{
*/
/**
* \brief Describes a kind of token.
*/
typedef enum CXTokenKind {
/**
* \brief A token that contains some kind of punctuation.
*/
CXToken_Punctuation,
/**
* \brief A language keyword.
*/
CXToken_Keyword,
/**
* \brief An identifier (that is not a keyword).
*/
CXToken_Identifier,
/**
* \brief A numeric, string, or character literal.
*/
CXToken_Literal,
/**
* \brief A comment.
*/
CXToken_Comment
, CXToken_BuiltInType // HLSL Change
} CXTokenKind;
/**
* \brief Describes a single preprocessing token.
*/
typedef struct {
unsigned int_data[4];
void *ptr_data;
} CXToken;
/**
* \brief Determine the kind of the given token.
*/
CINDEX_LINKAGE CXTokenKind clang_getTokenKind(CXToken);
/**
* \brief Determine the spelling of the given token.
*
* The spelling of a token is the textual representation of that token, e.g.,
* the text of an identifier or keyword.
*/
CINDEX_LINKAGE CXString clang_getTokenSpelling(CXTranslationUnit, CXToken);
/**
* \brief Retrieve the source location of the given token.
*/
CINDEX_LINKAGE CXSourceLocation clang_getTokenLocation(CXTranslationUnit,
CXToken);
/**
* \brief Retrieve a source range that covers the given token.
*/
CINDEX_LINKAGE CXSourceRange clang_getTokenExtent(CXTranslationUnit, CXToken);
/**
* \brief Tokenize the source code described by the given range into raw
* lexical tokens.
*
* \param TU the translation unit whose text is being tokenized.
*
* \param Range the source range in which text should be tokenized. All of the
* tokens produced by tokenization will fall within this source range,
*
* \param Tokens this pointer will be set to point to the array of tokens
* that occur within the given source range. The returned pointer must be
* freed with clang_disposeTokens() before the translation unit is destroyed.
*
* \param NumTokens will be set to the number of tokens in the \c *Tokens
* array.
*
*/
CINDEX_LINKAGE void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
CXToken **Tokens, unsigned *NumTokens);
/**
* \brief Annotate the given set of tokens by providing cursors for each token
* that can be mapped to a specific entity within the abstract syntax tree.
*
* This token-annotation routine is equivalent to invoking
* clang_getCursor() for the source locations of each of the
* tokens. The cursors provided are filtered, so that only those
* cursors that have a direct correspondence to the token are
* accepted. For example, given a function call \c f(x),
* clang_getCursor() would provide the following cursors:
*
* * when the cursor is over the 'f', a DeclRefExpr cursor referring to 'f'.
* * when the cursor is over the '(' or the ')', a CallExpr referring to 'f'.
* * when the cursor is over the 'x', a DeclRefExpr cursor referring to 'x'.
*
* Only the first and last of these cursors will occur within the
* annotate, since the tokens "f" and "x' directly refer to a function
* and a variable, respectively, but the parentheses are just a small
* part of the full syntax of the function call expression, which is
* not provided as an annotation.
*
* \param TU the translation unit that owns the given tokens.
*
* \param Tokens the set of tokens to annotate.
*
* \param NumTokens the number of tokens in \p Tokens.
*
* \param Cursors an array of \p NumTokens cursors, whose contents will be
* replaced with the cursors corresponding to each token.
*/
CINDEX_LINKAGE void clang_annotateTokens(CXTranslationUnit TU,
CXToken *Tokens, unsigned NumTokens,
CXCursor *Cursors);
/**
* \brief Free the given set of tokens.
*/
CINDEX_LINKAGE void clang_disposeTokens(CXTranslationUnit TU,
CXToken *Tokens, unsigned NumTokens);
/**
* @}
*/
/**
* \defgroup CINDEX_DEBUG Debugging facilities
*
* These routines are used for testing and debugging, only, and should not
* be relied upon.
*
* @{
*/
/* for debug/testing */
CINDEX_LINKAGE CXString clang_getCursorKindSpelling(enum CXCursorKind Kind);
CINDEX_LINKAGE void clang_getDefinitionSpellingAndExtent(CXCursor,
const char **startBuf,
const char **endBuf,
unsigned *startLine,
unsigned *startColumn,
unsigned *endLine,
unsigned *endColumn);
CINDEX_LINKAGE void clang_enableStackTraces(void);
CINDEX_LINKAGE void clang_executeOnThread(void (*fn)(void*), void *user_data,
unsigned stack_size);
/**
* @}
*/
/**
* \defgroup CINDEX_CODE_COMPLET Code completion
*
* Code completion involves taking an (incomplete) source file, along with
* knowledge of where the user is actively editing that file, and suggesting
* syntactically- and semantically-valid constructs that the user might want to
* use at that particular point in the source code. These data structures and
* routines provide support for code completion.
*
* @{
*/
/**
* \brief A semantic string that describes a code-completion result.
*
* A semantic string that describes the formatting of a code-completion
* result as a single "template" of text that should be inserted into the
* source buffer when a particular code-completion result is selected.
* Each semantic string is made up of some number of "chunks", each of which
* contains some text along with a description of what that text means, e.g.,
* the name of the entity being referenced, whether the text chunk is part of
* the template, or whether it is a "placeholder" that the user should replace
* with actual code,of a specific kind. See \c CXCompletionChunkKind for a
* description of the different kinds of chunks.
*/
typedef void *CXCompletionString;
/**
* \brief A single result of code completion.
*/
typedef struct {
/**
* \brief The kind of entity that this completion refers to.
*
* The cursor kind will be a macro, keyword, or a declaration (one of the
* *Decl cursor kinds), describing the entity that the completion is
* referring to.
*
* \todo In the future, we would like to provide a full cursor, to allow
* the client to extract additional information from declaration.
*/
enum CXCursorKind CursorKind;
/**
* \brief The code-completion string that describes how to insert this
* code-completion result into the editing buffer.
*/
CXCompletionString CompletionString;
} CXCompletionResult;
/**
* \brief Describes a single piece of text within a code-completion string.
*
* Each "chunk" within a code-completion string (\c CXCompletionString) is
* either a piece of text with a specific "kind" that describes how that text
* should be interpreted by the client or is another completion string.
*/
enum CXCompletionChunkKind {
/**
* \brief A code-completion string that describes "optional" text that
* could be a part of the template (but is not required).
*
* The Optional chunk is the only kind of chunk that has a code-completion
* string for its representation, which is accessible via
* \c clang_getCompletionChunkCompletionString(). The code-completion string
* describes an additional part of the template that is completely optional.
* For example, optional chunks can be used to describe the placeholders for
* arguments that match up with defaulted function parameters, e.g. given:
*
* \code
* void f(int x, float y = 3.14, double z = 2.71828);
* \endcode
*
* The code-completion string for this function would contain:
* - a TypedText chunk for "f".
* - a LeftParen chunk for "(".
* - a Placeholder chunk for "int x"
* - an Optional chunk containing the remaining defaulted arguments, e.g.,
* - a Comma chunk for ","
* - a Placeholder chunk for "float y"
* - an Optional chunk containing the last defaulted argument:
* - a Comma chunk for ","
* - a Placeholder chunk for "double z"
* - a RightParen chunk for ")"
*
* There are many ways to handle Optional chunks. Two simple approaches are:
* - Completely ignore optional chunks, in which case the template for the
* function "f" would only include the first parameter ("int x").
* - Fully expand all optional chunks, in which case the template for the
* function "f" would have all of the parameters.
*/
CXCompletionChunk_Optional,
/**
* \brief Text that a user would be expected to type to get this
* code-completion result.
*
* There will be exactly one "typed text" chunk in a semantic string, which
* will typically provide the spelling of a keyword or the name of a
* declaration that could be used at the current code point. Clients are
* expected to filter the code-completion results based on the text in this
* chunk.
*/
CXCompletionChunk_TypedText,
/**
* \brief Text that should be inserted as part of a code-completion result.
*
* A "text" chunk represents text that is part of the template to be
* inserted into user code should this particular code-completion result
* be selected.
*/
CXCompletionChunk_Text,
/**
* \brief Placeholder text that should be replaced by the user.
*
* A "placeholder" chunk marks a place where the user should insert text
* into the code-completion template. For example, placeholders might mark
* the function parameters for a function declaration, to indicate that the
* user should provide arguments for each of those parameters. The actual
* text in a placeholder is a suggestion for the text to display before
* the user replaces the placeholder with real code.
*/
CXCompletionChunk_Placeholder,
/**
* \brief Informative text that should be displayed but never inserted as
* part of the template.
*
* An "informative" chunk contains annotations that can be displayed to
* help the user decide whether a particular code-completion result is the
* right option, but which is not part of the actual template to be inserted
* by code completion.
*/
CXCompletionChunk_Informative,
/**
* \brief Text that describes the current parameter when code-completion is
* referring to function call, message send, or template specialization.
*
* A "current parameter" chunk occurs when code-completion is providing
* information about a parameter corresponding to the argument at the
* code-completion point. For example, given a function
*
* \code
* int add(int x, int y);
* \endcode
*
* and the source code \c add(, where the code-completion point is after the
* "(", the code-completion string will contain a "current parameter" chunk
* for "int x", indicating that the current argument will initialize that
* parameter. After typing further, to \c add(17, (where the code-completion
* point is after the ","), the code-completion string will contain a
* "current paremeter" chunk to "int y".
*/
CXCompletionChunk_CurrentParameter,
/**
* \brief A left parenthesis ('('), used to initiate a function call or
* signal the beginning of a function parameter list.
*/
CXCompletionChunk_LeftParen,
/**
* \brief A right parenthesis (')'), used to finish a function call or
* signal the end of a function parameter list.
*/
CXCompletionChunk_RightParen,
/**
* \brief A left bracket ('[').
*/
CXCompletionChunk_LeftBracket,
/**
* \brief A right bracket (']').
*/
CXCompletionChunk_RightBracket,
/**
* \brief A left brace ('{').
*/
CXCompletionChunk_LeftBrace,
/**
* \brief A right brace ('}').
*/
CXCompletionChunk_RightBrace,
/**
* \brief A left angle bracket ('<').
*/
CXCompletionChunk_LeftAngle,
/**
* \brief A right angle bracket ('>').
*/
CXCompletionChunk_RightAngle,
/**
* \brief A comma separator (',').
*/
CXCompletionChunk_Comma,
/**
* \brief Text that specifies the result type of a given result.
*
* This special kind of informative chunk is not meant to be inserted into
* the text buffer. Rather, it is meant to illustrate the type that an
* expression using the given completion string would have.
*/
CXCompletionChunk_ResultType,
/**
* \brief A colon (':').
*/
CXCompletionChunk_Colon,
/**
* \brief A semicolon (';').
*/
CXCompletionChunk_SemiColon,
/**
* \brief An '=' sign.
*/
CXCompletionChunk_Equal,
/**
* Horizontal space (' ').
*/
CXCompletionChunk_HorizontalSpace,
/**
* Vertical space ('\n'), after which it is generally a good idea to
* perform indentation.
*/
CXCompletionChunk_VerticalSpace
};
/**
* \brief Determine the kind of a particular chunk within a completion string.
*
* \param completion_string the completion string to query.
*
* \param chunk_number the 0-based index of the chunk in the completion string.
*
* \returns the kind of the chunk at the index \c chunk_number.
*/
CINDEX_LINKAGE enum CXCompletionChunkKind
clang_getCompletionChunkKind(CXCompletionString completion_string,
unsigned chunk_number);
/**
* \brief Retrieve the text associated with a particular chunk within a
* completion string.
*
* \param completion_string the completion string to query.
*
* \param chunk_number the 0-based index of the chunk in the completion string.
*
* \returns the text associated with the chunk at index \c chunk_number.
*/
CINDEX_LINKAGE CXString
clang_getCompletionChunkText(CXCompletionString completion_string,
unsigned chunk_number);
/**
* \brief Retrieve the completion string associated with a particular chunk
* within a completion string.
*
* \param completion_string the completion string to query.
*
* \param chunk_number the 0-based index of the chunk in the completion string.
*
* \returns the completion string associated with the chunk at index
* \c chunk_number.
*/
CINDEX_LINKAGE CXCompletionString
clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
unsigned chunk_number);
/**
* \brief Retrieve the number of chunks in the given code-completion string.
*/
CINDEX_LINKAGE unsigned
clang_getNumCompletionChunks(CXCompletionString completion_string);
/**
* \brief Determine the priority of this code completion.
*
* The priority of a code completion indicates how likely it is that this
* particular completion is the completion that the user will select. The
* priority is selected by various internal heuristics.
*
* \param completion_string The completion string to query.
*
* \returns The priority of this completion string. Smaller values indicate
* higher-priority (more likely) completions.
*/
CINDEX_LINKAGE unsigned
clang_getCompletionPriority(CXCompletionString completion_string);
/**
* \brief Determine the availability of the entity that this code-completion
* string refers to.
*
* \param completion_string The completion string to query.
*
* \returns The availability of the completion string.
*/
CINDEX_LINKAGE enum CXAvailabilityKind
clang_getCompletionAvailability(CXCompletionString completion_string);
/**
* \brief Retrieve the number of annotations associated with the given
* completion string.
*
* \param completion_string the completion string to query.
*
* \returns the number of annotations associated with the given completion
* string.
*/
CINDEX_LINKAGE unsigned
clang_getCompletionNumAnnotations(CXCompletionString completion_string);
/**
* \brief Retrieve the annotation associated with the given completion string.
*
* \param completion_string the completion string to query.
*
* \param annotation_number the 0-based index of the annotation of the
* completion string.
*
* \returns annotation string associated with the completion at index
* \c annotation_number, or a NULL string if that annotation is not available.
*/
CINDEX_LINKAGE CXString
clang_getCompletionAnnotation(CXCompletionString completion_string,
unsigned annotation_number);
/**
* \brief Retrieve the parent context of the given completion string.
*
* The parent context of a completion string is the semantic parent of
* the declaration (if any) that the code completion represents. For example,
* a code completion for an Objective-C method would have the method's class
* or protocol as its context.
*
* \param completion_string The code completion string whose parent is
* being queried.
*
* \param kind DEPRECATED: always set to CXCursor_NotImplemented if non-NULL.
*
* \returns The name of the completion parent, e.g., "NSObject" if
* the completion string represents a method in the NSObject class.
*/
CINDEX_LINKAGE CXString
clang_getCompletionParent(CXCompletionString completion_string,
enum CXCursorKind *kind);
/**
* \brief Retrieve the brief documentation comment attached to the declaration
* that corresponds to the given completion string.
*/
CINDEX_LINKAGE CXString
clang_getCompletionBriefComment(CXCompletionString completion_string);
/**
* \brief Retrieve a completion string for an arbitrary declaration or macro
* definition cursor.
*
* \param cursor The cursor to query.
*
* \returns A non-context-sensitive completion string for declaration and macro
* definition cursors, or NULL for other kinds of cursors.
*/
CINDEX_LINKAGE CXCompletionString
clang_getCursorCompletionString(CXCursor cursor);
/**
* \brief Contains the results of code-completion.
*
* This data structure contains the results of code completion, as
* produced by \c clang_codeCompleteAt(). Its contents must be freed by
* \c clang_disposeCodeCompleteResults.
*/
typedef struct {
/**
* \brief The code-completion results.
*/
CXCompletionResult *Results;
/**
* \brief The number of code-completion results stored in the
* \c Results array.
*/
unsigned NumResults;
} CXCodeCompleteResults;
/**
* \brief Flags that can be passed to \c clang_codeCompleteAt() to
* modify its behavior.
*
* The enumerators in this enumeration can be bitwise-OR'd together to
* provide multiple options to \c clang_codeCompleteAt().
*/
enum CXCodeComplete_Flags {
/**
* \brief Whether to include macros within the set of code
* completions returned.
*/
CXCodeComplete_IncludeMacros = 0x01,
/**
* \brief Whether to include code patterns for language constructs
* within the set of code completions, e.g., for loops.
*/
CXCodeComplete_IncludeCodePatterns = 0x02,
/**
* \brief Whether to include brief documentation within the set of code
* completions returned.
*/
CXCodeComplete_IncludeBriefComments = 0x04
};
/**
* \brief Bits that represent the context under which completion is occurring.
*
* The enumerators in this enumeration may be bitwise-OR'd together if multiple
* contexts are occurring simultaneously.
*/
enum CXCompletionContext {
/**
* \brief The context for completions is unexposed, as only Clang results
* should be included. (This is equivalent to having no context bits set.)
*/
CXCompletionContext_Unexposed = 0,
/**
* \brief Completions for any possible type should be included in the results.
*/
CXCompletionContext_AnyType = 1 << 0,
/**
* \brief Completions for any possible value (variables, function calls, etc.)
* should be included in the results.
*/
CXCompletionContext_AnyValue = 1 << 1,
/**
* \brief Completions for values that resolve to an Objective-C object should
* be included in the results.
*/
CXCompletionContext_ObjCObjectValue = 1 << 2,
/**
* \brief Completions for values that resolve to an Objective-C selector
* should be included in the results.
*/
CXCompletionContext_ObjCSelectorValue = 1 << 3,
/**
* \brief Completions for values that resolve to a C++ class type should be
* included in the results.
*/
CXCompletionContext_CXXClassTypeValue = 1 << 4,
/**
* \brief Completions for fields of the member being accessed using the dot
* operator should be included in the results.
*/
CXCompletionContext_DotMemberAccess = 1 << 5,
/**
* \brief Completions for fields of the member being accessed using the arrow
* operator should be included in the results.
*/
CXCompletionContext_ArrowMemberAccess = 1 << 6,
/**
* \brief Completions for properties of the Objective-C object being accessed
* using the dot operator should be included in the results.
*/
CXCompletionContext_ObjCPropertyAccess = 1 << 7,
/**
* \brief Completions for enum tags should be included in the results.
*/
CXCompletionContext_EnumTag = 1 << 8,
/**
* \brief Completions for union tags should be included in the results.
*/
CXCompletionContext_UnionTag = 1 << 9,
/**
* \brief Completions for struct tags should be included in the results.
*/
CXCompletionContext_StructTag = 1 << 10,
/**
* \brief Completions for C++ class names should be included in the results.
*/
CXCompletionContext_ClassTag = 1 << 11,
/**
* \brief Completions for C++ namespaces and namespace aliases should be
* included in the results.
*/
CXCompletionContext_Namespace = 1 << 12,
/**
* \brief Completions for C++ nested name specifiers should be included in
* the results.
*/
CXCompletionContext_NestedNameSpecifier = 1 << 13,
/**
* \brief Completions for Objective-C interfaces (classes) should be included
* in the results.
*/
CXCompletionContext_ObjCInterface = 1 << 14,
/**
* \brief Completions for Objective-C protocols should be included in
* the results.
*/
CXCompletionContext_ObjCProtocol = 1 << 15,
/**
* \brief Completions for Objective-C categories should be included in
* the results.
*/
CXCompletionContext_ObjCCategory = 1 << 16,
/**
* \brief Completions for Objective-C instance messages should be included
* in the results.
*/
CXCompletionContext_ObjCInstanceMessage = 1 << 17,
/**
* \brief Completions for Objective-C class messages should be included in
* the results.
*/
CXCompletionContext_ObjCClassMessage = 1 << 18,
/**
* \brief Completions for Objective-C selector names should be included in
* the results.
*/
CXCompletionContext_ObjCSelectorName = 1 << 19,
/**
* \brief Completions for preprocessor macro names should be included in
* the results.
*/
CXCompletionContext_MacroName = 1 << 20,
/**
* \brief Natural language completions should be included in the results.
*/
CXCompletionContext_NaturalLanguage = 1 << 21,
/**
* \brief The current context is unknown, so set all contexts.
*/
CXCompletionContext_Unknown = ((1 << 22) - 1)
};
/**
* \brief Returns a default set of code-completion options that can be
* passed to\c clang_codeCompleteAt().
*/
CINDEX_LINKAGE unsigned clang_defaultCodeCompleteOptions(void);
/**
* \brief Perform code completion at a given location in a translation unit.
*
* This function performs code completion at a particular file, line, and
* column within source code, providing results that suggest potential
* code snippets based on the context of the completion. The basic model
* for code completion is that Clang will parse a complete source file,
* performing syntax checking up to the location where code-completion has
* been requested. At that point, a special code-completion token is passed
* to the parser, which recognizes this token and determines, based on the
* current location in the C/Objective-C/C++ grammar and the state of
* semantic analysis, what completions to provide. These completions are
* returned via a new \c CXCodeCompleteResults structure.
*
* Code completion itself is meant to be triggered by the client when the
* user types punctuation characters or whitespace, at which point the
* code-completion location will coincide with the cursor. For example, if \c p
* is a pointer, code-completion might be triggered after the "-" and then
* after the ">" in \c p->. When the code-completion location is afer the ">",
* the completion results will provide, e.g., the members of the struct that
* "p" points to. The client is responsible for placing the cursor at the
* beginning of the token currently being typed, then filtering the results
* based on the contents of the token. For example, when code-completing for
* the expression \c p->get, the client should provide the location just after
* the ">" (e.g., pointing at the "g") to this code-completion hook. Then, the
* client can filter the results based on the current token text ("get"), only
* showing those results that start with "get". The intent of this interface
* is to separate the relatively high-latency acquisition of code-completion
* results from the filtering of results on a per-character basis, which must
* have a lower latency.
*
* \param TU The translation unit in which code-completion should
* occur. The source files for this translation unit need not be
* completely up-to-date (and the contents of those source files may
* be overridden via \p unsaved_files). Cursors referring into the
* translation unit may be invalidated by this invocation.
*
* \param complete_filename The name of the source file where code
* completion should be performed. This filename may be any file
* included in the translation unit.
*
* \param complete_line The line at which code-completion should occur.
*
* \param complete_column The column at which code-completion should occur.
* Note that the column should point just after the syntactic construct that
* initiated code completion, and not in the middle of a lexical token.
*
* \param unsaved_files the Tiles that have not yet been saved to disk
* but may be required for parsing or code completion, including the
* contents of those files. The contents and name of these files (as
* specified by CXUnsavedFile) are copied when necessary, so the
* client only needs to guarantee their validity until the call to
* this function returns.
*
* \param num_unsaved_files The number of unsaved file entries in \p
* unsaved_files.
*
* \param options Extra options that control the behavior of code
* completion, expressed as a bitwise OR of the enumerators of the
* CXCodeComplete_Flags enumeration. The
* \c clang_defaultCodeCompleteOptions() function returns a default set
* of code-completion options.
*
* \returns If successful, a new \c CXCodeCompleteResults structure
* containing code-completion results, which should eventually be
* freed with \c clang_disposeCodeCompleteResults(). If code
* completion fails, returns NULL.
*/
CINDEX_LINKAGE
CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
const char *complete_filename,
unsigned complete_line,
unsigned complete_column,
struct CXUnsavedFile *unsaved_files,
unsigned num_unsaved_files,
unsigned options);
/**
* \brief Sort the code-completion results in case-insensitive alphabetical
* order.
*
* \param Results The set of results to sort.
* \param NumResults The number of results in \p Results.
*/
CINDEX_LINKAGE
void clang_sortCodeCompletionResults(CXCompletionResult *Results,
unsigned NumResults);
/**
* \brief Free the given set of code-completion results.
*/
CINDEX_LINKAGE
void clang_disposeCodeCompleteResults(CXCodeCompleteResults *Results);
/**
* \brief Determine the number of diagnostics produced prior to the
* location where code completion was performed.
*/
CINDEX_LINKAGE
unsigned clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *Results);
/**
* \brief Retrieve a diagnostic associated with the given code completion.
*
* \param Results the code completion results to query.
* \param Index the zero-based diagnostic number to retrieve.
*
* \returns the requested diagnostic. This diagnostic must be freed
* via a call to \c clang_disposeDiagnostic().
*/
CINDEX_LINKAGE
CXDiagnostic clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *Results,
unsigned Index);
/**
* \brief Determines what completions are appropriate for the context
* the given code completion.
*
* \param Results the code completion results to query
*
* \returns the kinds of completions that are appropriate for use
* along with the given code completion results.
*/
CINDEX_LINKAGE
unsigned long long clang_codeCompleteGetContexts(
CXCodeCompleteResults *Results);
/**
* \brief Returns the cursor kind for the container for the current code
* completion context. The container is only guaranteed to be set for
* contexts where a container exists (i.e. member accesses or Objective-C
* message sends); if there is not a container, this function will return
* CXCursor_InvalidCode.
*
* \param Results the code completion results to query
*
* \param IsIncomplete on return, this value will be false if Clang has complete
* information about the container. If Clang does not have complete
* information, this value will be true.
*
* \returns the container kind, or CXCursor_InvalidCode if there is not a
* container
*/
CINDEX_LINKAGE
enum CXCursorKind clang_codeCompleteGetContainerKind(
CXCodeCompleteResults *Results,
unsigned *IsIncomplete);
/**
* \brief Returns the USR for the container for the current code completion
* context. If there is not a container for the current context, this
* function will return the empty string.
*
* \param Results the code completion results to query
*
* \returns the USR for the container
*/
CINDEX_LINKAGE
CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *Results);
/**
* \brief Returns the currently-entered selector for an Objective-C message
* send, formatted like "initWithFoo:bar:". Only guaranteed to return a
* non-empty string for CXCompletionContext_ObjCInstanceMessage and
* CXCompletionContext_ObjCClassMessage.
*
* \param Results the code completion results to query
*
* \returns the selector (or partial selector) that has been entered thus far
* for an Objective-C message send.
*/
CINDEX_LINKAGE
CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *Results);
/**
* @}
*/
/**
* \defgroup CINDEX_MISC Miscellaneous utility functions
*
* @{
*/
/**
* \brief Return a version string, suitable for showing to a user, but not
* intended to be parsed (the format is not guaranteed to be stable).
*/
CINDEX_LINKAGE CXString clang_getClangVersion(void);
/**
* \brief Enable/disable crash recovery.
*
* \param isEnabled Flag to indicate if crash recovery is enabled. A non-zero
* value enables crash recovery, while 0 disables it.
*/
CINDEX_LINKAGE void clang_toggleCrashRecovery(unsigned isEnabled);
/**
* \brief Visitor invoked for each file in a translation unit
* (used with clang_getInclusions()).
*
* This visitor function will be invoked by clang_getInclusions() for each
* file included (either at the top-level or by \#include directives) within
* a translation unit. The first argument is the file being included, and
* the second and third arguments provide the inclusion stack. The
* array is sorted in order of immediate inclusion. For example,
* the first element refers to the location that included 'included_file'.
*/
typedef void (*CXInclusionVisitor)(CXFile included_file,
CXSourceLocation* inclusion_stack,
unsigned include_len,
CXClientData client_data);
/**
* \brief Visit the set of preprocessor inclusions in a translation unit.
* The visitor function is called with the provided data for every included
* file. This does not include headers included by the PCH file (unless one
* is inspecting the inclusions in the PCH file itself).
*/
CINDEX_LINKAGE void clang_getInclusions(CXTranslationUnit tu,
CXInclusionVisitor visitor,
CXClientData client_data);
/**
* @}
*/
/** \defgroup CINDEX_REMAPPING Remapping functions
*
* @{
*/
/**
* \brief A remapping of original source files and their translated files.
*/
typedef void *CXRemapping;
/**
* \brief Retrieve a remapping.
*
* \param path the path that contains metadata about remappings.
*
* \returns the requested remapping. This remapping must be freed
* via a call to \c clang_remap_dispose(). Can return NULL if an error occurred.
*/
CINDEX_LINKAGE CXRemapping clang_getRemappings(const char *path);
/**
* \brief Retrieve a remapping.
*
* \param filePaths pointer to an array of file paths containing remapping info.
*
* \param numFiles number of file paths.
*
* \returns the requested remapping. This remapping must be freed
* via a call to \c clang_remap_dispose(). Can return NULL if an error occurred.
*/
CINDEX_LINKAGE
CXRemapping clang_getRemappingsFromFileList(const char **filePaths,
unsigned numFiles);
/**
* \brief Determine the number of remappings.
*/
CINDEX_LINKAGE unsigned clang_remap_getNumFiles(CXRemapping);
/**
* \brief Get the original and the associated filename from the remapping.
*
* \param original If non-NULL, will be set to the original filename.
*
* \param transformed If non-NULL, will be set to the filename that the original
* is associated with.
*/
CINDEX_LINKAGE void clang_remap_getFilenames(CXRemapping, unsigned index,
CXString *original, CXString *transformed);
/**
* \brief Dispose the remapping.
*/
CINDEX_LINKAGE void clang_remap_dispose(CXRemapping);
/**
* @}
*/
/** \defgroup CINDEX_HIGH Higher level API functions
*
* @{
*/
enum CXVisitorResult {
CXVisit_Break,
CXVisit_Continue
};
typedef struct {
void *context;
enum CXVisitorResult (*visit)(void *context, CXCursor, CXSourceRange);
} CXCursorAndRangeVisitor;
typedef enum {
/**
* \brief Function returned successfully.
*/
CXResult_Success = 0,
/**
* \brief One of the parameters was invalid for the function.
*/
CXResult_Invalid = 1,
/**
* \brief The function was terminated by a callback (e.g. it returned
* CXVisit_Break)
*/
CXResult_VisitBreak = 2
} CXResult;
/**
* \brief Find references of a declaration in a specific file.
*
* \param cursor pointing to a declaration or a reference of one.
*
* \param file to search for references.
*
* \param visitor callback that will receive pairs of CXCursor/CXSourceRange for
* each reference found.
* The CXSourceRange will point inside the file; if the reference is inside
* a macro (and not a macro argument) the CXSourceRange will be invalid.
*
* \returns one of the CXResult enumerators.
*/
CINDEX_LINKAGE CXResult clang_findReferencesInFile(CXCursor cursor, CXFile file,
CXCursorAndRangeVisitor visitor);
/**
* \brief Find #import/#include directives in a specific file.
*
* \param TU translation unit containing the file to query.
*
* \param file to search for #import/#include directives.
*
* \param visitor callback that will receive pairs of CXCursor/CXSourceRange for
* each directive found.
*
* \returns one of the CXResult enumerators.
*/
CINDEX_LINKAGE CXResult clang_findIncludesInFile(CXTranslationUnit TU,
CXFile file,
CXCursorAndRangeVisitor visitor);
#ifdef __has_feature
# if __has_feature(blocks)
typedef enum CXVisitorResult
(^CXCursorAndRangeVisitorBlock)(CXCursor, CXSourceRange);
CINDEX_LINKAGE
CXResult clang_findReferencesInFileWithBlock(CXCursor, CXFile,
CXCursorAndRangeVisitorBlock);
CINDEX_LINKAGE
CXResult clang_findIncludesInFileWithBlock(CXTranslationUnit, CXFile,
CXCursorAndRangeVisitorBlock);
# endif
#endif
/**
* \brief The client's data object that is associated with a CXFile.
*/
typedef void *CXIdxClientFile;
/**
* \brief The client's data object that is associated with a semantic entity.
*/
typedef void *CXIdxClientEntity;
/**
* \brief The client's data object that is associated with a semantic container
* of entities.
*/
typedef void *CXIdxClientContainer;
/**
* \brief The client's data object that is associated with an AST file (PCH
* or module).
*/
typedef void *CXIdxClientASTFile;
/**
* \brief Source location passed to index callbacks.
*/
typedef struct {
void *ptr_data[2];
unsigned int_data;
} CXIdxLoc;
/**
* \brief Data for ppIncludedFile callback.
*/
typedef struct {
/**
* \brief Location of '#' in the \#include/\#import directive.
*/
CXIdxLoc hashLoc;
/**
* \brief Filename as written in the \#include/\#import directive.
*/
const char *filename;
/**
* \brief The actual file that the \#include/\#import directive resolved to.
*/
CXFile file;
int isImport;
int isAngled;
/**
* \brief Non-zero if the directive was automatically turned into a module
* import.
*/
int isModuleImport;
} CXIdxIncludedFileInfo;
/**
* \brief Data for IndexerCallbacks#importedASTFile.
*/
typedef struct {
/**
* \brief Top level AST file containing the imported PCH, module or submodule.
*/
CXFile file;
/**
* \brief The imported module or NULL if the AST file is a PCH.
*/
CXModule mod;
/**
* \brief Location where the file is imported. Applicable only for modules.
*/
CXIdxLoc loc;
/**
* \brief Non-zero if an inclusion directive was automatically turned into
* a module import. Applicable only for modules.
*/
int isImplicit;
} CXIdxImportedASTFileInfo;
typedef enum {
CXIdxEntity_Unexposed = 0,
CXIdxEntity_Typedef = 1,
CXIdxEntity_Function = 2,
CXIdxEntity_Variable = 3,
CXIdxEntity_Field = 4,
CXIdxEntity_EnumConstant = 5,
CXIdxEntity_ObjCClass = 6,
CXIdxEntity_ObjCProtocol = 7,
CXIdxEntity_ObjCCategory = 8,
CXIdxEntity_ObjCInstanceMethod = 9,
CXIdxEntity_ObjCClassMethod = 10,
CXIdxEntity_ObjCProperty = 11,
CXIdxEntity_ObjCIvar = 12,
CXIdxEntity_Enum = 13,
CXIdxEntity_Struct = 14,
CXIdxEntity_Union = 15,
CXIdxEntity_CXXClass = 16,
CXIdxEntity_CXXNamespace = 17,
CXIdxEntity_CXXNamespaceAlias = 18,
CXIdxEntity_CXXStaticVariable = 19,
CXIdxEntity_CXXStaticMethod = 20,
CXIdxEntity_CXXInstanceMethod = 21,
CXIdxEntity_CXXConstructor = 22,
CXIdxEntity_CXXDestructor = 23,
CXIdxEntity_CXXConversionFunction = 24,
CXIdxEntity_CXXTypeAlias = 25,
CXIdxEntity_CXXInterface = 26
} CXIdxEntityKind;
typedef enum {
CXIdxEntityLang_None = 0,
CXIdxEntityLang_C = 1,
CXIdxEntityLang_ObjC = 2,
CXIdxEntityLang_CXX = 3
} CXIdxEntityLanguage;
/**
* \brief Extra C++ template information for an entity. This can apply to:
* CXIdxEntity_Function
* CXIdxEntity_CXXClass
* CXIdxEntity_CXXStaticMethod
* CXIdxEntity_CXXInstanceMethod
* CXIdxEntity_CXXConstructor
* CXIdxEntity_CXXConversionFunction
* CXIdxEntity_CXXTypeAlias
*/
typedef enum {
CXIdxEntity_NonTemplate = 0,
CXIdxEntity_Template = 1,
CXIdxEntity_TemplatePartialSpecialization = 2,
CXIdxEntity_TemplateSpecialization = 3
} CXIdxEntityCXXTemplateKind;
typedef enum {
CXIdxAttr_Unexposed = 0,
CXIdxAttr_IBAction = 1,
CXIdxAttr_IBOutlet = 2,
CXIdxAttr_IBOutletCollection = 3
} CXIdxAttrKind;
typedef struct {
CXIdxAttrKind kind;
CXCursor cursor;
CXIdxLoc loc;
} CXIdxAttrInfo;
typedef struct {
CXIdxEntityKind kind;
CXIdxEntityCXXTemplateKind templateKind;
CXIdxEntityLanguage lang;
const char *name;
const char *USR;
CXCursor cursor;
const CXIdxAttrInfo *const *attributes;
unsigned numAttributes;
} CXIdxEntityInfo;
typedef struct {
CXCursor cursor;
} CXIdxContainerInfo;
typedef struct {
const CXIdxAttrInfo *attrInfo;
const CXIdxEntityInfo *objcClass;
CXCursor classCursor;
CXIdxLoc classLoc;
} CXIdxIBOutletCollectionAttrInfo;
typedef enum {
CXIdxDeclFlag_Skipped = 0x1
} CXIdxDeclInfoFlags;
typedef struct {
const CXIdxEntityInfo *entityInfo;
CXCursor cursor;
CXIdxLoc loc;
const CXIdxContainerInfo *semanticContainer;
/**
* \brief Generally same as #semanticContainer but can be different in
* cases like out-of-line C++ member functions.
*/
const CXIdxContainerInfo *lexicalContainer;
int isRedeclaration;
int isDefinition;
int isContainer;
const CXIdxContainerInfo *declAsContainer;
/**
* \brief Whether the declaration exists in code or was created implicitly
* by the compiler, e.g. implicit Objective-C methods for properties.
*/
int isImplicit;
const CXIdxAttrInfo *const *attributes;
unsigned numAttributes;
unsigned flags;
} CXIdxDeclInfo;
typedef enum {
CXIdxObjCContainer_ForwardRef = 0,
CXIdxObjCContainer_Interface = 1,
CXIdxObjCContainer_Implementation = 2
} CXIdxObjCContainerKind;
typedef struct {
const CXIdxDeclInfo *declInfo;
CXIdxObjCContainerKind kind;
} CXIdxObjCContainerDeclInfo;
typedef struct {
const CXIdxEntityInfo *base;
CXCursor cursor;
CXIdxLoc loc;
} CXIdxBaseClassInfo;
typedef struct {
const CXIdxEntityInfo *protocol;
CXCursor cursor;
CXIdxLoc loc;
} CXIdxObjCProtocolRefInfo;
typedef struct {
const CXIdxObjCProtocolRefInfo *const *protocols;
unsigned numProtocols;
} CXIdxObjCProtocolRefListInfo;
typedef struct {
const CXIdxObjCContainerDeclInfo *containerInfo;
const CXIdxBaseClassInfo *superInfo;
const CXIdxObjCProtocolRefListInfo *protocols;
} CXIdxObjCInterfaceDeclInfo;
typedef struct {
const CXIdxObjCContainerDeclInfo *containerInfo;
const CXIdxEntityInfo *objcClass;
CXCursor classCursor;
CXIdxLoc classLoc;
const CXIdxObjCProtocolRefListInfo *protocols;
} CXIdxObjCCategoryDeclInfo;
typedef struct {
const CXIdxDeclInfo *declInfo;
const CXIdxEntityInfo *getter;
const CXIdxEntityInfo *setter;
} CXIdxObjCPropertyDeclInfo;
typedef struct {
const CXIdxDeclInfo *declInfo;
const CXIdxBaseClassInfo *const *bases;
unsigned numBases;
} CXIdxCXXClassDeclInfo;
/**
* \brief Data for IndexerCallbacks#indexEntityReference.
*/
typedef enum {
/**
* \brief The entity is referenced directly in user's code.
*/
CXIdxEntityRef_Direct = 1,
/**
* \brief An implicit reference, e.g. a reference of an Objective-C method
* via the dot syntax.
*/
CXIdxEntityRef_Implicit = 2
} CXIdxEntityRefKind;
/**
* \brief Data for IndexerCallbacks#indexEntityReference.
*/
typedef struct {
CXIdxEntityRefKind kind;
/**
* \brief Reference cursor.
*/
CXCursor cursor;
CXIdxLoc loc;
/**
* \brief The entity that gets referenced.
*/
const CXIdxEntityInfo *referencedEntity;
/**
* \brief Immediate "parent" of the reference. For example:
*
* \code
* Foo *var;
* \endcode
*
* The parent of reference of type 'Foo' is the variable 'var'.
* For references inside statement bodies of functions/methods,
* the parentEntity will be the function/method.
*/
const CXIdxEntityInfo *parentEntity;
/**
* \brief Lexical container context of the reference.
*/
const CXIdxContainerInfo *container;
} CXIdxEntityRefInfo;
/**
* \brief A group of callbacks used by #clang_indexSourceFile and
* #clang_indexTranslationUnit.
*/
typedef struct {
/**
* \brief Called periodically to check whether indexing should be aborted.
* Should return 0 to continue, and non-zero to abort.
*/
int (*abortQuery)(CXClientData client_data, void *reserved);
/**
* \brief Called at the end of indexing; passes the complete diagnostic set.
*/
void (*diagnostic)(CXClientData client_data,
CXDiagnosticSet, void *reserved);
CXIdxClientFile (*enteredMainFile)(CXClientData client_data,
CXFile mainFile, void *reserved);
/**
* \brief Called when a file gets \#included/\#imported.
*/
CXIdxClientFile (*ppIncludedFile)(CXClientData client_data,
const CXIdxIncludedFileInfo *);
/**
* \brief Called when a AST file (PCH or module) gets imported.
*
* AST files will not get indexed (there will not be callbacks to index all
* the entities in an AST file). The recommended action is that, if the AST
* file is not already indexed, to initiate a new indexing job specific to
* the AST file.
*/
CXIdxClientASTFile (*importedASTFile)(CXClientData client_data,
const CXIdxImportedASTFileInfo *);
/**
* \brief Called at the beginning of indexing a translation unit.
*/
CXIdxClientContainer (*startedTranslationUnit)(CXClientData client_data,
void *reserved);
void (*indexDeclaration)(CXClientData client_data,
const CXIdxDeclInfo *);
/**
* \brief Called to index a reference of an entity.
*/
void (*indexEntityReference)(CXClientData client_data,
const CXIdxEntityRefInfo *);
} IndexerCallbacks;
CINDEX_LINKAGE int clang_index_isEntityObjCContainerKind(CXIdxEntityKind);
CINDEX_LINKAGE const CXIdxObjCContainerDeclInfo *
clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *);
CINDEX_LINKAGE const CXIdxObjCInterfaceDeclInfo *
clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *);
CINDEX_LINKAGE
const CXIdxObjCCategoryDeclInfo *
clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *);
CINDEX_LINKAGE const CXIdxObjCProtocolRefListInfo *
clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *);
CINDEX_LINKAGE const CXIdxObjCPropertyDeclInfo *
clang_index_getObjCPropertyDeclInfo(const CXIdxDeclInfo *);
CINDEX_LINKAGE const CXIdxIBOutletCollectionAttrInfo *
clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *);
CINDEX_LINKAGE const CXIdxCXXClassDeclInfo *
clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *);
/**
* \brief For retrieving a custom CXIdxClientContainer attached to a
* container.
*/
CINDEX_LINKAGE CXIdxClientContainer
clang_index_getClientContainer(const CXIdxContainerInfo *);
/**
* \brief For setting a custom CXIdxClientContainer attached to a
* container.
*/
CINDEX_LINKAGE void
clang_index_setClientContainer(const CXIdxContainerInfo *,CXIdxClientContainer);
/**
* \brief For retrieving a custom CXIdxClientEntity attached to an entity.
*/
CINDEX_LINKAGE CXIdxClientEntity
clang_index_getClientEntity(const CXIdxEntityInfo *);
/**
* \brief For setting a custom CXIdxClientEntity attached to an entity.
*/
CINDEX_LINKAGE void
clang_index_setClientEntity(const CXIdxEntityInfo *, CXIdxClientEntity);
/**
* \brief An indexing action/session, to be applied to one or multiple
* translation units.
*/
typedef void *CXIndexAction;
/**
* \brief An indexing action/session, to be applied to one or multiple
* translation units.
*
* \param CIdx The index object with which the index action will be associated.
*/
CINDEX_LINKAGE CXIndexAction clang_IndexAction_create(CXIndex CIdx);
/**
* \brief Destroy the given index action.
*
* The index action must not be destroyed until all of the translation units
* created within that index action have been destroyed.
*/
CINDEX_LINKAGE void clang_IndexAction_dispose(CXIndexAction);
typedef enum {
/**
* \brief Used to indicate that no special indexing options are needed.
*/
CXIndexOpt_None = 0x0,
/**
* \brief Used to indicate that IndexerCallbacks#indexEntityReference should
* be invoked for only one reference of an entity per source file that does
* not also include a declaration/definition of the entity.
*/
CXIndexOpt_SuppressRedundantRefs = 0x1,
/**
* \brief Function-local symbols should be indexed. If this is not set
* function-local symbols will be ignored.
*/
CXIndexOpt_IndexFunctionLocalSymbols = 0x2,
/**
* \brief Implicit function/class template instantiations should be indexed.
* If this is not set, implicit instantiations will be ignored.
*/
CXIndexOpt_IndexImplicitTemplateInstantiations = 0x4,
/**
* \brief Suppress all compiler warnings when parsing for indexing.
*/
CXIndexOpt_SuppressWarnings = 0x8,
/**
* \brief Skip a function/method body that was already parsed during an
* indexing session associated with a \c CXIndexAction object.
* Bodies in system headers are always skipped.
*/
CXIndexOpt_SkipParsedBodiesInSession = 0x10
} CXIndexOptFlags;
/**
* \brief Index the given source file and the translation unit corresponding
* to that file via callbacks implemented through #IndexerCallbacks.
*
* \param client_data pointer data supplied by the client, which will
* be passed to the invoked callbacks.
*
* \param index_callbacks Pointer to indexing callbacks that the client
* implements.
*
* \param index_callbacks_size Size of #IndexerCallbacks structure that gets
* passed in index_callbacks.
*
* \param index_options A bitmask of options that affects how indexing is
* performed. This should be a bitwise OR of the CXIndexOpt_XXX flags.
*
* \param[out] out_TU pointer to store a \c CXTranslationUnit that can be
* reused after indexing is finished. Set to \c NULL if you do not require it.
*
* \returns 0 on success or if there were errors from which the compiler could
* recover. If there is a failure from which there is no recovery, returns
* a non-zero \c CXErrorCode.
*
* The rest of the parameters are the same as #clang_parseTranslationUnit.
*/
CINDEX_LINKAGE int clang_indexSourceFile(CXIndexAction,
CXClientData client_data,
IndexerCallbacks *index_callbacks,
unsigned index_callbacks_size,
unsigned index_options,
const char *source_filename,
const char * const *command_line_args,
int num_command_line_args,
struct CXUnsavedFile *unsaved_files,
unsigned num_unsaved_files,
CXTranslationUnit *out_TU,
unsigned TU_options);
/**
* \brief Index the given translation unit via callbacks implemented through
* #IndexerCallbacks.
*
* The order of callback invocations is not guaranteed to be the same as
* when indexing a source file. The high level order will be:
*
* -Preprocessor callbacks invocations
* -Declaration/reference callbacks invocations
* -Diagnostic callback invocations
*
* The parameters are the same as #clang_indexSourceFile.
*
* \returns If there is a failure from which there is no recovery, returns
* non-zero, otherwise returns 0.
*/
CINDEX_LINKAGE int clang_indexTranslationUnit(CXIndexAction,
CXClientData client_data,
IndexerCallbacks *index_callbacks,
unsigned index_callbacks_size,
unsigned index_options,
CXTranslationUnit);
/**
* \brief Retrieve the CXIdxFile, file, line, column, and offset represented by
* the given CXIdxLoc.
*
* If the location refers into a macro expansion, retrieves the
* location of the macro expansion and if it refers into a macro argument
* retrieves the location of the argument.
*/
CINDEX_LINKAGE void clang_indexLoc_getFileLocation(CXIdxLoc loc,
CXIdxClientFile *indexFile,
CXFile *file,
unsigned *line,
unsigned *column,
unsigned *offset);
/**
* \brief Retrieve the CXSourceLocation represented by the given CXIdxLoc.
*/
CINDEX_LINKAGE
CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc loc);
/**
* \brief Visitor invoked for each field found by a traversal.
*
* This visitor function will be invoked for each field found by
* \c clang_Type_visitFields. Its first argument is the cursor being
* visited, its second argument is the client data provided to
* \c clang_Type_visitFields.
*
* The visitor should return one of the \c CXVisitorResult values
* to direct \c clang_Type_visitFields.
*/
typedef enum CXVisitorResult (*CXFieldVisitor)(CXCursor C,
CXClientData client_data);
/**
* \brief Visit the fields of a particular type.
*
* This function visits all the direct fields of the given cursor,
* invoking the given \p visitor function with the cursors of each
* visited field. The traversal may be ended prematurely, if
* the visitor returns \c CXFieldVisit_Break.
*
* \param T the record type whose field may be visited.
*
* \param visitor the visitor function that will be invoked for each
* field of \p T.
*
* \param client_data pointer data supplied by the client, which will
* be passed to the visitor each time it is invoked.
*
* \returns a non-zero value if the traversal was terminated
* prematurely by the visitor returning \c CXFieldVisit_Break.
*/
CINDEX_LINKAGE unsigned clang_Type_visitFields(CXType T,
CXFieldVisitor visitor,
CXClientData client_data);
/**
* @}
*/
/**
* @}
*/
// HLSL Change Starts
unsigned clang_ms_countSkippedRanges(CXTranslationUnit TU, CXFile file);
void clang_ms_getSkippedRanges(CXTranslationUnit TU, CXFile file, CXSourceRange* ranges, unsigned len);
// HLSL Change Ends
#ifdef __cplusplus
}
#endif
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include | repos/DirectXShaderCompiler/tools/clang/include/clang-c/Documentation.h | /*==-- clang-c/Documentation.h - Utilities for comment processing -*- C -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This header provides a supplementary interface for inspecting *|
|* documentation comments. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_CLANG_C_DOCUMENTATION_H
#define LLVM_CLANG_C_DOCUMENTATION_H
#include "clang-c/Index.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \defgroup CINDEX_COMMENT Comment introspection
*
* The routines in this group provide access to information in documentation
* comments. These facilities are distinct from the core and may be subject to
* their own schedule of stability and deprecation.
*
* @{
*/
/**
* \brief A parsed comment.
*/
typedef struct {
const void *ASTNode;
CXTranslationUnit TranslationUnit;
} CXComment;
/**
* \brief Given a cursor that represents a documentable entity (e.g.,
* declaration), return the associated parsed comment as a
* \c CXComment_FullComment AST node.
*/
CINDEX_LINKAGE CXComment clang_Cursor_getParsedComment(CXCursor C);
/**
* \brief Describes the type of the comment AST node (\c CXComment). A comment
* node can be considered block content (e. g., paragraph), inline content
* (plain text) or neither (the root AST node).
*/
enum CXCommentKind {
/**
* \brief Null comment. No AST node is constructed at the requested location
* because there is no text or a syntax error.
*/
CXComment_Null = 0,
/**
* \brief Plain text. Inline content.
*/
CXComment_Text = 1,
/**
* \brief A command with word-like arguments that is considered inline content.
*
* For example: \\c command.
*/
CXComment_InlineCommand = 2,
/**
* \brief HTML start tag with attributes (name-value pairs). Considered
* inline content.
*
* For example:
* \verbatim
* <br> <br /> <a href="http://example.org/">
* \endverbatim
*/
CXComment_HTMLStartTag = 3,
/**
* \brief HTML end tag. Considered inline content.
*
* For example:
* \verbatim
* </a>
* \endverbatim
*/
CXComment_HTMLEndTag = 4,
/**
* \brief A paragraph, contains inline comment. The paragraph itself is
* block content.
*/
CXComment_Paragraph = 5,
/**
* \brief A command that has zero or more word-like arguments (number of
* word-like arguments depends on command name) and a paragraph as an
* argument. Block command is block content.
*
* Paragraph argument is also a child of the block command.
*
* For example: \\brief has 0 word-like arguments and a paragraph argument.
*
* AST nodes of special kinds that parser knows about (e. g., \\param
* command) have their own node kinds.
*/
CXComment_BlockCommand = 6,
/**
* \brief A \\param or \\arg command that describes the function parameter
* (name, passing direction, description).
*
* For example: \\param [in] ParamName description.
*/
CXComment_ParamCommand = 7,
/**
* \brief A \\tparam command that describes a template parameter (name and
* description).
*
* For example: \\tparam T description.
*/
CXComment_TParamCommand = 8,
/**
* \brief A verbatim block command (e. g., preformatted code). Verbatim
* block has an opening and a closing command and contains multiple lines of
* text (\c CXComment_VerbatimBlockLine child nodes).
*
* For example:
* \\verbatim
* aaa
* \\endverbatim
*/
CXComment_VerbatimBlockCommand = 9,
/**
* \brief A line of text that is contained within a
* CXComment_VerbatimBlockCommand node.
*/
CXComment_VerbatimBlockLine = 10,
/**
* \brief A verbatim line command. Verbatim line has an opening command,
* a single line of text (up to the newline after the opening command) and
* has no closing command.
*/
CXComment_VerbatimLine = 11,
/**
* \brief A full comment attached to a declaration, contains block content.
*/
CXComment_FullComment = 12
};
/**
* \brief The most appropriate rendering mode for an inline command, chosen on
* command semantics in Doxygen.
*/
enum CXCommentInlineCommandRenderKind {
/**
* \brief Command argument should be rendered in a normal font.
*/
CXCommentInlineCommandRenderKind_Normal,
/**
* \brief Command argument should be rendered in a bold font.
*/
CXCommentInlineCommandRenderKind_Bold,
/**
* \brief Command argument should be rendered in a monospaced font.
*/
CXCommentInlineCommandRenderKind_Monospaced,
/**
* \brief Command argument should be rendered emphasized (typically italic
* font).
*/
CXCommentInlineCommandRenderKind_Emphasized
};
/**
* \brief Describes parameter passing direction for \\param or \\arg command.
*/
enum CXCommentParamPassDirection {
/**
* \brief The parameter is an input parameter.
*/
CXCommentParamPassDirection_In,
/**
* \brief The parameter is an output parameter.
*/
CXCommentParamPassDirection_Out,
/**
* \brief The parameter is an input and output parameter.
*/
CXCommentParamPassDirection_InOut
};
/**
* \param Comment AST node of any kind.
*
* \returns the type of the AST node.
*/
CINDEX_LINKAGE enum CXCommentKind clang_Comment_getKind(CXComment Comment);
/**
* \param Comment AST node of any kind.
*
* \returns number of children of the AST node.
*/
CINDEX_LINKAGE unsigned clang_Comment_getNumChildren(CXComment Comment);
/**
* \param Comment AST node of any kind.
*
* \param ChildIdx child index (zero-based).
*
* \returns the specified child of the AST node.
*/
CINDEX_LINKAGE
CXComment clang_Comment_getChild(CXComment Comment, unsigned ChildIdx);
/**
* \brief A \c CXComment_Paragraph node is considered whitespace if it contains
* only \c CXComment_Text nodes that are empty or whitespace.
*
* Other AST nodes (except \c CXComment_Paragraph and \c CXComment_Text) are
* never considered whitespace.
*
* \returns non-zero if \c Comment is whitespace.
*/
CINDEX_LINKAGE unsigned clang_Comment_isWhitespace(CXComment Comment);
/**
* \returns non-zero if \c Comment is inline content and has a newline
* immediately following it in the comment text. Newlines between paragraphs
* do not count.
*/
CINDEX_LINKAGE
unsigned clang_InlineContentComment_hasTrailingNewline(CXComment Comment);
/**
* \param Comment a \c CXComment_Text AST node.
*
* \returns text contained in the AST node.
*/
CINDEX_LINKAGE CXString clang_TextComment_getText(CXComment Comment);
/**
* \param Comment a \c CXComment_InlineCommand AST node.
*
* \returns name of the inline command.
*/
CINDEX_LINKAGE
CXString clang_InlineCommandComment_getCommandName(CXComment Comment);
/**
* \param Comment a \c CXComment_InlineCommand AST node.
*
* \returns the most appropriate rendering mode, chosen on command
* semantics in Doxygen.
*/
CINDEX_LINKAGE enum CXCommentInlineCommandRenderKind
clang_InlineCommandComment_getRenderKind(CXComment Comment);
/**
* \param Comment a \c CXComment_InlineCommand AST node.
*
* \returns number of command arguments.
*/
CINDEX_LINKAGE
unsigned clang_InlineCommandComment_getNumArgs(CXComment Comment);
/**
* \param Comment a \c CXComment_InlineCommand AST node.
*
* \param ArgIdx argument index (zero-based).
*
* \returns text of the specified argument.
*/
CINDEX_LINKAGE
CXString clang_InlineCommandComment_getArgText(CXComment Comment,
unsigned ArgIdx);
/**
* \param Comment a \c CXComment_HTMLStartTag or \c CXComment_HTMLEndTag AST
* node.
*
* \returns HTML tag name.
*/
CINDEX_LINKAGE CXString clang_HTMLTagComment_getTagName(CXComment Comment);
/**
* \param Comment a \c CXComment_HTMLStartTag AST node.
*
* \returns non-zero if tag is self-closing (for example, <br />).
*/
CINDEX_LINKAGE
unsigned clang_HTMLStartTagComment_isSelfClosing(CXComment Comment);
/**
* \param Comment a \c CXComment_HTMLStartTag AST node.
*
* \returns number of attributes (name-value pairs) attached to the start tag.
*/
CINDEX_LINKAGE unsigned clang_HTMLStartTag_getNumAttrs(CXComment Comment);
/**
* \param Comment a \c CXComment_HTMLStartTag AST node.
*
* \param AttrIdx attribute index (zero-based).
*
* \returns name of the specified attribute.
*/
CINDEX_LINKAGE
CXString clang_HTMLStartTag_getAttrName(CXComment Comment, unsigned AttrIdx);
/**
* \param Comment a \c CXComment_HTMLStartTag AST node.
*
* \param AttrIdx attribute index (zero-based).
*
* \returns value of the specified attribute.
*/
CINDEX_LINKAGE
CXString clang_HTMLStartTag_getAttrValue(CXComment Comment, unsigned AttrIdx);
/**
* \param Comment a \c CXComment_BlockCommand AST node.
*
* \returns name of the block command.
*/
CINDEX_LINKAGE
CXString clang_BlockCommandComment_getCommandName(CXComment Comment);
/**
* \param Comment a \c CXComment_BlockCommand AST node.
*
* \returns number of word-like arguments.
*/
CINDEX_LINKAGE
unsigned clang_BlockCommandComment_getNumArgs(CXComment Comment);
/**
* \param Comment a \c CXComment_BlockCommand AST node.
*
* \param ArgIdx argument index (zero-based).
*
* \returns text of the specified word-like argument.
*/
CINDEX_LINKAGE
CXString clang_BlockCommandComment_getArgText(CXComment Comment,
unsigned ArgIdx);
/**
* \param Comment a \c CXComment_BlockCommand or
* \c CXComment_VerbatimBlockCommand AST node.
*
* \returns paragraph argument of the block command.
*/
CINDEX_LINKAGE
CXComment clang_BlockCommandComment_getParagraph(CXComment Comment);
/**
* \param Comment a \c CXComment_ParamCommand AST node.
*
* \returns parameter name.
*/
CINDEX_LINKAGE
CXString clang_ParamCommandComment_getParamName(CXComment Comment);
/**
* \param Comment a \c CXComment_ParamCommand AST node.
*
* \returns non-zero if the parameter that this AST node represents was found
* in the function prototype and \c clang_ParamCommandComment_getParamIndex
* function will return a meaningful value.
*/
CINDEX_LINKAGE
unsigned clang_ParamCommandComment_isParamIndexValid(CXComment Comment);
/**
* \param Comment a \c CXComment_ParamCommand AST node.
*
* \returns zero-based parameter index in function prototype.
*/
CINDEX_LINKAGE
unsigned clang_ParamCommandComment_getParamIndex(CXComment Comment);
/**
* \param Comment a \c CXComment_ParamCommand AST node.
*
* \returns non-zero if parameter passing direction was specified explicitly in
* the comment.
*/
CINDEX_LINKAGE
unsigned clang_ParamCommandComment_isDirectionExplicit(CXComment Comment);
/**
* \param Comment a \c CXComment_ParamCommand AST node.
*
* \returns parameter passing direction.
*/
CINDEX_LINKAGE
enum CXCommentParamPassDirection clang_ParamCommandComment_getDirection(
CXComment Comment);
/**
* \param Comment a \c CXComment_TParamCommand AST node.
*
* \returns template parameter name.
*/
CINDEX_LINKAGE
CXString clang_TParamCommandComment_getParamName(CXComment Comment);
/**
* \param Comment a \c CXComment_TParamCommand AST node.
*
* \returns non-zero if the parameter that this AST node represents was found
* in the template parameter list and
* \c clang_TParamCommandComment_getDepth and
* \c clang_TParamCommandComment_getIndex functions will return a meaningful
* value.
*/
CINDEX_LINKAGE
unsigned clang_TParamCommandComment_isParamPositionValid(CXComment Comment);
/**
* \param Comment a \c CXComment_TParamCommand AST node.
*
* \returns zero-based nesting depth of this parameter in the template parameter list.
*
* For example,
* \verbatim
* template<typename C, template<typename T> class TT>
* void test(TT<int> aaa);
* \endverbatim
* for C and TT nesting depth is 0,
* for T nesting depth is 1.
*/
CINDEX_LINKAGE
unsigned clang_TParamCommandComment_getDepth(CXComment Comment);
/**
* \param Comment a \c CXComment_TParamCommand AST node.
*
* \returns zero-based parameter index in the template parameter list at a
* given nesting depth.
*
* For example,
* \verbatim
* template<typename C, template<typename T> class TT>
* void test(TT<int> aaa);
* \endverbatim
* for C and TT nesting depth is 0, so we can ask for index at depth 0:
* at depth 0 C's index is 0, TT's index is 1.
*
* For T nesting depth is 1, so we can ask for index at depth 0 and 1:
* at depth 0 T's index is 1 (same as TT's),
* at depth 1 T's index is 0.
*/
CINDEX_LINKAGE
unsigned clang_TParamCommandComment_getIndex(CXComment Comment, unsigned Depth);
/**
* \param Comment a \c CXComment_VerbatimBlockLine AST node.
*
* \returns text contained in the AST node.
*/
CINDEX_LINKAGE
CXString clang_VerbatimBlockLineComment_getText(CXComment Comment);
/**
* \param Comment a \c CXComment_VerbatimLine AST node.
*
* \returns text contained in the AST node.
*/
CINDEX_LINKAGE CXString clang_VerbatimLineComment_getText(CXComment Comment);
/**
* \brief Convert an HTML tag AST node to string.
*
* \param Comment a \c CXComment_HTMLStartTag or \c CXComment_HTMLEndTag AST
* node.
*
* \returns string containing an HTML tag.
*/
CINDEX_LINKAGE CXString clang_HTMLTagComment_getAsString(CXComment Comment);
/**
* \brief Convert a given full parsed comment to an HTML fragment.
*
* Specific details of HTML layout are subject to change. Don't try to parse
* this HTML back into an AST, use other APIs instead.
*
* Currently the following CSS classes are used:
* \li "para-brief" for \\brief paragraph and equivalent commands;
* \li "para-returns" for \\returns paragraph and equivalent commands;
* \li "word-returns" for the "Returns" word in \\returns paragraph.
*
* Function argument documentation is rendered as a \<dl\> list with arguments
* sorted in function prototype order. CSS classes used:
* \li "param-name-index-NUMBER" for parameter name (\<dt\>);
* \li "param-descr-index-NUMBER" for parameter description (\<dd\>);
* \li "param-name-index-invalid" and "param-descr-index-invalid" are used if
* parameter index is invalid.
*
* Template parameter documentation is rendered as a \<dl\> list with
* parameters sorted in template parameter list order. CSS classes used:
* \li "tparam-name-index-NUMBER" for parameter name (\<dt\>);
* \li "tparam-descr-index-NUMBER" for parameter description (\<dd\>);
* \li "tparam-name-index-other" and "tparam-descr-index-other" are used for
* names inside template template parameters;
* \li "tparam-name-index-invalid" and "tparam-descr-index-invalid" are used if
* parameter position is invalid.
*
* \param Comment a \c CXComment_FullComment AST node.
*
* \returns string containing an HTML fragment.
*/
CINDEX_LINKAGE CXString clang_FullComment_getAsHTML(CXComment Comment);
/**
* \brief Convert a given full parsed comment to an XML document.
*
* A Relax NG schema for the XML can be found in comment-xml-schema.rng file
* inside clang source tree.
*
* \param Comment a \c CXComment_FullComment AST node.
*
* \returns string containing an XML document.
*/
CINDEX_LINKAGE CXString clang_FullComment_getAsXML(CXComment Comment);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* CLANG_C_DOCUMENTATION_H */
|
0 | repos/DirectXShaderCompiler/tools/clang/include | repos/DirectXShaderCompiler/tools/clang/include/clang-c/CXString.h | /*===-- clang-c/CXString.h - C Index strings --------------------*- C -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This header provides the interface to C Index strings. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_CLANG_C_CXSTRING_H
#define LLVM_CLANG_C_CXSTRING_H
#include "clang-c/Platform.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \defgroup CINDEX_STRING String manipulation routines
* \ingroup CINDEX
*
* @{
*/
/**
* \brief A character string.
*
* The \c CXString type is used to return strings from the interface when
* the ownership of that string might differ from one call to the next.
* Use \c clang_getCString() to retrieve the string data and, once finished
* with the string data, call \c clang_disposeString() to free the string.
*/
typedef struct {
const void *data;
unsigned private_flags;
} CXString;
/**
* \brief Retrieve the character data associated with the given string.
*/
CINDEX_LINKAGE const char * LIBCLANG_CC clang_getCString(CXString string);
/**
* \brief Free the given string.
*/
CINDEX_LINKAGE void LIBCLANG_CC clang_disposeString(CXString string);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include | repos/DirectXShaderCompiler/tools/clang/include/clang/CMakeLists.txt | add_subdirectory(AST)
add_subdirectory(Basic)
add_subdirectory(Driver)
add_subdirectory(Parse)
add_subdirectory(Sema)
add_subdirectory(Serialization)
|
0 | repos/DirectXShaderCompiler/tools/clang/include | repos/DirectXShaderCompiler/tools/clang/include/clang/module.modulemap | module Clang_Analysis {
requires cplusplus
umbrella "Analysis"
textual header "Analysis/Analyses/ThreadSafetyOps.def"
module * { export * }
}
module Clang_AST {
requires cplusplus
umbrella "AST"
textual header "AST/BuiltinTypes.def"
textual header "AST/TypeLocNodes.def"
textual header "AST/TypeNodes.def"
module * { export * }
}
module Clang_ASTMatchers { requires cplusplus umbrella "ASTMatchers" module * { export * } }
module Clang_Basic {
requires cplusplus
umbrella "Basic"
textual header "Basic/BuiltinsAArch64.def"
textual header "Basic/BuiltinsARM.def"
textual header "Basic/Builtins.def"
textual header "Basic/BuiltinsHexagon.def"
textual header "Basic/BuiltinsLe64.def"
textual header "Basic/BuiltinsMips.def"
textual header "Basic/BuiltinsNEON.def"
textual header "Basic/BuiltinsNVPTX.def"
textual header "Basic/BuiltinsPPC.def"
textual header "Basic/BuiltinsR600.def"
textual header "Basic/BuiltinsSystemZ.def"
textual header "Basic/BuiltinsX86.def"
textual header "Basic/BuiltinsXCore.def"
textual header "Basic/DiagnosticOptions.def"
textual header "Basic/LangOptions.def"
textual header "Basic/OpenCLExtensions.def"
textual header "Basic/OpenMPKinds.def"
textual header "Basic/OperatorKinds.def"
textual header "Basic/Sanitizers.def"
textual header "Basic/TokenKinds.def"
module * { export * }
}
module Clang_CodeGen { requires cplusplus umbrella "CodeGen" module * { export * } }
module Clang_Config { requires cplusplus umbrella "Config" module * { export * } }
// Files for diagnostic groups are spread all over the include/clang/ tree, but
// logically form a single module.
module Clang_Diagnostics {
requires cplusplus
module All { header "Basic/AllDiagnostics.h" export * }
module Analysis { header "Analysis/AnalysisDiagnostic.h" export * }
module AST { header "AST/ASTDiagnostic.h" export * }
module Comment { header "AST/CommentDiagnostic.h" export * }
module Driver { header "Driver/DriverDiagnostic.h" export * }
module Frontend { header "Frontend/FrontendDiagnostic.h" export * }
module Lex { header "Lex/LexDiagnostic.h" export * }
module Parse { header "Parse/ParseDiagnostic.h" export * }
// FIXME: This breaks the build of Clang_Sema, for unknown reasons.
//module Sema { header "Sema/SemaDiagnostic.h" export * }
module Serialization { header "Serialization/SerializationDiagnostic.h" export * }
}
module Clang_Driver {
requires cplusplus
umbrella "Driver"
textual header "Driver/Types.def"
module * { export * }
}
module Clang_Edit { requires cplusplus umbrella "Edit" module * { export * } }
module Clang_Format { requires cplusplus umbrella "Format" module * { export * } }
module Clang_Frontend {
requires cplusplus
umbrella "Frontend"
textual header "Frontend/CodeGenOptions.def"
textual header "Frontend/LangStandards.def"
module * { export * }
}
module Clang_FrontendTool { requires cplusplus umbrella "FrontendTool" module * { export * } }
module Clang_Index { requires cplusplus umbrella "Index" module * { export * } }
module Clang_Lex { requires cplusplus umbrella "Lex" module * { export * } }
module Clang_Parse { requires cplusplus umbrella "Parse" module * { export * } }
module Clang_Rewrite { requires cplusplus umbrella "Rewrite" module * { export * } }
module Clang_Sema { requires cplusplus umbrella "Sema" module * { export * } }
module Clang_Serialization { requires cplusplus umbrella "Serialization" module * { export * } }
module Clang_StaticAnalyzer_Core {
requires cplusplus
umbrella "StaticAnalyzer/Core"
textual header "StaticAnalyzer/Core/Analyses.def"
module * { export * }
}
module Clang_StaticAnalyzer_Checkers {
requires cplusplus
umbrella "StaticAnalyzer/Checkers"
module * { export * }
}
module Clang_StaticAnalyzer_Frontend {
requires cplusplus
umbrella "StaticAnalyzer/Frontend"
module * { export * }
}
module Clang_Tooling {
requires cplusplus umbrella "Tooling" module * { export * }
// FIXME: Exclude this header to avoid pulling all of the AST matchers
// library into clang-format. Due to inline key functions in the headers,
// importing the AST matchers library gives a link dependency on the AST
// matchers (and thus the AST), which clang-format should not have.
exclude header "Tooling/RefactoringCallbacks.h"
}
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Config/config.h.cmake | /* This generated file is for internal use. Do not include it from headers. */
#ifdef CONFIG_H
#error config.h can only be included once
#else
#define CONFIG_H
/* Bug report URL. */
#define BUG_REPORT_URL "${BUG_REPORT_URL}"
/* Default OpenMP runtime used by -fopenmp. */
#define CLANG_DEFAULT_OPENMP_RUNTIME "${CLANG_DEFAULT_OPENMP_RUNTIME}"
/* Multilib suffix for libdir. */
#define CLANG_LIBDIR_SUFFIX "${CLANG_LIBDIR_SUFFIX}"
/* Relative directory for resource files */
#define CLANG_RESOURCE_DIR "${CLANG_RESOURCE_DIR}"
/* Directories clang will search for headers */
#define C_INCLUDE_DIRS "${C_INCLUDE_DIRS}"
/* Default <path> to all compiler invocations for --sysroot=<path>. */
#define DEFAULT_SYSROOT "${DEFAULT_SYSROOT}"
/* Directory where gcc is installed. */
#define GCC_INSTALL_PREFIX "${GCC_INSTALL_PREFIX}"
/* Define if we have libxml2 */
#cmakedefine CLANG_HAVE_LIBXML ${CLANG_HAVE_LIBXML}
/* The LLVM product name and version */
#define BACKEND_PACKAGE_STRING "${BACKEND_PACKAGE_STRING}"
/* Linker version detected at compile time. */
#cmakedefine HOST_LINK_VERSION "${HOST_LINK_VERSION}"
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Config/config.h.in | /* This generated file is for internal use. Do not include it from headers. */
#ifdef CONFIG_H
#error config.h can only be included once
#else
#define CONFIG_H
/* Bug report URL. */
#undef BUG_REPORT_URL
/* Default OpenMP runtime used by -fopenmp. */
#undef CLANG_DEFAULT_OPENMP_RUNTIME
/* Multilib suffix for libdir. */
#undef CLANG_LIBDIR_SUFFIX
/* Relative directory for resource files */
#undef CLANG_RESOURCE_DIR
/* Directories clang will search for headers */
#undef C_INCLUDE_DIRS
/* Default <path> to all compiler invocations for --sysroot=<path>. */
#undef DEFAULT_SYSROOT
/* Directory where gcc is installed. */
#undef GCC_INSTALL_PREFIX
/* Define if we have libxml2 */
#undef CLANG_HAVE_LIBXML
#undef PACKAGE_STRING
/* The LLVM product name and version */
#define BACKEND_PACKAGE_STRING PACKAGE_STRING
/* Linker version detected at compile time. */
#undef HOST_LINK_VERSION
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Edit/FileOffset.h | //===----- FileOffset.h - Offset in a file ----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_EDIT_FILEOFFSET_H
#define LLVM_CLANG_EDIT_FILEOFFSET_H
#include "clang/Basic/SourceLocation.h"
namespace clang {
namespace edit {
class FileOffset {
FileID FID;
unsigned Offs;
public:
FileOffset() : Offs(0) { }
FileOffset(FileID fid, unsigned offs) : FID(fid), Offs(offs) { }
bool isInvalid() const { return FID.isInvalid(); }
FileID getFID() const { return FID; }
unsigned getOffset() const { return Offs; }
FileOffset getWithOffset(unsigned offset) const {
FileOffset NewOffs = *this;
NewOffs.Offs += offset;
return NewOffs;
}
friend bool operator==(FileOffset LHS, FileOffset RHS) {
return LHS.FID == RHS.FID && LHS.Offs == RHS.Offs;
}
friend bool operator!=(FileOffset LHS, FileOffset RHS) {
return !(LHS == RHS);
}
friend bool operator<(FileOffset LHS, FileOffset RHS) {
return std::tie(LHS.FID, LHS.Offs) < std::tie(RHS.FID, RHS.Offs);
}
friend bool operator>(FileOffset LHS, FileOffset RHS) {
return RHS < LHS;
}
friend bool operator>=(FileOffset LHS, FileOffset RHS) {
return !(LHS < RHS);
}
friend bool operator<=(FileOffset LHS, FileOffset RHS) {
return !(RHS < LHS);
}
};
}
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Edit/Commit.h | //===----- Commit.h - A unit of edits ---------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_EDIT_COMMIT_H
#define LLVM_CLANG_EDIT_COMMIT_H
#include "clang/Edit/FileOffset.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Allocator.h"
namespace clang {
class LangOptions;
class PPConditionalDirectiveRecord;
namespace edit {
class EditedSource;
class Commit {
public:
enum EditKind {
Act_Insert,
Act_InsertFromRange,
Act_Remove
};
struct Edit {
EditKind Kind;
StringRef Text;
SourceLocation OrigLoc;
FileOffset Offset;
FileOffset InsertFromRangeOffs;
unsigned Length;
bool BeforePrev;
SourceLocation getFileLocation(SourceManager &SM) const;
CharSourceRange getFileRange(SourceManager &SM) const;
CharSourceRange getInsertFromRange(SourceManager &SM) const;
};
private:
const SourceManager &SourceMgr;
const LangOptions &LangOpts;
const PPConditionalDirectiveRecord *PPRec;
EditedSource *Editor;
bool IsCommitable;
SmallVector<Edit, 8> CachedEdits;
llvm::BumpPtrAllocator StrAlloc;
public:
explicit Commit(EditedSource &Editor);
Commit(const SourceManager &SM, const LangOptions &LangOpts,
const PPConditionalDirectiveRecord *PPRec = nullptr)
: SourceMgr(SM), LangOpts(LangOpts), PPRec(PPRec), Editor(nullptr),
IsCommitable(true) { }
bool isCommitable() const { return IsCommitable; }
bool insert(SourceLocation loc, StringRef text, bool afterToken = false,
bool beforePreviousInsertions = false);
bool insertAfterToken(SourceLocation loc, StringRef text,
bool beforePreviousInsertions = false) {
return insert(loc, text, /*afterToken=*/true, beforePreviousInsertions);
}
bool insertBefore(SourceLocation loc, StringRef text) {
return insert(loc, text, /*afterToken=*/false,
/*beforePreviousInsertions=*/true);
}
bool insertFromRange(SourceLocation loc, CharSourceRange range,
bool afterToken = false,
bool beforePreviousInsertions = false);
bool insertWrap(StringRef before, CharSourceRange range, StringRef after);
bool remove(CharSourceRange range);
bool replace(CharSourceRange range, StringRef text);
bool replaceWithInner(CharSourceRange range, CharSourceRange innerRange);
bool replaceText(SourceLocation loc, StringRef text,
StringRef replacementText);
bool insertFromRange(SourceLocation loc, SourceRange TokenRange,
bool afterToken = false,
bool beforePreviousInsertions = false) {
return insertFromRange(loc, CharSourceRange::getTokenRange(TokenRange),
afterToken, beforePreviousInsertions);
}
bool insertWrap(StringRef before, SourceRange TokenRange, StringRef after) {
return insertWrap(before, CharSourceRange::getTokenRange(TokenRange), after);
}
bool remove(SourceRange TokenRange) {
return remove(CharSourceRange::getTokenRange(TokenRange));
}
bool replace(SourceRange TokenRange, StringRef text) {
return replace(CharSourceRange::getTokenRange(TokenRange), text);
}
bool replaceWithInner(SourceRange TokenRange, SourceRange TokenInnerRange) {
return replaceWithInner(CharSourceRange::getTokenRange(TokenRange),
CharSourceRange::getTokenRange(TokenInnerRange));
}
typedef SmallVectorImpl<Edit>::const_iterator edit_iterator;
edit_iterator edit_begin() const { return CachedEdits.begin(); }
edit_iterator edit_end() const { return CachedEdits.end(); }
private:
void addInsert(SourceLocation OrigLoc,
FileOffset Offs, StringRef text, bool beforePreviousInsertions);
void addInsertFromRange(SourceLocation OrigLoc, FileOffset Offs,
FileOffset RangeOffs, unsigned RangeLen,
bool beforePreviousInsertions);
void addRemove(SourceLocation OrigLoc, FileOffset Offs, unsigned Len);
bool canInsert(SourceLocation loc, FileOffset &Offset);
bool canInsertAfterToken(SourceLocation loc, FileOffset &Offset,
SourceLocation &AfterLoc);
bool canInsertInOffset(SourceLocation OrigLoc, FileOffset Offs);
bool canRemoveRange(CharSourceRange range, FileOffset &Offs, unsigned &Len);
bool canReplaceText(SourceLocation loc, StringRef text,
FileOffset &Offs, unsigned &Len);
void commitInsert(FileOffset offset, StringRef text,
bool beforePreviousInsertions);
void commitRemove(FileOffset offset, unsigned length);
bool isAtStartOfMacroExpansion(SourceLocation loc,
SourceLocation *MacroBegin = nullptr) const;
bool isAtEndOfMacroExpansion(SourceLocation loc,
SourceLocation *MacroEnd = nullptr) const;
StringRef copyString(StringRef str) {
char *buf = StrAlloc.Allocate<char>(str.size());
std::memcpy(buf, str.data(), str.size());
return StringRef(buf, str.size());
}
};
}
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Edit/Rewriters.h | //===--- Rewriters.h - Rewritings ---------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_EDIT_REWRITERS_H
#define LLVM_CLANG_EDIT_REWRITERS_H
#include "llvm/ADT/SmallVector.h"
namespace clang {
class ObjCMessageExpr;
class ObjCMethodDecl;
class ObjCInterfaceDecl;
class ObjCProtocolDecl;
class NSAPI;
class EnumDecl;
class TypedefDecl;
class ParentMap;
namespace edit {
class Commit;
bool rewriteObjCRedundantCallWithLiteral(const ObjCMessageExpr *Msg,
const NSAPI &NS, Commit &commit);
bool rewriteToObjCLiteralSyntax(const ObjCMessageExpr *Msg,
const NSAPI &NS, Commit &commit,
const ParentMap *PMap);
bool rewriteToObjCSubscriptSyntax(const ObjCMessageExpr *Msg,
const NSAPI &NS, Commit &commit);
}
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Edit/EditedSource.h | //===----- EditedSource.h - Collection of source edits ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_EDIT_EDITEDSOURCE_H
#define LLVM_CLANG_EDIT_EDITEDSOURCE_H
#include "clang/Edit/FileOffset.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Allocator.h"
#include <map>
namespace clang {
class LangOptions;
class PPConditionalDirectiveRecord;
namespace edit {
class Commit;
class EditsReceiver;
class EditedSource {
const SourceManager &SourceMgr;
const LangOptions &LangOpts;
const PPConditionalDirectiveRecord *PPRec;
struct FileEdit {
StringRef Text;
unsigned RemoveLen;
FileEdit() : RemoveLen(0) {}
};
typedef std::map<FileOffset, FileEdit> FileEditsTy;
FileEditsTy FileEdits;
llvm::DenseMap<unsigned, SourceLocation> ExpansionToArgMap;
llvm::BumpPtrAllocator StrAlloc;
public:
EditedSource(const SourceManager &SM, const LangOptions &LangOpts,
const PPConditionalDirectiveRecord *PPRec = nullptr)
: SourceMgr(SM), LangOpts(LangOpts), PPRec(PPRec),
StrAlloc() { }
const SourceManager &getSourceManager() const { return SourceMgr; }
const LangOptions &getLangOpts() const { return LangOpts; }
const PPConditionalDirectiveRecord *getPPCondDirectiveRecord() const {
return PPRec;
}
bool canInsertInOffset(SourceLocation OrigLoc, FileOffset Offs);
bool commit(const Commit &commit);
void applyRewrites(EditsReceiver &receiver);
void clearRewrites();
StringRef copyString(StringRef str) {
char *buf = StrAlloc.Allocate<char>(str.size());
std::memcpy(buf, str.data(), str.size());
return StringRef(buf, str.size());
}
StringRef copyString(const Twine &twine);
private:
bool commitInsert(SourceLocation OrigLoc, FileOffset Offs, StringRef text,
bool beforePreviousInsertions);
bool commitInsertFromRange(SourceLocation OrigLoc, FileOffset Offs,
FileOffset InsertFromRangeOffs, unsigned Len,
bool beforePreviousInsertions);
void commitRemove(SourceLocation OrigLoc, FileOffset BeginOffs, unsigned Len);
StringRef getSourceText(FileOffset BeginOffs, FileOffset EndOffs,
bool &Invalid);
FileEditsTy::iterator getActionForOffset(FileOffset Offs);
};
}
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Edit/EditsReceiver.h | //===----- EditedSource.h - Collection of source edits ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_EDIT_EDITSRECEIVER_H
#define LLVM_CLANG_EDIT_EDITSRECEIVER_H
#include "clang/Basic/LLVM.h"
namespace clang {
class SourceLocation;
class CharSourceRange;
namespace edit {
class EditsReceiver {
public:
virtual ~EditsReceiver() { }
virtual void insert(SourceLocation loc, StringRef text) = 0;
virtual void replace(CharSourceRange range, StringRef text) = 0;
/// \brief By default it calls replace with an empty string.
virtual void remove(CharSourceRange range);
};
}
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/Multilib.h | //===--- Multilib.h ---------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_DRIVER_MULTILIB_H
#define LLVM_CLANG_DRIVER_MULTILIB_H
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Option/Option.h"
#include <functional>
#include <string>
#include <vector>
namespace clang {
namespace driver {
/// This corresponds to a single GCC Multilib, or a segment of one controlled
/// by a command line flag
class Multilib {
public:
typedef std::vector<std::string> flags_list;
private:
std::string GCCSuffix;
std::string OSSuffix;
std::string IncludeSuffix;
flags_list Flags;
public:
Multilib(StringRef GCCSuffix = "", StringRef OSSuffix = "",
StringRef IncludeSuffix = "");
/// \brief Get the detected GCC installation path suffix for the multi-arch
/// target variant. Always starts with a '/', unless empty
const std::string &gccSuffix() const {
assert(GCCSuffix.empty() ||
(StringRef(GCCSuffix).front() == '/' && GCCSuffix.size() > 1));
return GCCSuffix;
}
/// Set the GCC installation path suffix.
Multilib &gccSuffix(StringRef S);
/// \brief Get the detected os path suffix for the multi-arch
/// target variant. Always starts with a '/', unless empty
const std::string &osSuffix() const {
assert(OSSuffix.empty() ||
(StringRef(OSSuffix).front() == '/' && OSSuffix.size() > 1));
return OSSuffix;
}
/// Set the os path suffix.
Multilib &osSuffix(StringRef S);
/// \brief Get the include directory suffix. Always starts with a '/', unless
/// empty
const std::string &includeSuffix() const {
assert(IncludeSuffix.empty() ||
(StringRef(IncludeSuffix).front() == '/' && IncludeSuffix.size() > 1));
return IncludeSuffix;
}
/// Set the include directory suffix
Multilib &includeSuffix(StringRef S);
/// \brief Get the flags that indicate or contraindicate this multilib's use
/// All elements begin with either '+' or '-'
const flags_list &flags() const { return Flags; }
flags_list &flags() { return Flags; }
/// Add a flag to the flags list
Multilib &flag(StringRef F) {
assert(F.front() == '+' || F.front() == '-');
Flags.push_back(F);
return *this;
}
/// \brief print summary of the Multilib
void print(raw_ostream &OS) const;
/// Check whether any of the 'against' flags contradict the 'for' flags.
bool isValid() const;
/// Check whether the default is selected
bool isDefault() const
{ return GCCSuffix.empty() && OSSuffix.empty() && IncludeSuffix.empty(); }
bool operator==(const Multilib &Other) const;
};
raw_ostream &operator<<(raw_ostream &OS, const Multilib &M);
class MultilibSet {
public:
typedef std::vector<Multilib> multilib_list;
typedef multilib_list::iterator iterator;
typedef multilib_list::const_iterator const_iterator;
typedef std::function<std::vector<std::string>(
StringRef InstallDir, StringRef Triple, const Multilib &M)>
IncludeDirsFunc;
typedef llvm::function_ref<bool(const Multilib &)> FilterCallback;
private:
multilib_list Multilibs;
IncludeDirsFunc IncludeCallback;
public:
MultilibSet() {}
/// Add an optional Multilib segment
MultilibSet &Maybe(const Multilib &M);
/// Add a set of mutually incompatible Multilib segments
MultilibSet &Either(const Multilib &M1, const Multilib &M2);
MultilibSet &Either(const Multilib &M1, const Multilib &M2,
const Multilib &M3);
MultilibSet &Either(const Multilib &M1, const Multilib &M2,
const Multilib &M3, const Multilib &M4);
MultilibSet &Either(const Multilib &M1, const Multilib &M2,
const Multilib &M3, const Multilib &M4,
const Multilib &M5);
MultilibSet &Either(ArrayRef<Multilib> Ms);
/// Filter out some subset of the Multilibs using a user defined callback
MultilibSet &FilterOut(FilterCallback F);
/// Filter out those Multilibs whose gccSuffix matches the given expression
MultilibSet &FilterOut(const char *Regex);
/// Add a completed Multilib to the set
void push_back(const Multilib &M);
/// Union this set of multilibs with another
void combineWith(const MultilibSet &MS);
/// Remove all of thie multilibs from the set
void clear() { Multilibs.clear(); }
iterator begin() { return Multilibs.begin(); }
const_iterator begin() const { return Multilibs.begin(); }
iterator end() { return Multilibs.end(); }
const_iterator end() const { return Multilibs.end(); }
/// Pick the best multilib in the set, \returns false if none are compatible
bool select(const Multilib::flags_list &Flags, Multilib &M) const;
unsigned size() const { return Multilibs.size(); }
void print(raw_ostream &OS) const;
MultilibSet &setIncludeDirsCallback(IncludeDirsFunc F) {
IncludeCallback = std::move(F);
return *this;
}
const IncludeDirsFunc &includeDirsCallback() const { return IncludeCallback; }
private:
/// Apply the filter to Multilibs and return the subset that remains
static multilib_list filterCopy(FilterCallback F, const multilib_list &Ms);
/// Apply the filter to the multilib_list, removing those that don't match
static void filterInPlace(FilterCallback F, multilib_list &Ms);
};
raw_ostream &operator<<(raw_ostream &OS, const MultilibSet &MS);
}
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/Action.h | //===--- Action.h - Abstract compilation steps ------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_DRIVER_ACTION_H
#define LLVM_CLANG_DRIVER_ACTION_H
#include "clang/Driver/Types.h"
#include "clang/Driver/Util.h"
#include "llvm/ADT/SmallVector.h"
namespace llvm {
namespace opt {
class Arg;
}
}
namespace clang {
namespace driver {
/// Action - Represent an abstract compilation step to perform.
///
/// An action represents an edge in the compilation graph; typically
/// it is a job to transform an input using some tool.
///
/// The current driver is hard wired to expect actions which produce a
/// single primary output, at least in terms of controlling the
/// compilation. Actions can produce auxiliary files, but can only
/// produce a single output to feed into subsequent actions.
class Action {
public:
typedef ActionList::size_type size_type;
typedef ActionList::iterator iterator;
typedef ActionList::const_iterator const_iterator;
enum ActionClass {
InputClass = 0,
BindArchClass,
CudaDeviceClass,
CudaHostClass,
PreprocessJobClass,
PrecompileJobClass,
AnalyzeJobClass,
MigrateJobClass,
CompileJobClass,
BackendJobClass,
AssembleJobClass,
LinkJobClass,
LipoJobClass,
DsymutilJobClass,
VerifyDebugInfoJobClass,
VerifyPCHJobClass,
JobClassFirst=PreprocessJobClass,
JobClassLast=VerifyPCHJobClass
};
static const char *getClassName(ActionClass AC);
private:
ActionClass Kind;
/// The output type of this action.
types::ID Type;
ActionList Inputs;
unsigned OwnsInputs : 1;
protected:
Action(ActionClass Kind, types::ID Type)
: Kind(Kind), Type(Type), OwnsInputs(true) {}
Action(ActionClass Kind, std::unique_ptr<Action> Input, types::ID Type)
: Kind(Kind), Type(Type), Inputs(1, Input.release()), OwnsInputs(true) {
}
Action(ActionClass Kind, std::unique_ptr<Action> Input)
: Kind(Kind), Type(Input->getType()), Inputs(1, Input.release()),
OwnsInputs(true) {}
Action(ActionClass Kind, const ActionList &Inputs, types::ID Type)
: Kind(Kind), Type(Type), Inputs(Inputs), OwnsInputs(true) {}
public:
virtual ~Action();
const char *getClassName() const { return Action::getClassName(getKind()); }
bool getOwnsInputs() { return OwnsInputs; }
void setOwnsInputs(bool Value) { OwnsInputs = Value; }
ActionClass getKind() const { return Kind; }
types::ID getType() const { return Type; }
ActionList &getInputs() { return Inputs; }
const ActionList &getInputs() const { return Inputs; }
size_type size() const { return Inputs.size(); }
iterator begin() { return Inputs.begin(); }
iterator end() { return Inputs.end(); }
const_iterator begin() const { return Inputs.begin(); }
const_iterator end() const { return Inputs.end(); }
};
class InputAction : public Action {
virtual void anchor();
const llvm::opt::Arg &Input;
public:
InputAction(const llvm::opt::Arg &Input, types::ID Type);
const llvm::opt::Arg &getInputArg() const { return Input; }
static bool classof(const Action *A) {
return A->getKind() == InputClass;
}
};
class BindArchAction : public Action {
virtual void anchor();
/// The architecture to bind, or 0 if the default architecture
/// should be bound.
const char *ArchName;
public:
BindArchAction(std::unique_ptr<Action> Input, const char *ArchName);
const char *getArchName() const { return ArchName; }
static bool classof(const Action *A) {
return A->getKind() == BindArchClass;
}
};
class CudaDeviceAction : public Action {
virtual void anchor();
/// GPU architecture to bind -- e.g 'sm_35'.
const char *GpuArchName;
/// True when action results are not consumed by the host action (e.g when
/// -fsyntax-only or --cuda-device-only options are used).
bool AtTopLevel;
public:
CudaDeviceAction(std::unique_ptr<Action> Input, const char *ArchName,
bool AtTopLevel);
const char *getGpuArchName() const { return GpuArchName; }
bool isAtTopLevel() const { return AtTopLevel; }
static bool classof(const Action *A) {
return A->getKind() == CudaDeviceClass;
}
};
class CudaHostAction : public Action {
virtual void anchor();
ActionList DeviceActions;
public:
CudaHostAction(std::unique_ptr<Action> Input,
const ActionList &DeviceActions);
~CudaHostAction() override;
ActionList &getDeviceActions() { return DeviceActions; }
const ActionList &getDeviceActions() const { return DeviceActions; }
static bool classof(const Action *A) { return A->getKind() == CudaHostClass; }
};
class JobAction : public Action {
virtual void anchor();
protected:
JobAction(ActionClass Kind, std::unique_ptr<Action> Input, types::ID Type);
JobAction(ActionClass Kind, const ActionList &Inputs, types::ID Type);
public:
static bool classof(const Action *A) {
return (A->getKind() >= JobClassFirst &&
A->getKind() <= JobClassLast);
}
};
class PreprocessJobAction : public JobAction {
void anchor() override;
public:
PreprocessJobAction(std::unique_ptr<Action> Input, types::ID OutputType);
static bool classof(const Action *A) {
return A->getKind() == PreprocessJobClass;
}
};
class PrecompileJobAction : public JobAction {
void anchor() override;
public:
PrecompileJobAction(std::unique_ptr<Action> Input, types::ID OutputType);
static bool classof(const Action *A) {
return A->getKind() == PrecompileJobClass;
}
};
class AnalyzeJobAction : public JobAction {
void anchor() override;
public:
AnalyzeJobAction(std::unique_ptr<Action> Input, types::ID OutputType);
static bool classof(const Action *A) {
return A->getKind() == AnalyzeJobClass;
}
};
class MigrateJobAction : public JobAction {
void anchor() override;
public:
MigrateJobAction(std::unique_ptr<Action> Input, types::ID OutputType);
static bool classof(const Action *A) {
return A->getKind() == MigrateJobClass;
}
};
class CompileJobAction : public JobAction {
void anchor() override;
public:
CompileJobAction(std::unique_ptr<Action> Input, types::ID OutputType);
static bool classof(const Action *A) {
return A->getKind() == CompileJobClass;
}
};
class BackendJobAction : public JobAction {
void anchor() override;
public:
BackendJobAction(std::unique_ptr<Action> Input, types::ID OutputType);
static bool classof(const Action *A) {
return A->getKind() == BackendJobClass;
}
};
class AssembleJobAction : public JobAction {
void anchor() override;
public:
AssembleJobAction(std::unique_ptr<Action> Input, types::ID OutputType);
static bool classof(const Action *A) {
return A->getKind() == AssembleJobClass;
}
};
class LinkJobAction : public JobAction {
void anchor() override;
public:
LinkJobAction(ActionList &Inputs, types::ID Type);
static bool classof(const Action *A) {
return A->getKind() == LinkJobClass;
}
};
class LipoJobAction : public JobAction {
void anchor() override;
public:
LipoJobAction(ActionList &Inputs, types::ID Type);
static bool classof(const Action *A) {
return A->getKind() == LipoJobClass;
}
};
class DsymutilJobAction : public JobAction {
void anchor() override;
public:
DsymutilJobAction(ActionList &Inputs, types::ID Type);
static bool classof(const Action *A) {
return A->getKind() == DsymutilJobClass;
}
};
class VerifyJobAction : public JobAction {
void anchor() override;
public:
VerifyJobAction(ActionClass Kind, std::unique_ptr<Action> Input,
types::ID Type);
VerifyJobAction(ActionClass Kind, ActionList &Inputs, types::ID Type);
static bool classof(const Action *A) {
return A->getKind() == VerifyDebugInfoJobClass ||
A->getKind() == VerifyPCHJobClass;
}
};
class VerifyDebugInfoJobAction : public VerifyJobAction {
void anchor() override;
public:
VerifyDebugInfoJobAction(std::unique_ptr<Action> Input, types::ID Type);
static bool classof(const Action *A) {
return A->getKind() == VerifyDebugInfoJobClass;
}
};
class VerifyPCHJobAction : public VerifyJobAction {
void anchor() override;
public:
VerifyPCHJobAction(std::unique_ptr<Action> Input, types::ID Type);
static bool classof(const Action *A) {
return A->getKind() == VerifyPCHJobClass;
}
};
} // end namespace driver
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/SanitizerArgs.h | //===--- SanitizerArgs.h - Arguments for sanitizer tools -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_DRIVER_SANITIZERARGS_H
#define LLVM_CLANG_DRIVER_SANITIZERARGS_H
#include "clang/Basic/Sanitizers.h"
#include "clang/Driver/Types.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include <string>
#include <vector>
namespace clang {
namespace driver {
class ToolChain;
class SanitizerArgs {
SanitizerSet Sanitizers;
SanitizerSet RecoverableSanitizers;
SanitizerSet TrapSanitizers;
std::vector<std::string> BlacklistFiles;
int CoverageFeatures;
int MsanTrackOrigins;
bool MsanUseAfterDtor;
int AsanFieldPadding;
bool AsanZeroBaseShadow;
bool AsanSharedRuntime;
bool LinkCXXRuntimes;
public:
/// Parses the sanitizer arguments from an argument list.
SanitizerArgs(const ToolChain &TC, const llvm::opt::ArgList &Args);
bool needsAsanRt() const { return Sanitizers.has(SanitizerKind::Address); }
bool needsSharedAsanRt() const { return AsanSharedRuntime; }
bool needsTsanRt() const { return Sanitizers.has(SanitizerKind::Thread); }
bool needsMsanRt() const { return Sanitizers.has(SanitizerKind::Memory); }
bool needsLsanRt() const {
return Sanitizers.has(SanitizerKind::Leak) &&
!Sanitizers.has(SanitizerKind::Address);
}
bool needsUbsanRt() const;
bool needsDfsanRt() const { return Sanitizers.has(SanitizerKind::DataFlow); }
bool needsSafeStackRt() const {
return Sanitizers.has(SanitizerKind::SafeStack);
}
bool requiresPIE() const;
bool needsUnwindTables() const;
bool linkCXXRuntimes() const { return LinkCXXRuntimes; }
void addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs, types::ID InputType) const;
private:
void clear();
};
} // namespace driver
} // namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/Driver.h | //===--- Driver.h - Clang GCC Compatible Driver -----------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_DRIVER_DRIVER_H
#define LLVM_CLANG_DRIVER_DRIVER_H
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/LLVM.h"
#include "clang/Driver/Phases.h"
#include "clang/Driver/Types.h"
#include "clang/Driver/Util.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/Path.h" // FIXME: Kill when CompilationInfo
#include <memory>
// lands.
#include <list>
#include <set>
#include <string>
namespace llvm {
namespace opt {
class Arg;
class ArgList;
class DerivedArgList;
class InputArgList;
class OptTable;
}
}
namespace clang {
namespace driver {
class Action;
class Command;
class Compilation;
class InputInfo;
class JobList;
class JobAction;
class SanitizerArgs;
class ToolChain;
/// Driver - Encapsulate logic for constructing compilation processes
/// from a set of gcc-driver-like command line arguments.
class Driver {
llvm::opt::OptTable *Opts;
DiagnosticsEngine &Diags;
enum DriverMode {
GCCMode,
GXXMode,
CPPMode,
CLMode
} Mode;
enum SaveTempsMode {
SaveTempsNone,
SaveTempsCwd,
SaveTempsObj
} SaveTemps;
public:
// Diag - Forwarding function for diagnostics.
DiagnosticBuilder Diag(unsigned DiagID) const {
return Diags.Report(DiagID);
}
// FIXME: Privatize once interface is stable.
public:
/// The name the driver was invoked as.
std::string Name;
/// The path the driver executable was in, as invoked from the
/// command line.
std::string Dir;
/// The original path to the clang executable.
std::string ClangExecutable;
/// The path to the installed clang directory, if any.
std::string InstalledDir;
/// The path to the compiler resource directory.
std::string ResourceDir;
/// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
/// functionality.
/// FIXME: This type of customization should be removed in favor of the
/// universal driver when it is ready.
typedef SmallVector<std::string, 4> prefix_list;
prefix_list PrefixDirs;
/// sysroot, if present
std::string SysRoot;
/// Dynamic loader prefix, if present
std::string DyldPrefix;
/// If the standard library is used
bool UseStdLib;
/// Default target triple.
std::string DefaultTargetTriple;
/// Driver title to use with help.
std::string DriverTitle;
/// Information about the host which can be overridden by the user.
std::string HostBits, HostMachine, HostSystem, HostRelease;
/// The file to log CC_PRINT_OPTIONS output to, if enabled.
const char *CCPrintOptionsFilename;
/// The file to log CC_PRINT_HEADERS output to, if enabled.
const char *CCPrintHeadersFilename;
/// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
const char *CCLogDiagnosticsFilename;
/// A list of inputs and their types for the given arguments.
typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16>
InputList;
/// Whether the driver should follow g++ like behavior.
bool CCCIsCXX() const { return Mode == GXXMode; }
/// Whether the driver is just the preprocessor.
bool CCCIsCPP() const { return Mode == CPPMode; }
/// Whether the driver should follow cl.exe like behavior.
bool IsCLMode() const { return Mode == CLMode; }
/// Only print tool bindings, don't build any jobs.
unsigned CCCPrintBindings : 1;
/// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
/// CCPrintOptionsFilename or to stderr.
unsigned CCPrintOptions : 1;
/// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
/// information to CCPrintHeadersFilename or to stderr.
unsigned CCPrintHeaders : 1;
/// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
/// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
/// format.
unsigned CCLogDiagnostics : 1;
/// Whether the driver is generating diagnostics for debugging purposes.
unsigned CCGenDiagnostics : 1;
private:
/// Name to use when invoking gcc/g++.
std::string CCCGenericGCCName;
/// Whether to check that input files exist when constructing compilation
/// jobs.
unsigned CheckInputsExist : 1;
public:
/// Use lazy precompiled headers for PCH support.
unsigned CCCUsePCH : 1;
private:
/// Certain options suppress the 'no input files' warning.
bool SuppressMissingInputWarning : 1;
std::list<std::string> TempFiles;
std::list<std::string> ResultFiles;
/// \brief Cache of all the ToolChains in use by the driver.
///
/// This maps from the string representation of a triple to a ToolChain
/// created targeting that triple. The driver owns all the ToolChain objects
/// stored in it, and will clean them up when torn down.
mutable llvm::StringMap<ToolChain *> ToolChains;
private:
/// TranslateInputArgs - Create a new derived argument list from the input
/// arguments, after applying the standard argument translations.
llvm::opt::DerivedArgList *
TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
// getFinalPhase - Determine which compilation mode we are in and record
// which option we used to determine the final phase.
phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
llvm::opt::Arg **FinalPhaseArg = nullptr) const;
// Before executing jobs, sets up response files for commands that need them.
void setUpResponseFiles(Compilation &C, Command &Cmd);
void generatePrefixedToolNames(const char *Tool, const ToolChain &TC,
SmallVectorImpl<std::string> &Names) const;
public:
Driver(StringRef _ClangExecutable,
StringRef _DefaultTargetTriple,
DiagnosticsEngine &_Diags);
~Driver();
/// @name Accessors
/// @{
/// Name to use when invoking gcc/g++.
const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
const llvm::opt::OptTable &getOpts() const { return *Opts; }
const DiagnosticsEngine &getDiags() const { return Diags; }
bool getCheckInputsExist() const { return CheckInputsExist; }
void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
const std::string &getTitle() { return DriverTitle; }
void setTitle(std::string Value) { DriverTitle = Value; }
/// \brief Get the path to the main clang executable.
const char *getClangProgramPath() const {
return ClangExecutable.c_str();
}
/// \brief Get the path to where the clang executable was installed.
const char *getInstalledDir() const {
if (!InstalledDir.empty())
return InstalledDir.c_str();
return Dir.c_str();
}
void setInstalledDir(StringRef Value) {
InstalledDir = Value;
}
bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
/// @}
/// @name Primary Functionality
/// @{
/// BuildCompilation - Construct a compilation object for a command
/// line argument vector.
///
/// \return A compilation, or 0 if none was built for the given
/// argument vector. A null return value does not necessarily
/// indicate an error condition, the diagnostics should be queried
/// to determine if an error occurred.
Compilation *BuildCompilation(ArrayRef<const char *> Args);
/// @name Driver Steps
/// @{
/// ParseDriverMode - Look for and handle the driver mode option in Args.
void ParseDriverMode(ArrayRef<const char *> Args);
/// ParseArgStrings - Parse the given list of strings into an
/// ArgList.
llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args);
/// BuildInputs - Construct the list of inputs and their types from
/// the given arguments.
///
/// \param TC - The default host tool chain.
/// \param Args - The input arguments.
/// \param Inputs - The list to store the resulting compilation
/// inputs onto.
void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
InputList &Inputs) const;
/// BuildActions - Construct the list of actions to perform for the
/// given arguments, which are only done for a single architecture.
///
/// \param TC - The default host tool chain.
/// \param Args - The input arguments.
/// \param Actions - The list to store the resulting actions onto.
void BuildActions(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
const InputList &Inputs, ActionList &Actions) const;
/// BuildUniversalActions - Construct the list of actions to perform
/// for the given arguments, which may require a universal build.
///
/// \param TC - The default host tool chain.
/// \param Args - The input arguments.
/// \param Actions - The list to store the resulting actions onto.
void BuildUniversalActions(const ToolChain &TC,
llvm::opt::DerivedArgList &Args,
const InputList &BAInputs,
ActionList &Actions) const;
/// BuildJobs - Bind actions to concrete tools and translate
/// arguments to form the list of jobs to run.
///
/// \param C - The compilation that is being built.
void BuildJobs(Compilation &C) const;
/// ExecuteCompilation - Execute the compilation according to the command line
/// arguments and return an appropriate exit code.
///
/// This routine handles additional processing that must be done in addition
/// to just running the subprocesses, for example reporting errors, setting
/// up response files, removing temporary files, etc.
int ExecuteCompilation(Compilation &C,
SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
/// generateCompilationDiagnostics - Generate diagnostics information
/// including preprocessed source file(s).
///
void generateCompilationDiagnostics(Compilation &C,
const Command &FailingCommand);
/// @}
/// @name Helper Methods
/// @{
/// PrintActions - Print the list of actions.
void PrintActions(const Compilation &C) const;
/// PrintHelp - Print the help text.
///
/// \param ShowHidden - Show hidden options.
void PrintHelp(bool ShowHidden) const;
/// PrintVersion - Print the driver version.
void PrintVersion(const Compilation &C, raw_ostream &OS) const;
/// GetFilePath - Lookup \p Name in the list of file search paths.
///
/// \param TC - The tool chain for additional information on
/// directories to search.
//
// FIXME: This should be in CompilationInfo.
std::string GetFilePath(const char *Name, const ToolChain &TC) const;
/// GetProgramPath - Lookup \p Name in the list of program search paths.
///
/// \param TC - The provided tool chain for additional information on
/// directories to search.
//
// FIXME: This should be in CompilationInfo.
std::string GetProgramPath(const char *Name, const ToolChain &TC) const;
/// HandleImmediateArgs - Handle any arguments which should be
/// treated before building actions or binding tools.
///
/// \return Whether any compilation should be built for this
/// invocation.
bool HandleImmediateArgs(const Compilation &C);
/// ConstructAction - Construct the appropriate action to do for
/// \p Phase on the \p Input, taking in to account arguments
/// like -fsyntax-only or --analyze.
std::unique_ptr<Action>
ConstructPhaseAction(const ToolChain &TC, const llvm::opt::ArgList &Args,
phases::ID Phase, std::unique_ptr<Action> Input) const;
/// BuildJobsForAction - Construct the jobs to perform for the
/// action \p A.
void BuildJobsForAction(Compilation &C,
const Action *A,
const ToolChain *TC,
const char *BoundArch,
bool AtTopLevel,
bool MultipleArchs,
const char *LinkingOutput,
InputInfo &Result) const;
/// Returns the default name for linked images (e.g., "a.out").
const char *getDefaultImageName() const;
/// GetNamedOutputPath - Return the name to use for the output of
/// the action \p JA. The result is appended to the compilation's
/// list of temporary or result files, as appropriate.
///
/// \param C - The compilation.
/// \param JA - The action of interest.
/// \param BaseInput - The original input file that this action was
/// triggered by.
/// \param BoundArch - The bound architecture.
/// \param AtTopLevel - Whether this is a "top-level" action.
/// \param MultipleArchs - Whether multiple -arch options were supplied.
const char *GetNamedOutputPath(Compilation &C,
const JobAction &JA,
const char *BaseInput,
const char *BoundArch,
bool AtTopLevel,
bool MultipleArchs) const;
/// GetTemporaryPath - Return the pathname of a temporary file to use
/// as part of compilation; the file will have the given prefix and suffix.
///
/// GCC goes to extra lengths here to be a bit more robust.
std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const;
/// ShouldUseClangCompiler - Should the clang compiler be used to
/// handle this action.
bool ShouldUseClangCompiler(const JobAction &JA) const;
bool IsUsingLTO(const llvm::opt::ArgList &Args) const;
private:
/// \brief Retrieves a ToolChain for a particular \p Target triple.
///
/// Will cache ToolChains for the life of the driver object, and create them
/// on-demand.
const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
const llvm::Triple &Target) const;
/// @}
/// \brief Get bitmasks for which option flags to include and exclude based on
/// the driver mode.
std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks() const;
public:
/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
/// return the grouped values as integers. Numbers which are not
/// provided are set to 0.
///
/// \return True if the entire string was parsed (9.2), or all
/// groups were parsed (10.3.5extrastuff). HadExtra is true if all
/// groups were parsed but extra characters remain at the end.
static bool GetReleaseVersion(const char *Str, unsigned &Major,
unsigned &Minor, unsigned &Micro,
bool &HadExtra);
};
/// \return True if the last defined optimization level is -Ofast.
/// And False otherwise.
bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
} // end namespace driver
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/ToolChain.h | //===--- ToolChain.h - Collections of tools for one platform ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_DRIVER_TOOLCHAIN_H
#define LLVM_CLANG_DRIVER_TOOLCHAIN_H
#include "clang/Basic/Sanitizers.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Multilib.h"
#include "clang/Driver/Types.h"
#include "clang/Driver/Util.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/Path.h"
#include <memory>
#include <string>
namespace llvm {
namespace opt {
class ArgList;
class DerivedArgList;
class InputArgList;
}
}
namespace clang {
class ObjCRuntime;
namespace driver {
class Compilation;
class Driver;
class JobAction;
class SanitizerArgs;
class Tool;
/// ToolChain - Access to tools for a single platform.
class ToolChain {
public:
typedef SmallVector<std::string, 16> path_list;
enum CXXStdlibType {
CST_Libcxx,
CST_Libstdcxx
};
enum RuntimeLibType {
RLT_CompilerRT,
RLT_Libgcc
};
enum RTTIMode {
RM_EnabledExplicitly,
RM_EnabledImplicitly,
RM_DisabledExplicitly,
RM_DisabledImplicitly
};
private:
const Driver &D;
const llvm::Triple Triple;
const llvm::opt::ArgList &Args;
// We need to initialize CachedRTTIArg before CachedRTTIMode
const llvm::opt::Arg *const CachedRTTIArg;
const RTTIMode CachedRTTIMode;
/// The list of toolchain specific path prefixes to search for
/// files.
path_list FilePaths;
/// The list of toolchain specific path prefixes to search for
/// programs.
path_list ProgramPaths;
mutable std::unique_ptr<Tool> Clang;
mutable std::unique_ptr<Tool> Assemble;
mutable std::unique_ptr<Tool> Link;
Tool *getClang() const;
Tool *getAssemble() const;
Tool *getLink() const;
Tool *getClangAs() const;
mutable std::unique_ptr<SanitizerArgs> SanitizerArguments;
protected:
MultilibSet Multilibs;
ToolChain(const Driver &D, const llvm::Triple &T,
const llvm::opt::ArgList &Args);
virtual Tool *buildAssembler() const;
virtual Tool *buildLinker() const;
virtual Tool *getTool(Action::ActionClass AC) const;
/// \name Utilities for implementing subclasses.
///@{
static void addSystemInclude(const llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args,
const Twine &Path);
static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args,
const Twine &Path);
static void
addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args,
const Twine &Path);
static void addSystemIncludes(const llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args,
ArrayRef<StringRef> Paths);
///@}
public:
virtual ~ToolChain();
// Accessors
const Driver &getDriver() const;
const llvm::Triple &getTriple() const { return Triple; }
llvm::Triple::ArchType getArch() const { return Triple.getArch(); }
StringRef getArchName() const { return Triple.getArchName(); }
StringRef getPlatform() const { return Triple.getVendorName(); }
StringRef getOS() const { return Triple.getOSName(); }
/// \brief Provide the default architecture name (as expected by -arch) for
/// this toolchain. Note t
StringRef getDefaultUniversalArchName() const;
std::string getTripleString() const {
return Triple.getTriple();
}
path_list &getFilePaths() { return FilePaths; }
const path_list &getFilePaths() const { return FilePaths; }
path_list &getProgramPaths() { return ProgramPaths; }
const path_list &getProgramPaths() const { return ProgramPaths; }
const MultilibSet &getMultilibs() const { return Multilibs; }
const SanitizerArgs& getSanitizerArgs() const;
// Returns the Arg * that explicitly turned on/off rtti, or nullptr.
const llvm::opt::Arg *getRTTIArg() const { return CachedRTTIArg; }
// Returns the RTTIMode for the toolchain with the current arguments.
RTTIMode getRTTIMode() const { return CachedRTTIMode; }
// Tool access.
/// TranslateArgs - Create a new derived argument list for any argument
/// translations this ToolChain may wish to perform, or 0 if no tool chain
/// specific translations are needed.
///
/// \param BoundArch - The bound architecture name, or 0.
virtual llvm::opt::DerivedArgList *
TranslateArgs(const llvm::opt::DerivedArgList &Args,
const char *BoundArch) const {
return nullptr;
}
/// Choose a tool to use to handle the action \p JA.
///
/// This can be overridden when a particular ToolChain needs to use
/// a C compiler other than Clang.
virtual Tool *SelectTool(const JobAction &JA) const;
// Helper methods
std::string GetFilePath(const char *Name) const;
std::string GetProgramPath(const char *Name) const;
/// Returns the linker path, respecting the -fuse-ld= argument to determine
/// the linker suffix or name.
std::string GetLinkerPath() const;
/// \brief Dispatch to the specific toolchain for verbose printing.
///
/// This is used when handling the verbose option to print detailed,
/// toolchain-specific information useful for understanding the behavior of
/// the driver on a specific platform.
virtual void printVerboseInfo(raw_ostream &OS) const {};
// Platform defaults information
/// \brief Returns true if the toolchain is targeting a non-native
/// architecture.
virtual bool isCrossCompiling() const;
/// HasNativeLTOLinker - Check whether the linker and related tools have
/// native LLVM support.
virtual bool HasNativeLLVMSupport() const;
/// LookupTypeForExtension - Return the default language type to use for the
/// given extension.
virtual types::ID LookupTypeForExtension(const char *Ext) const;
/// IsBlocksDefault - Does this tool chain enable -fblocks by default.
virtual bool IsBlocksDefault() const { return false; }
/// IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as
/// by default.
virtual bool IsIntegratedAssemblerDefault() const { return false; }
/// \brief Check if the toolchain should use the integrated assembler.
bool useIntegratedAs() const;
/// IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
virtual bool IsMathErrnoDefault() const { return true; }
/// IsEncodeExtendedBlockSignatureDefault - Does this tool chain enable
/// -fencode-extended-block-signature by default.
virtual bool IsEncodeExtendedBlockSignatureDefault() const { return false; }
/// IsObjCNonFragileABIDefault - Does this tool chain set
/// -fobjc-nonfragile-abi by default.
virtual bool IsObjCNonFragileABIDefault() const { return false; }
/// UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the
/// mixed dispatch method be used?
virtual bool UseObjCMixedDispatch() const { return false; }
/// GetDefaultStackProtectorLevel - Get the default stack protector level for
/// this tool chain (0=off, 1=on, 2=strong, 3=all).
virtual unsigned GetDefaultStackProtectorLevel(bool KernelOrKext) const {
return 0;
}
/// GetDefaultRuntimeLibType - Get the default runtime library variant to use.
virtual RuntimeLibType GetDefaultRuntimeLibType() const {
return ToolChain::RLT_Libgcc;
}
/// IsUnwindTablesDefault - Does this tool chain use -funwind-tables
/// by default.
virtual bool IsUnwindTablesDefault() const;
/// \brief Test whether this toolchain defaults to PIC.
virtual bool isPICDefault() const = 0;
/// \brief Test whether this toolchain defaults to PIE.
virtual bool isPIEDefault() const = 0;
/// \brief Tests whether this toolchain forces its default for PIC, PIE or
/// non-PIC. If this returns true, any PIC related flags should be ignored
/// and instead the results of \c isPICDefault() and \c isPIEDefault() are
/// used exclusively.
virtual bool isPICDefaultForced() const = 0;
/// SupportsProfiling - Does this tool chain support -pg.
virtual bool SupportsProfiling() const { return true; }
/// Does this tool chain support Objective-C garbage collection.
virtual bool SupportsObjCGC() const { return true; }
/// Complain if this tool chain doesn't support Objective-C ARC.
virtual void CheckObjCARC() const {}
/// UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf
/// compile unit information.
virtual bool UseDwarfDebugFlags() const { return false; }
/// UseSjLjExceptions - Does this tool chain use SjLj exceptions.
virtual bool UseSjLjExceptions() const { return false; }
/// getThreadModel() - Which thread model does this target use?
virtual std::string getThreadModel() const { return "posix"; }
/// isThreadModelSupported() - Does this target support a thread model?
virtual bool isThreadModelSupported(const StringRef Model) const;
/// ComputeLLVMTriple - Return the LLVM target triple to use, after taking
/// command line arguments into account.
virtual std::string
ComputeLLVMTriple(const llvm::opt::ArgList &Args,
types::ID InputType = types::TY_INVALID) const;
/// ComputeEffectiveClangTriple - Return the Clang triple to use for this
/// target, which may take into account the command line arguments. For
/// example, on Darwin the -mmacosx-version-min= command line argument (which
/// sets the deployment target) determines the version in the triple passed to
/// Clang.
virtual std::string ComputeEffectiveClangTriple(
const llvm::opt::ArgList &Args,
types::ID InputType = types::TY_INVALID) const;
/// getDefaultObjCRuntime - Return the default Objective-C runtime
/// for this platform.
///
/// FIXME: this really belongs on some sort of DeploymentTarget abstraction
virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const;
/// hasBlocksRuntime - Given that the user is compiling with
/// -fblocks, does this tool chain guarantee the existence of a
/// blocks runtime?
///
/// FIXME: this really belongs on some sort of DeploymentTarget abstraction
virtual bool hasBlocksRuntime() const { return true; }
/// \brief Add the clang cc1 arguments for system include paths.
///
/// This routine is responsible for adding the necessary cc1 arguments to
/// include headers from standard system header directories.
virtual void
AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args) const;
/// \brief Add options that need to be passed to cc1 for this target.
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args) const;
/// \brief Add warning options that need to be passed to cc1 for this target.
virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const;
// GetRuntimeLibType - Determine the runtime library type to use with the
// given compilation arguments.
virtual RuntimeLibType
GetRuntimeLibType(const llvm::opt::ArgList &Args) const;
// GetCXXStdlibType - Determine the C++ standard library type to use with the
// given compilation arguments.
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const;
/// AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set
/// the include paths to use for the given C++ standard library type.
virtual void
AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
llvm::opt::ArgStringList &CC1Args) const;
/// AddCXXStdlibLibArgs - Add the system specific linker arguments to use
/// for the given C++ standard library type.
virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs) const;
/// AddCCKextLibArgs - Add the system specific linker arguments to use
/// for kernel extensions (Darwin-specific).
virtual void AddCCKextLibArgs(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs) const;
/// AddFastMathRuntimeIfAvailable - If a runtime library exists that sets
/// global flags for unsafe floating point math, add it and return true.
///
/// This checks for presence of the -Ofast, -ffast-math or -funsafe-math flags.
virtual bool
AddFastMathRuntimeIfAvailable(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs) const;
/// \brief Return sanitizers which are available in this toolchain.
virtual SanitizerMask getSupportedSanitizers() const;
};
} // end namespace driver
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/Options.h | //===--- Options.h - Option info & table ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_DRIVER_OPTIONS_H
#define LLVM_CLANG_DRIVER_OPTIONS_H
namespace llvm {
namespace opt {
class OptTable;
}
}
namespace clang {
namespace driver {
namespace options {
/// Flags specifically for clang options. Must not overlap with
/// llvm::opt::DriverFlag.
enum ClangFlags {
DriverOption = (1 << 4),
LinkerInput = (1 << 5),
NoArgumentUnused = (1 << 6),
Unsupported = (1 << 7),
CoreOption = (1 << 8),
CLOption = (1 << 9),
CC1Option = (1 << 10),
CC1AsOption = (1 << 11),
NoDriverOption = (1 << 12)
};
enum ID {
OPT_INVALID = 0, // This is not an option ID.
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR) OPT_##ID,
#include "clang/Driver/Options.inc"
LastOption
#undef OPTION
};
}
llvm::opt::OptTable *createDriverOptTable();
}
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/Phases.h | //===--- Phases.h - Transformations on Driver Types -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_DRIVER_PHASES_H
#define LLVM_CLANG_DRIVER_PHASES_H
namespace clang {
namespace driver {
namespace phases {
/// ID - Ordered values for successive stages in the
/// compilation process which interact with user options.
enum ID {
Preprocess,
Precompile,
Compile,
Backend,
Assemble,
Link
};
enum {
MaxNumberOfPhases = Link + 1
};
const char *getPhaseName(ID Id);
} // end namespace phases
} // end namespace driver
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/DriverDiagnostic.h | //===--- DiagnosticDriver.h - Diagnostics for libdriver ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_DRIVER_DRIVERDIAGNOSTIC_H
#define LLVM_CLANG_DRIVER_DRIVERDIAGNOSTIC_H
#include "clang/Basic/Diagnostic.h"
namespace clang {
namespace diag {
enum {
#define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\
SFINAE,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM,
#define DRIVERSTART
#include "clang/Basic/DiagnosticDriverKinds.inc"
#undef DIAG
NUM_BUILTIN_DRIVER_DIAGNOSTICS
};
} // end namespace diag
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/Compilation.h | //===--- Compilation.h - Compilation Task Data Structure --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_DRIVER_COMPILATION_H
#define LLVM_CLANG_DRIVER_COMPILATION_H
#include "clang/Driver/Job.h"
#include "clang/Driver/Util.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/Path.h"
namespace llvm {
namespace opt {
class DerivedArgList;
class InputArgList;
}
}
namespace clang {
namespace driver {
class Driver;
class JobAction;
class JobList;
class ToolChain;
/// Compilation - A set of tasks to perform for a single driver
/// invocation.
class Compilation {
/// The driver we were created by.
const Driver &TheDriver;
/// The default tool chain.
const ToolChain &DefaultToolChain;
/// The original (untranslated) input argument list.
llvm::opt::InputArgList *Args;
/// The driver translated arguments. Note that toolchains may perform their
/// own argument translation.
llvm::opt::DerivedArgList *TranslatedArgs;
/// The list of actions.
ActionList Actions;
/// The root list of jobs.
JobList Jobs;
/// Cache of translated arguments for a particular tool chain and bound
/// architecture.
llvm::DenseMap<std::pair<const ToolChain *, const char *>,
llvm::opt::DerivedArgList *> TCArgs;
/// Temporary files which should be removed on exit.
llvm::opt::ArgStringList TempFiles;
/// Result files which should be removed on failure.
ArgStringMap ResultFiles;
/// Result files which are generated correctly on failure, and which should
/// only be removed if we crash.
ArgStringMap FailureResultFiles;
/// Redirection for stdout, stderr, etc.
const StringRef **Redirects;
/// Whether we're compiling for diagnostic purposes.
bool ForDiagnostics;
public:
Compilation(const Driver &D, const ToolChain &DefaultToolChain,
llvm::opt::InputArgList *Args,
llvm::opt::DerivedArgList *TranslatedArgs);
~Compilation();
const Driver &getDriver() const { return TheDriver; }
const ToolChain &getDefaultToolChain() const { return DefaultToolChain; }
const llvm::opt::InputArgList &getInputArgs() const { return *Args; }
const llvm::opt::DerivedArgList &getArgs() const { return *TranslatedArgs; }
llvm::opt::DerivedArgList &getArgs() { return *TranslatedArgs; }
ActionList &getActions() { return Actions; }
const ActionList &getActions() const { return Actions; }
JobList &getJobs() { return Jobs; }
const JobList &getJobs() const { return Jobs; }
void addCommand(std::unique_ptr<Command> C) { Jobs.addJob(std::move(C)); }
const llvm::opt::ArgStringList &getTempFiles() const { return TempFiles; }
const ArgStringMap &getResultFiles() const { return ResultFiles; }
const ArgStringMap &getFailureResultFiles() const {
return FailureResultFiles;
}
/// Returns the sysroot path.
StringRef getSysRoot() const;
/// getArgsForToolChain - Return the derived argument list for the
/// tool chain \p TC (or the default tool chain, if TC is not specified).
///
/// \param BoundArch - The bound architecture name, or 0.
const llvm::opt::DerivedArgList &getArgsForToolChain(const ToolChain *TC,
const char *BoundArch);
/// addTempFile - Add a file to remove on exit, and returns its
/// argument.
const char *addTempFile(const char *Name) {
TempFiles.push_back(Name);
return Name;
}
/// addResultFile - Add a file to remove on failure, and returns its
/// argument.
const char *addResultFile(const char *Name, const JobAction *JA) {
ResultFiles[JA] = Name;
return Name;
}
/// addFailureResultFile - Add a file to remove if we crash, and returns its
/// argument.
const char *addFailureResultFile(const char *Name, const JobAction *JA) {
FailureResultFiles[JA] = Name;
return Name;
}
/// CleanupFile - Delete a given file.
///
/// \param IssueErrors - Report failures as errors.
/// \return Whether the file was removed successfully.
bool CleanupFile(const char *File, bool IssueErrors = false) const;
/// CleanupFileList - Remove the files in the given list.
///
/// \param IssueErrors - Report failures as errors.
/// \return Whether all files were removed successfully.
bool CleanupFileList(const llvm::opt::ArgStringList &Files,
bool IssueErrors = false) const;
/// CleanupFileMap - Remove the files in the given map.
///
/// \param JA - If specified, only delete the files associated with this
/// JobAction. Otherwise, delete all files in the map.
/// \param IssueErrors - Report failures as errors.
/// \return Whether all files were removed successfully.
bool CleanupFileMap(const ArgStringMap &Files,
const JobAction *JA,
bool IssueErrors = false) const;
/// ExecuteCommand - Execute an actual command.
///
/// \param FailingCommand - For non-zero results, this will be set to the
/// Command which failed, if any.
/// \return The result code of the subprocess.
int ExecuteCommand(const Command &C, const Command *&FailingCommand) const;
/// ExecuteJob - Execute a single job.
///
/// \param FailingCommands - For non-zero results, this will be a vector of
/// failing commands and their associated result code.
void ExecuteJobs(
const JobList &Jobs,
SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) const;
/// initCompilationForDiagnostics - Remove stale state and suppress output
/// so compilation can be reexecuted to generate additional diagnostic
/// information (e.g., preprocessed source(s)).
void initCompilationForDiagnostics();
/// Return true if we're compiling for diagnostics.
bool isForDiagnostics() { return ForDiagnostics; }
};
} // end namespace driver
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/Types.h | //===--- Types.h - Input & Temporary Driver Types ---------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_DRIVER_TYPES_H
#define LLVM_CLANG_DRIVER_TYPES_H
#include "clang/Driver/Phases.h"
#include "llvm/ADT/SmallVector.h"
namespace clang {
namespace driver {
namespace types {
enum ID {
TY_INVALID,
#define TYPE(NAME, ID, PP_TYPE, TEMP_SUFFIX, FLAGS) TY_##ID,
#include "clang/Driver/Types.def"
#undef TYPE
TY_LAST
};
/// getTypeName - Return the name of the type for \p Id.
const char *getTypeName(ID Id);
/// getPreprocessedType - Get the ID of the type for this input when
/// it has been preprocessed, or INVALID if this input is not
/// preprocessed.
ID getPreprocessedType(ID Id);
/// getTypeTempSuffix - Return the suffix to use when creating a
/// temp file of this type, or null if unspecified.
const char *getTypeTempSuffix(ID Id, bool CLMode = false);
/// onlyAssembleType - Should this type only be assembled.
bool onlyAssembleType(ID Id);
/// onlyPrecompileType - Should this type only be precompiled.
bool onlyPrecompileType(ID Id);
/// canTypeBeUserSpecified - Can this type be specified on the
/// command line (by the type name); this is used when forwarding
/// commands to gcc.
bool canTypeBeUserSpecified(ID Id);
/// appendSuffixForType - When generating outputs of this type,
/// should the suffix be appended (instead of replacing the existing
/// suffix).
bool appendSuffixForType(ID Id);
/// canLipoType - Is this type acceptable as the output of a
/// universal build (currently, just the Nothing, Image, and Object
/// types).
bool canLipoType(ID Id);
/// isAcceptedByClang - Can clang handle this input type.
bool isAcceptedByClang(ID Id);
/// isCXX - Is this a "C++" input (C++ and Obj-C++ sources and headers).
bool isCXX(ID Id);
/// isCuda - Is this a CUDA input.
bool isCuda(ID Id);
/// isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
bool isObjC(ID Id);
/// lookupTypeForExtension - Lookup the type to use for the file
/// extension \p Ext.
ID lookupTypeForExtension(const char *Ext);
/// lookupTypeForTypSpecifier - Lookup the type to use for a user
/// specified type name.
ID lookupTypeForTypeSpecifier(const char *Name);
/// getCompilationPhases - Get the list of compilation phases ('Phases') to be
/// done for type 'Id'.
void getCompilationPhases(
ID Id,
llvm::SmallVectorImpl<phases::ID> &Phases);
/// lookupCXXTypeForCType - Lookup CXX input type that corresponds to given
/// C type (used for clang++ emulation of g++ behaviour)
ID lookupCXXTypeForCType(ID Id);
} // end namespace types
} // end namespace driver
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/CMakeLists.txt | set(LLVM_TARGET_DEFINITIONS Options.td)
tablegen(LLVM Options.inc -gen-opt-parser-defs)
add_public_tablegen_target(ClangDriverOptions)
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/Tool.h | //===--- Tool.h - Compilation Tools -----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_DRIVER_TOOL_H
#define LLVM_CLANG_DRIVER_TOOL_H
#include "clang/Basic/LLVM.h"
#include "llvm/Support/Program.h"
namespace llvm {
namespace opt {
class ArgList;
}
}
namespace clang {
namespace driver {
class Compilation;
class InputInfo;
class Job;
class JobAction;
class ToolChain;
typedef SmallVector<InputInfo, 4> InputInfoList;
/// Tool - Information on a specific compilation tool.
class Tool {
public:
// Documents the level of support for response files in this tool.
// Response files are necessary if the command line gets too large,
// requiring the arguments to be transfered to a file.
enum ResponseFileSupport {
// Provides full support for response files, which means we can transfer
// all tool input arguments to a file. E.g.: clang, gcc, binutils and MSVC
// tools.
RF_Full,
// Input file names can live in a file, but flags can't. E.g.: ld64 (Mac
// OS X linker).
RF_FileList,
// Does not support response files: all arguments must be passed via
// command line.
RF_None
};
private:
/// The tool name (for debugging).
const char *Name;
/// The human readable name for the tool, for use in diagnostics.
const char *ShortName;
/// The tool chain this tool is a part of.
const ToolChain &TheToolChain;
/// The level of support for response files seen in this tool
const ResponseFileSupport ResponseSupport;
/// The encoding to use when writing response files for this tool on Windows
const llvm::sys::WindowsEncodingMethod ResponseEncoding;
/// The flag used to pass a response file via command line to this tool
const char *const ResponseFlag;
public:
Tool(const char *Name, const char *ShortName, const ToolChain &TC,
ResponseFileSupport ResponseSupport = RF_None,
llvm::sys::WindowsEncodingMethod ResponseEncoding = llvm::sys::WEM_UTF8,
const char *ResponseFlag = "@");
public:
virtual ~Tool();
const char *getName() const { return Name; }
const char *getShortName() const { return ShortName; }
const ToolChain &getToolChain() const { return TheToolChain; }
virtual bool hasIntegratedAssembler() const { return false; }
virtual bool canEmitIR() const { return false; }
virtual bool hasIntegratedCPP() const = 0;
virtual bool isLinkJob() const { return false; }
virtual bool isDsymutilJob() const { return false; }
/// \brief Returns the level of support for response files of this tool,
/// whether it accepts arguments to be passed via a file on disk.
ResponseFileSupport getResponseFilesSupport() const {
return ResponseSupport;
}
/// \brief Returns which encoding the response file should use. This is only
/// relevant on Windows platforms where there are different encodings being
/// accepted for different tools. On UNIX, UTF8 is universal.
///
/// Windows use cases: - GCC and Binutils on mingw only accept ANSI response
/// files encoded with the system current code page.
/// - MSVC's CL.exe and LINK.exe accept UTF16 on Windows.
/// - Clang accepts both UTF8 and UTF16.
///
/// FIXME: When GNU tools learn how to parse UTF16 on Windows, we should
/// always use UTF16 for Windows, which is the Windows official encoding for
/// international characters.
llvm::sys::WindowsEncodingMethod getResponseFileEncoding() const {
return ResponseEncoding;
}
/// \brief Returns which prefix to use when passing the name of a response
/// file as a parameter to this tool.
const char *getResponseFileFlag() const { return ResponseFlag; }
/// \brief Does this tool have "good" standardized diagnostics, or should the
/// driver add an additional "command failed" diagnostic on failures.
virtual bool hasGoodDiagnostics() const { return false; }
/// ConstructJob - Construct jobs to perform the action \p JA,
/// writing to \p Output and with \p Inputs, and add the jobs to
/// \p C.
///
/// \param TCArgs - The argument list for this toolchain, with any
/// tool chain specific translations applied.
/// \param LinkingOutput - If this output will eventually feed the
/// linker, then this is the final output name of the linked image.
virtual void ConstructJob(Compilation &C, const JobAction &JA,
const InputInfo &Output,
const InputInfoList &Inputs,
const llvm::opt::ArgList &TCArgs,
const char *LinkingOutput) const = 0;
};
} // end namespace driver
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/Types.def | //===--- Types.def - Driver Type info ---------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the driver type information. Users of this file
// must define the TYPE macro to make use of this information.
//
//===----------------------------------------------------------------------===//
#ifndef TYPE
#error "Define TYPE prior to including this file!"
#endif
// TYPE(NAME, ID, PP_TYPE, TEMP_SUFFIX, FLAGS)
// The first value is the type name as a string; for types which can
// be user specified this should be the equivalent -x option.
// The second value is the type id, which will result in a
// clang::driver::types::TY_XX enum constant.
// The third value is that id of the type for preprocessed inputs of
// this type, or INVALID if this type is not preprocessed.
// The fourth value is the suffix to use when creating temporary files
// of this type, or null if unspecified.
// The fifth value is a string containing option flags. Valid values:
// a - The type should only be assembled.
// p - The type should only be precompiled.
// u - The type can be user specified (with -x).
// A - The type's temporary suffix should be appended when generating
// outputs of this type.
// C family source language (with and without preprocessing).
TYPE("cpp-output", PP_C, INVALID, "i", "u")
TYPE("c", C, PP_C, "c", "u")
TYPE("cl", CL, PP_C, "cl", "u")
TYPE("cuda-cpp-output", PP_CUDA, INVALID, "cui", "u")
TYPE("cuda", CUDA, PP_CUDA, "cu", "u")
TYPE("cuda", CUDA_DEVICE, PP_CUDA, "cu", "")
TYPE("objective-c-cpp-output", PP_ObjC, INVALID, "mi", "u")
TYPE("objc-cpp-output", PP_ObjC_Alias, INVALID, "mi", "u")
TYPE("objective-c", ObjC, PP_ObjC, "m", "u")
TYPE("c++-cpp-output", PP_CXX, INVALID, "ii", "u")
TYPE("c++", CXX, PP_CXX, "cpp", "u")
TYPE("objective-c++-cpp-output", PP_ObjCXX, INVALID, "mii", "u")
TYPE("objc++-cpp-output", PP_ObjCXX_Alias, INVALID, "mii", "u")
TYPE("objective-c++", ObjCXX, PP_ObjCXX, "mm", "u")
// C family input files to precompile.
TYPE("c-header-cpp-output", PP_CHeader, INVALID, "i", "p")
TYPE("c-header", CHeader, PP_CHeader, "h", "pu")
TYPE("cl-header", CLHeader, PP_CHeader, "h", "pu")
TYPE("objective-c-header-cpp-output", PP_ObjCHeader, INVALID, "mi", "p")
TYPE("objective-c-header", ObjCHeader, PP_ObjCHeader, "h", "pu")
TYPE("c++-header-cpp-output", PP_CXXHeader, INVALID, "ii", "p")
TYPE("c++-header", CXXHeader, PP_CXXHeader, "hh", "pu")
TYPE("objective-c++-header-cpp-output", PP_ObjCXXHeader, INVALID, "mii", "p")
TYPE("objective-c++-header", ObjCXXHeader, PP_ObjCXXHeader, "h", "pu")
// Other languages.
TYPE("ada", Ada, INVALID, nullptr, "u")
TYPE("assembler", PP_Asm, INVALID, "s", "au")
TYPE("assembler-with-cpp", Asm, PP_Asm, "S", "au")
TYPE("f95", PP_Fortran, INVALID, nullptr, "u")
TYPE("f95-cpp-input", Fortran, PP_Fortran, nullptr, "u")
TYPE("java", Java, INVALID, nullptr, "u")
TYPE("hlsl", HLSL, PP_CXX, "hlsl", "u")
// LLVM IR/LTO types. We define separate types for IR and LTO because LTO
// outputs should use the standard suffixes.
TYPE("ir", LLVM_IR, INVALID, "ll", "u")
TYPE("ir", LLVM_BC, INVALID, "bc", "u")
TYPE("lto-ir", LTO_IR, INVALID, "s", "")
TYPE("lto-bc", LTO_BC, INVALID, "o", "")
// Misc.
TYPE("ast", AST, INVALID, "ast", "u")
TYPE("pcm", ModuleFile, INVALID, "pcm", "u")
TYPE("plist", Plist, INVALID, "plist", "")
TYPE("rewritten-objc", RewrittenObjC,INVALID, "cpp", "")
TYPE("rewritten-legacy-objc", RewrittenLegacyObjC,INVALID, "cpp", "")
TYPE("remap", Remap, INVALID, "remap", "")
TYPE("precompiled-header", PCH, INVALID, "gch", "A")
TYPE("object", Object, INVALID, "o", "")
TYPE("treelang", Treelang, INVALID, nullptr, "u")
TYPE("image", Image, INVALID, "out", "")
TYPE("dSYM", dSYM, INVALID, "dSYM", "A")
TYPE("dependencies", Dependencies, INVALID, "d", "")
TYPE("none", Nothing, INVALID, nullptr, "u")
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/Job.h | //===--- Job.h - Commands to Execute ----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_DRIVER_JOB_H
#define LLVM_CLANG_DRIVER_JOB_H
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/iterator.h"
#include "llvm/Option/Option.h"
#include <memory>
namespace llvm {
class raw_ostream;
}
namespace clang {
namespace driver {
class Action;
class Command;
class Tool;
// Re-export this as clang::driver::ArgStringList.
using llvm::opt::ArgStringList;
struct CrashReportInfo {
StringRef Filename;
StringRef VFSPath;
CrashReportInfo(StringRef Filename, StringRef VFSPath)
: Filename(Filename), VFSPath(VFSPath) {}
};
/// Command - An executable path/name and argument vector to
/// execute.
class Command {
/// Source - The action which caused the creation of this job.
const Action &Source;
/// Tool - The tool which caused the creation of this job.
const Tool &Creator;
/// The executable to run.
const char *Executable;
/// The list of program arguments (not including the implicit first
/// argument, which will be the executable).
llvm::opt::ArgStringList Arguments;
/// Response file name, if this command is set to use one, or nullptr
/// otherwise
const char *ResponseFile;
/// The input file list in case we need to emit a file list instead of a
/// proper response file
llvm::opt::ArgStringList InputFileList;
/// String storage if we need to create a new argument to specify a response
/// file
std::string ResponseFileFlag;
/// When a response file is needed, we try to put most arguments in an
/// exclusive file, while others remains as regular command line arguments.
/// This functions fills a vector with the regular command line arguments,
/// argv, excluding the ones passed in a response file.
void buildArgvForResponseFile(llvm::SmallVectorImpl<const char *> &Out) const;
/// Encodes an array of C strings into a single string separated by whitespace.
/// This function will also put in quotes arguments that have whitespaces and
/// will escape the regular backslashes (used in Windows paths) and quotes.
/// The results are the contents of a response file, written into a raw_ostream.
void writeResponseFile(raw_ostream &OS) const;
public:
Command(const Action &Source, const Tool &Creator, const char *Executable,
const llvm::opt::ArgStringList &Arguments);
virtual ~Command() {}
virtual void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote,
CrashReportInfo *CrashInfo = nullptr) const;
virtual int Execute(const StringRef **Redirects, std::string *ErrMsg,
bool *ExecutionFailed) const;
/// getSource - Return the Action which caused the creation of this job.
const Action &getSource() const { return Source; }
/// getCreator - Return the Tool which caused the creation of this job.
const Tool &getCreator() const { return Creator; }
/// Set to pass arguments via a response file when launching the command
void setResponseFile(const char *FileName);
/// Set an input file list, necessary if we need to use a response file but
/// the tool being called only supports input files lists.
void setInputFileList(llvm::opt::ArgStringList List) {
InputFileList = std::move(List);
}
const char *getExecutable() const { return Executable; }
const llvm::opt::ArgStringList &getArguments() const { return Arguments; }
/// Print a command argument, and optionally quote it.
static void printArg(llvm::raw_ostream &OS, const char *Arg, bool Quote);
};
/// Like Command, but with a fallback which is executed in case
/// the primary command crashes.
class FallbackCommand : public Command {
public:
FallbackCommand(const Action &Source_, const Tool &Creator_,
const char *Executable_, const ArgStringList &Arguments_,
std::unique_ptr<Command> Fallback_);
void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote,
CrashReportInfo *CrashInfo = nullptr) const override;
int Execute(const StringRef **Redirects, std::string *ErrMsg,
bool *ExecutionFailed) const override;
private:
std::unique_ptr<Command> Fallback;
};
/// JobList - A sequence of jobs to perform.
class JobList {
public:
typedef SmallVector<std::unique_ptr<Command>, 4> list_type;
typedef list_type::size_type size_type;
typedef llvm::pointee_iterator<list_type::iterator> iterator;
typedef llvm::pointee_iterator<list_type::const_iterator> const_iterator;
private:
list_type Jobs;
public:
void Print(llvm::raw_ostream &OS, const char *Terminator,
bool Quote, CrashReportInfo *CrashInfo = nullptr) const;
/// Add a job to the list (taking ownership).
void addJob(std::unique_ptr<Command> J) { Jobs.push_back(std::move(J)); }
/// Clear the job list.
void clear();
const list_type &getJobs() const { return Jobs; }
size_type size() const { return Jobs.size(); }
iterator begin() { return Jobs.begin(); }
const_iterator begin() const { return Jobs.begin(); }
iterator end() { return Jobs.end(); }
const_iterator end() const { return Jobs.end(); }
};
} // end namespace driver
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Driver/Util.h | //===--- Util.h - Common Driver Utilities -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_DRIVER_UTIL_H
#define LLVM_CLANG_DRIVER_UTIL_H
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/DenseMap.h"
namespace clang {
class DiagnosticsEngine;
namespace driver {
class Action;
class JobAction;
/// ArgStringMap - Type used to map a JobAction to its result file.
typedef llvm::DenseMap<const JobAction*, const char*> ArgStringMap;
/// ActionList - Type used for lists of actions.
typedef SmallVector<Action*, 3> ActionList;
} // end namespace driver
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Frontend/MultiplexConsumer.h | //===-- MultiplexConsumer.h - AST Consumer for PCH Generation ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares the MultiplexConsumer class, which can be used to
// multiplex ASTConsumer and SemaConsumer messages to many consumers.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_FRONTEND_MULTIPLEXCONSUMER_H
#define LLVM_CLANG_FRONTEND_MULTIPLEXCONSUMER_H
#include "clang/Basic/LLVM.h"
#include "clang/Sema/SemaConsumer.h"
#include <memory>
#include <vector>
namespace clang {
class MultiplexASTMutationListener;
class MultiplexASTDeserializationListener;
// Has a list of ASTConsumers and calls each of them. Owns its children.
class MultiplexConsumer : public SemaConsumer {
public:
// Takes ownership of the pointers in C.
MultiplexConsumer(std::vector<std::unique_ptr<ASTConsumer>> C);
~MultiplexConsumer() override;
// ASTConsumer
void Initialize(ASTContext &Context) override;
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override;
bool HandleTopLevelDecl(DeclGroupRef D) override;
void HandleInlineMethodDefinition(CXXMethodDecl *D) override;
void HandleInterestingDecl(DeclGroupRef D) override;
void HandleTranslationUnit(ASTContext &Ctx) override;
void HandleTagDeclDefinition(TagDecl *D) override;
void HandleTagDeclRequiredDefinition(const TagDecl *D) override;
void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) override;
void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
void HandleImplicitImportDecl(ImportDecl *D) override;
void HandleLinkerOptionPragma(llvm::StringRef Opts) override;
void HandleDetectMismatch(llvm::StringRef Name,
llvm::StringRef Value) override;
void HandleDependentLibrary(llvm::StringRef Lib) override;
void CompleteTentativeDefinition(VarDecl *D) override;
void HandleVTable(CXXRecordDecl *RD) override;
ASTMutationListener *GetASTMutationListener() override;
ASTDeserializationListener *GetASTDeserializationListener() override;
void PrintStats() override;
// SemaConsumer
void InitializeSema(Sema &S) override;
void ForgetSema() override;
private:
std::vector<std::unique_ptr<ASTConsumer>> Consumers; // Owns these.
std::unique_ptr<MultiplexASTMutationListener> MutationListener;
// std::unique_ptr<MultiplexASTDeserializationListener> DeserializationListener; // HLSL Change - no support for serialization
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Frontend/ChainedDiagnosticConsumer.h | //===- ChainedDiagnosticConsumer.h - Chain Diagnostic Clients ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_FRONTEND_CHAINEDDIAGNOSTICCONSUMER_H
#define LLVM_CLANG_FRONTEND_CHAINEDDIAGNOSTICCONSUMER_H
#include "clang/Basic/Diagnostic.h"
#include <memory>
namespace clang {
class LangOptions;
/// ChainedDiagnosticConsumer - Chain two diagnostic clients so that diagnostics
/// go to the first client and then the second. The first diagnostic client
/// should be the "primary" client, and will be used for computing whether the
/// diagnostics should be included in counts.
class ChainedDiagnosticConsumer : public DiagnosticConsumer {
virtual void anchor();
std::unique_ptr<DiagnosticConsumer> OwningPrimary;
DiagnosticConsumer *Primary;
std::unique_ptr<DiagnosticConsumer> Secondary;
public:
ChainedDiagnosticConsumer(std::unique_ptr<DiagnosticConsumer> Primary,
std::unique_ptr<DiagnosticConsumer> Secondary)
: OwningPrimary(std::move(Primary)), Primary(OwningPrimary.get()),
Secondary(std::move(Secondary)) {}
/// \brief Construct without taking ownership of \c Primary.
ChainedDiagnosticConsumer(DiagnosticConsumer *Primary,
std::unique_ptr<DiagnosticConsumer> Secondary)
: Primary(Primary), Secondary(std::move(Secondary)) {}
void BeginSourceFile(const LangOptions &LO,
const Preprocessor *PP) override {
Primary->BeginSourceFile(LO, PP);
Secondary->BeginSourceFile(LO, PP);
}
void EndSourceFile() override {
Secondary->EndSourceFile();
Primary->EndSourceFile();
}
void finish() override {
Secondary->finish();
Primary->finish();
}
bool IncludeInDiagnosticCounts() const override {
return Primary->IncludeInDiagnosticCounts();
}
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
const Diagnostic &Info) override {
// Default implementation (Warnings/errors count).
DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
Primary->HandleDiagnostic(DiagLevel, Info);
Secondary->HandleDiagnostic(DiagLevel, Info);
}
};
} // end namspace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Frontend/FrontendPluginRegistry.h | //===-- FrontendAction.h - Pluggable Frontend Action Interface --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_FRONTEND_FRONTENDPLUGINREGISTRY_H
#define LLVM_CLANG_FRONTEND_FRONTENDPLUGINREGISTRY_H
#include "clang/Frontend/FrontendAction.h"
#include "llvm/Support/Registry.h"
// Instantiated in FrontendAction.cpp.
extern template class llvm::Registry<clang::PluginASTAction>;
namespace clang {
/// The frontend plugin registry.
typedef llvm::Registry<PluginASTAction> FrontendPluginRegistry;
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Frontend/CodeGenOptions.h | //===--- CodeGenOptions.h ---------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the CodeGenOptions interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_FRONTEND_CODEGENOPTIONS_H
#define LLVM_CLANG_FRONTEND_CODEGENOPTIONS_H
#include "clang/Basic/Sanitizers.h"
#include "llvm/Support/Regex.h"
#include <memory>
#include <string>
#include <vector>
#include <map>
#include <set>
#include "dxc/HLSL/HLSLExtensionsCodegenHelper.h" // HLSL change
#include "dxc/Support/SPIRVOptions.h" // SPIR-V Change
#include "dxc/DxcBindingTable/DxcBindingTable.h" // HLSL change
#include "dxc/Support/DxcOptToggles.h" // HLSL change
namespace clang {
/// \brief Bitfields of CodeGenOptions, split out from CodeGenOptions to ensure
/// that this large collection of bitfields is a trivial class type.
class CodeGenOptionsBase {
public:
#define CODEGENOPT(Name, Bits, Default) unsigned Name : Bits;
#define ENUM_CODEGENOPT(Name, Type, Bits, Default)
#include "clang/Frontend/CodeGenOptions.def"
protected:
#define CODEGENOPT(Name, Bits, Default)
#define ENUM_CODEGENOPT(Name, Type, Bits, Default) unsigned Name : Bits;
#include "clang/Frontend/CodeGenOptions.def"
};
/// CodeGenOptions - Track various options which control how the code
/// is optimized and passed to the backend.
class CodeGenOptions : public CodeGenOptionsBase {
public:
enum InliningMethod {
NoInlining, // Perform no inlining whatsoever.
NormalInlining, // Use the standard function inlining pass.
OnlyAlwaysInlining // Only run the always inlining pass.
};
enum VectorLibrary {
NoLibrary, // Don't use any vector library.
Accelerate // Use the Accelerate framework.
};
enum ObjCDispatchMethodKind {
Legacy = 0,
NonLegacy = 1,
Mixed = 2
};
enum DebugInfoKind {
NoDebugInfo, /// Don't generate debug info.
LocTrackingOnly, /// Emit location information but do not generate
/// debug info in the output. This is useful in
/// cases where the backend wants to track source
/// locations for instructions without actually
/// emitting debug info for them (e.g., when -Rpass
/// is used).
DebugLineTablesOnly, /// Emit only debug info necessary for generating
/// line number tables (-gline-tables-only).
LimitedDebugInfo, /// Limit generated debug info to reduce size
/// (-fno-standalone-debug). This emits
/// forward decls for types that could be
/// replaced with forward decls in the source
/// code. For dynamic C++ classes type info
/// is only emitted int the module that
/// contains the classe's vtable.
FullDebugInfo /// Generate complete debug info.
};
enum TLSModel {
GeneralDynamicTLSModel,
LocalDynamicTLSModel,
InitialExecTLSModel,
LocalExecTLSModel
};
enum FPContractModeKind {
FPC_Off, // Form fused FP ops only where result will not be affected.
FPC_On, // Form fused FP ops according to FP_CONTRACT rules.
FPC_Fast // Aggressively fuse FP ops (E.g. FMA).
};
enum StructReturnConventionKind {
SRCK_Default, // No special option was passed.
SRCK_OnStack, // Small structs on the stack (-fpcc-struct-return).
SRCK_InRegs // Small structs in registers (-freg-struct-return).
};
/// The code model to use (-mcmodel).
std::string CodeModel;
/// The filename with path we use for coverage files. The extension will be
/// replaced.
std::string CoverageFile;
/// The version string to put into coverage files.
char CoverageVersion[4];
/// Enable additional debugging information.
std::string DebugPass;
/// The string to embed in debug information as the current working directory.
std::string DebugCompilationDir;
/// The string to embed in the debug information for the compile unit, if
/// non-empty.
std::string DwarfDebugFlags;
/// The ABI to use for passing floating point arguments.
std::string FloatABI;
/// The float precision limit to use, if non-empty.
std::string LimitFloatPrecision;
/// The name of the bitcode file to link before optzns.
std::string LinkBitcodeFile;
/// The user provided name for the "main file", if non-empty. This is useful
/// in situations where the input file name does not match the original input
/// file, for example with -save-temps.
std::string MainFileName;
/// The name for the split debug info file that we'll break out. This is used
/// in the backend for setting the name in the skeleton cu.
std::string SplitDwarfFile;
/// The name of the relocation model to use.
std::string RelocationModel;
/// The thread model to use
std::string ThreadModel;
/// If not an empty string, trap intrinsics are lowered to calls to this
/// function instead of to trap instructions.
std::string TrapFuncName;
/// A list of command-line options to forward to the LLVM backend.
std::vector<std::string> BackendOptions;
/// A list of dependent libraries.
std::vector<std::string> DependentLibraries;
/// Name of the profile file to use as output for -fprofile-instr-generate
/// and -fprofile-generate.
std::string InstrProfileOutput;
/// Name of the profile file to use with -fprofile-sample-use.
std::string SampleProfileFile;
/// Name of the profile file to use as input for -fprofile-instr-use
std::string InstrProfileInput;
/// A list of file names passed with -fcuda-include-gpubinary options to
/// forward to CUDA runtime back-end for incorporating them into host-side
/// object file.
std::vector<std::string> CudaGpuBinaryFileNames;
// HLSL Change Starts
/// Entry point of hlsl shader passed with -hlsl-entry.
std::string HLSLEntryFunction;
/// Shader model to target for hlsl shader passed with -hlsl-profile.
std::string HLSLProfile;
/// Whether to target high-level DXIL.
bool HLSLHighLevel = false;
/// Whether we allow preserve intermediate values
bool HLSLAllowPreserveValues = false;
/// Whether we fail compilation if loop fails to unroll
bool HLSLOnlyWarnOnUnrollFail = false;
/// Whether use legacy resource reservation.
bool HLSLLegacyResourceReservation = false;
/// Set [branch] on every if.
bool HLSLPreferControlFlow = false;
/// Set [flatten] on every if.
bool HLSLAvoidControlFlow = false;
/// Force [flatten] on every if.
bool HLSLAllResourcesBound = false;
/// Skip adding optional semantics defines except ones which are required for correctness.
bool HLSLIgnoreOptSemDefs = false;
/// List of semantic defines that must be ignored.
std::set<std::string> HLSLIgnoreSemDefs;
/// List of semantic defines that must be overridden with user-provided values.
std::map<std::string, std::string> HLSLOverrideSemDefs;
/// Major version of validator to run.
unsigned HLSLValidatorMajorVer = 0;
/// Minor version of validator to run.
unsigned HLSLValidatorMinorVer = 0;
/// Define macros passed in from command line
std::vector<std::string> HLSLDefines;
/// Precise output passed in from command line
std::vector<std::string> HLSLPreciseOutputs;
/// Arguments passed in from command line
std::vector<std::string> HLSLArguments;
/// Helper for generating llvm bitcode for hlsl extensions.
std::shared_ptr<hlsl::HLSLExtensionsCodegenHelper> HLSLExtensionsCodegen;
/// Signature packing mode (0 == default for target)
unsigned HLSLSignaturePackingStrategy = 0;
/// denormalized number mode ("ieee" for default)
hlsl::DXIL::Float32DenormMode HLSLFloat32DenormMode;
/// HLSLDefaultSpace also enables automatic binding for libraries if set. UINT_MAX == unset
unsigned HLSLDefaultSpace = UINT_MAX;
/// HLSLLibraryExports specifies desired exports, with optional renaming
std::vector<std::string> HLSLLibraryExports;
/// ExportShadersOnly limits library export functions to shaders
bool ExportShadersOnly = false;
/// DefaultLinkage Internal, External, or Default. If Default, default
/// function linkage is determined by library target.
hlsl::DXIL::DefaultLinkage DefaultLinkage = hlsl::DXIL::DefaultLinkage::Default;
/// Assume UAVs/SRVs may alias.
bool HLSLResMayAlias = false;
/// Lookback scan limit for memory dependencies
unsigned ScanLimit = 0;
/// Optimization pass enables, disables and selects
hlsl::options::OptimizationToggles HLSLOptimizationToggles;
/// Debug option to print IR before every pass
bool HLSLPrintBeforeAll = false;
/// Debug option to print IR before specific pass
std::set<std::string> HLSLPrintBefore;
/// Debug option to print IR after every pass
bool HLSLPrintAfterAll = false;
/// Debug option to print IR after specific pass
std::set<std::string> HLSLPrintAfter;
/// Force-replace lifetime intrinsics by zeroinitializer stores.
bool HLSLForceZeroStoreLifetimes = false;
/// Enable lifetime marker generation
bool HLSLEnableLifetimeMarkers = false;
/// Put shader sources and options in the module
bool HLSLEmbedSourcesInModule = false;
/// Enable generation of payload access qualifier metadata.
bool HLSLEnablePayloadAccessQualifiers = false;
/// Binding table for HLSL resources
hlsl::DxcBindingTable HLSLBindingTable;
/// Binding table #define
struct BindingTableParserType {
virtual ~BindingTableParserType() {};
virtual bool Parse(llvm::raw_ostream &os, hlsl::DxcBindingTable *outBindingTable) = 0;
};
std::shared_ptr<BindingTableParserType> BindingTableParser;
// HLSL Change Ends
// SPIRV Change Starts
#ifdef ENABLE_SPIRV_CODEGEN
clang::spirv::SpirvCodeGenOptions SpirvOptions;
#endif
// SPIRV Change Ends
/// Regular expression to select optimizations for which we should enable
/// optimization remarks. Transformation passes whose name matches this
/// expression (and support this feature), will emit a diagnostic
/// whenever they perform a transformation. This is enabled by the
/// -Rpass=regexp flag.
std::shared_ptr<llvm::Regex> OptimizationRemarkPattern;
/// Regular expression to select optimizations for which we should enable
/// missed optimization remarks. Transformation passes whose name matches this
/// expression (and support this feature), will emit a diagnostic
/// whenever they tried but failed to perform a transformation. This is
/// enabled by the -Rpass-missed=regexp flag.
std::shared_ptr<llvm::Regex> OptimizationRemarkMissedPattern;
/// Regular expression to select optimizations for which we should enable
/// optimization analyses. Transformation passes whose name matches this
/// expression (and support this feature), will emit a diagnostic
/// whenever they want to explain why they decided to apply or not apply
/// a given transformation. This is enabled by the -Rpass-analysis=regexp
/// flag.
std::shared_ptr<llvm::Regex> OptimizationRemarkAnalysisPattern;
/// Set of files definining the rules for the symbol rewriting.
std::vector<std::string> RewriteMapFiles;
/// Set of sanitizer checks that are non-fatal (i.e. execution should be
/// continued when possible).
SanitizerSet SanitizeRecover;
/// Set of sanitizer checks that trap rather than diagnose.
SanitizerSet SanitizeTrap;
public:
// Define accessors/mutators for code generation options of enumeration type.
#define CODEGENOPT(Name, Bits, Default)
#define ENUM_CODEGENOPT(Name, Type, Bits, Default) \
Type get##Name() const { return static_cast<Type>(Name); } \
void set##Name(Type Value) { Name = static_cast<unsigned>(Value); }
#include "clang/Frontend/CodeGenOptions.def"
CodeGenOptions();
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Frontend/LangStandards.def | //===-- LangStandards.def - Language Standard Data --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LANGSTANDARD
#error "LANGSTANDARD must be defined before including this file"
#endif
/// LANGSTANDARD(IDENT, NAME, DESC, FEATURES)
///
/// \param IDENT - The name of the standard as a C++ identifier.
/// \param NAME - The name of the standard.
/// \param DESC - A short description of the standard.
/// \param FEATURES - The standard features as flags, these are enums from the
/// clang::frontend namespace, which is assumed to be be available.
// C89-ish modes.
LANGSTANDARD(c89, "c89",
"ISO C 1990",
C89 | ImplicitInt)
LANGSTANDARD(c90, "c90",
"ISO C 1990",
C89 | ImplicitInt)
LANGSTANDARD(iso9899_1990, "iso9899:1990",
"ISO C 1990",
C89 | ImplicitInt)
LANGSTANDARD(c94, "iso9899:199409",
"ISO C 1990 with amendment 1",
C89 | Digraphs | ImplicitInt)
LANGSTANDARD(gnu89, "gnu89",
"ISO C 1990 with GNU extensions",
LineComment | C89 | Digraphs | GNUMode | ImplicitInt)
LANGSTANDARD(gnu90, "gnu90",
"ISO C 1990 with GNU extensions",
LineComment | C89 | Digraphs | GNUMode | ImplicitInt)
// C99-ish modes
LANGSTANDARD(c99, "c99",
"ISO C 1999",
LineComment | C99 | Digraphs | HexFloat)
LANGSTANDARD(c9x, "c9x",
"ISO C 1999",
LineComment | C99 | Digraphs | HexFloat)
LANGSTANDARD(iso9899_1999,
"iso9899:1999", "ISO C 1999",
LineComment | C99 | Digraphs | HexFloat)
LANGSTANDARD(iso9899_199x,
"iso9899:199x", "ISO C 1999",
LineComment | C99 | Digraphs | HexFloat)
LANGSTANDARD(gnu99, "gnu99",
"ISO C 1999 with GNU extensions",
LineComment | C99 | Digraphs | GNUMode | HexFloat)
LANGSTANDARD(gnu9x, "gnu9x",
"ISO C 1999 with GNU extensions",
LineComment | C99 | Digraphs | GNUMode | HexFloat)
// C11 modes
LANGSTANDARD(c11, "c11",
"ISO C 2011",
LineComment | C99 | C11 | Digraphs | HexFloat)
LANGSTANDARD(c1x, "c1x",
"ISO C 2011",
LineComment | C99 | C11 | Digraphs | HexFloat)
LANGSTANDARD(iso9899_2011,
"iso9899:2011", "ISO C 2011",
LineComment | C99 | C11 | Digraphs | HexFloat)
LANGSTANDARD(iso9899_201x,
"iso9899:2011", "ISO C 2011",
LineComment | C99 | C11 | Digraphs | HexFloat)
LANGSTANDARD(gnu11, "gnu11",
"ISO C 2011 with GNU extensions",
LineComment | C99 | C11 | Digraphs | GNUMode | HexFloat)
LANGSTANDARD(gnu1x, "gnu1x",
"ISO C 2011 with GNU extensions",
LineComment | C99 | C11 | Digraphs | GNUMode | HexFloat)
// C++ modes
LANGSTANDARD(cxx98, "c++98",
"ISO C++ 1998 with amendments",
LineComment | CPlusPlus | Digraphs)
LANGSTANDARD(cxx03, "c++03",
"ISO C++ 1998 with amendments",
LineComment | CPlusPlus | Digraphs)
LANGSTANDARD(gnucxx98, "gnu++98",
"ISO C++ 1998 with amendments and GNU extensions",
LineComment | CPlusPlus | Digraphs | GNUMode)
LANGSTANDARD(cxx0x, "c++0x",
"ISO C++ 2011 with amendments",
LineComment | CPlusPlus | CPlusPlus11 | Digraphs)
LANGSTANDARD(cxx11, "c++11",
"ISO C++ 2011 with amendments",
LineComment | CPlusPlus | CPlusPlus11 | Digraphs)
LANGSTANDARD(gnucxx0x, "gnu++0x",
"ISO C++ 2011 with amendments and GNU extensions",
LineComment | CPlusPlus | CPlusPlus11 | Digraphs | GNUMode)
LANGSTANDARD(gnucxx11, "gnu++11",
"ISO C++ 2011 with amendments and GNU extensions",
LineComment | CPlusPlus | CPlusPlus11 | Digraphs | GNUMode)
LANGSTANDARD(cxx1y, "c++1y",
"ISO C++ 2014 with amendments",
LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | Digraphs)
LANGSTANDARD(cxx14, "c++14",
"ISO C++ 2014 with amendments",
LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | Digraphs)
LANGSTANDARD(gnucxx1y, "gnu++1y",
"ISO C++ 2014 with amendments and GNU extensions",
LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | Digraphs |
GNUMode)
LANGSTANDARD(gnucxx14, "gnu++14",
"ISO C++ 2014 with amendments and GNU extensions",
LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | Digraphs |
GNUMode)
LANGSTANDARD(cxx1z, "c++1z",
"Working draft for ISO C++ 2017",
LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | CPlusPlus1z |
Digraphs)
LANGSTANDARD(gnucxx1z, "gnu++1z",
"Working draft for ISO C++ 2017 with GNU extensions",
LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | CPlusPlus1z |
Digraphs | GNUMode)
// HLSL Change: HLSL Language standard declaration
LANGSTANDARD(hlsl, "hlsl",
"HLSL",
LineComment | CPlusPlus )
// OpenCL
LANGSTANDARD(opencl, "cl",
"OpenCL 1.0",
LineComment | C99 | Digraphs | HexFloat)
LANGSTANDARD(opencl11, "CL1.1",
"OpenCL 1.1",
LineComment | C99 | Digraphs | HexFloat)
LANGSTANDARD(opencl12, "CL1.2",
"OpenCL 1.2",
LineComment | C99 | Digraphs | HexFloat)
LANGSTANDARD(opencl20, "CL2.0",
"OpenCL 2.0",
LineComment | C99 | Digraphs | HexFloat)
// CUDA
LANGSTANDARD(cuda, "cuda",
"NVIDIA CUDA(tm)",
LineComment | CPlusPlus | Digraphs)
#undef LANGSTANDARD
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Frontend/CompilerInvocation.h | //===-- CompilerInvocation.h - Compiler Invocation Helper Data --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H_
#define LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H_
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "clang/Frontend/DependencyOutputOptions.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/Frontend/LangStandard.h"
#include "clang/Frontend/MigratorOptions.h"
#include "clang/Frontend/PreprocessorOutputOptions.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include <string>
#include <vector>
namespace llvm {
namespace opt {
class ArgList;
}
}
namespace clang {
class CompilerInvocation;
class DiagnosticsEngine;
/// \brief Fill out Opts based on the options given in Args.
///
/// Args must have been created from the OptTable returned by
/// createCC1OptTable().
///
/// When errors are encountered, return false and, if Diags is non-null,
/// report the error(s).
bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args,
DiagnosticsEngine *Diags = nullptr);
class CompilerInvocationBase : public RefCountedBase<CompilerInvocation> {
void operator=(const CompilerInvocationBase &) = delete;
public:
/// Options controlling the language variant.
std::shared_ptr<LangOptions> LangOpts;
/// Options controlling the target.
std::shared_ptr<TargetOptions> TargetOpts;
/// Options controlling the diagnostic engine.
IntrusiveRefCntPtr<DiagnosticOptions> DiagnosticOpts;
/// Options controlling the \#include directive.
IntrusiveRefCntPtr<HeaderSearchOptions> HeaderSearchOpts;
/// Options controlling the preprocessor (aside from \#include handling).
IntrusiveRefCntPtr<PreprocessorOptions> PreprocessorOpts;
CompilerInvocationBase();
~CompilerInvocationBase();
CompilerInvocationBase(const CompilerInvocationBase &X);
LangOptions *getLangOpts() { return LangOpts.get(); }
const LangOptions *getLangOpts() const { return LangOpts.get(); }
TargetOptions &getTargetOpts() { return *TargetOpts.get(); }
const TargetOptions &getTargetOpts() const {
return *TargetOpts.get();
}
DiagnosticOptions &getDiagnosticOpts() const { return *DiagnosticOpts; }
HeaderSearchOptions &getHeaderSearchOpts() { return *HeaderSearchOpts; }
const HeaderSearchOptions &getHeaderSearchOpts() const {
return *HeaderSearchOpts;
}
PreprocessorOptions &getPreprocessorOpts() { return *PreprocessorOpts; }
const PreprocessorOptions &getPreprocessorOpts() const {
return *PreprocessorOpts;
}
};
/// \brief Helper class for holding the data necessary to invoke the compiler.
///
/// This class is designed to represent an abstract "invocation" of the
/// compiler, including data such as the include paths, the code generation
/// options, the warning flags, and so on.
class CompilerInvocation : public CompilerInvocationBase {
/// Options controlling the static analyzer.
AnalyzerOptionsRef AnalyzerOpts;
MigratorOptions MigratorOpts;
/// Options controlling IRgen and the backend.
CodeGenOptions CodeGenOpts;
/// Options controlling dependency output.
DependencyOutputOptions DependencyOutputOpts;
/// Options controlling file system operations.
FileSystemOptions FileSystemOpts;
/// Options controlling the frontend itself.
FrontendOptions FrontendOpts;
/// Options controlling preprocessed output.
PreprocessorOutputOptions PreprocessorOutputOpts;
public:
CompilerInvocation() : AnalyzerOpts(new AnalyzerOptions()) {}
/// @name Utility Methods
/// @{
/// \brief Create a compiler invocation from a list of input options.
/// \returns true on success.
///
/// \param [out] Res - The resulting invocation.
/// \param ArgBegin - The first element in the argument vector.
/// \param ArgEnd - The last element in the argument vector.
/// \param Diags - The diagnostic engine to use for errors.
static bool CreateFromArgs(CompilerInvocation &Res,
const char* const *ArgBegin,
const char* const *ArgEnd,
DiagnosticsEngine &Diags);
/// \brief Get the directory where the compiler headers
/// reside, relative to the compiler binary (found by the passed in
/// arguments).
///
/// \param Argv0 - The program path (from argv[0]), for finding the builtin
/// compiler path.
/// \param MainAddr - The address of main (or some other function in the main
/// executable), for finding the builtin compiler path.
static std::string GetResourcesPath(const char *Argv0, void *MainAddr);
/// \brief Set language defaults for the given input language and
/// language standard in the given LangOptions object.
///
/// \param Opts - The LangOptions object to set up.
/// \param IK - The input language.
/// \param LangStd - The input language standard.
static void setLangDefaults(LangOptions &Opts, InputKind IK,
LangStandard::Kind LangStd = LangStandard::lang_unspecified);
/// \brief Retrieve a module hash string that is suitable for uniquely
/// identifying the conditions under which the module was built.
std::string getModuleHash() const;
/// @}
/// @name Option Subgroups
/// @{
AnalyzerOptionsRef getAnalyzerOpts() const {
return AnalyzerOpts;
}
MigratorOptions &getMigratorOpts() { return MigratorOpts; }
const MigratorOptions &getMigratorOpts() const {
return MigratorOpts;
}
CodeGenOptions &getCodeGenOpts() { return CodeGenOpts; }
const CodeGenOptions &getCodeGenOpts() const {
return CodeGenOpts;
}
DependencyOutputOptions &getDependencyOutputOpts() {
return DependencyOutputOpts;
}
const DependencyOutputOptions &getDependencyOutputOpts() const {
return DependencyOutputOpts;
}
FileSystemOptions &getFileSystemOpts() { return FileSystemOpts; }
const FileSystemOptions &getFileSystemOpts() const {
return FileSystemOpts;
}
FrontendOptions &getFrontendOpts() { return FrontendOpts; }
const FrontendOptions &getFrontendOpts() const {
return FrontendOpts;
}
PreprocessorOutputOptions &getPreprocessorOutputOpts() {
return PreprocessorOutputOpts;
}
const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
return PreprocessorOutputOpts;
}
/// @}
};
namespace vfs {
class FileSystem;
}
IntrusiveRefCntPtr<vfs::FileSystem>
createVFSFromCompilerInvocation(const CompilerInvocation &CI,
DiagnosticsEngine &Diags);
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Frontend/SerializedDiagnosticReader.h | //===--- SerializedDiagnosticReader.h - Reads diagnostics -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_FRONTEND_SERIALIZED_DIAGNOSTIC_READER_H_
#define LLVM_CLANG_FRONTEND_SERIALIZED_DIAGNOSTIC_READER_H_
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Bitcode/BitstreamReader.h"
#include "llvm/Support/ErrorOr.h"
namespace clang {
namespace serialized_diags {
enum class SDError {
CouldNotLoad = 1,
InvalidSignature,
InvalidDiagnostics,
MalformedTopLevelBlock,
MalformedSubBlock,
MalformedBlockInfoBlock,
MalformedMetadataBlock,
MalformedDiagnosticBlock,
MalformedDiagnosticRecord,
MissingVersion,
VersionMismatch,
UnsupportedConstruct,
/// A generic error for subclass handlers that don't want or need to define
/// their own error_category.
HandlerFailed
};
const std::error_category &SDErrorCategory();
inline std::error_code make_error_code(SDError E) {
return std::error_code(static_cast<int>(E), SDErrorCategory());
}
/// \brief A location that is represented in the serialized diagnostics.
struct Location {
unsigned FileID;
unsigned Line;
unsigned Col;
unsigned Offset;
Location(unsigned FileID, unsigned Line, unsigned Col, unsigned Offset)
: FileID(FileID), Line(Line), Col(Col), Offset(Offset) {}
};
/// \brief A base class that handles reading serialized diagnostics from a file.
///
/// Subclasses should override the visit* methods with their logic for handling
/// the various constructs that are found in serialized diagnostics.
class SerializedDiagnosticReader {
public:
SerializedDiagnosticReader() {}
virtual ~SerializedDiagnosticReader() {}
/// \brief Read the diagnostics in \c File
std::error_code readDiagnostics(StringRef File);
private:
enum class Cursor;
/// \brief Read to the next record or block to process.
llvm::ErrorOr<Cursor> skipUntilRecordOrBlock(llvm::BitstreamCursor &Stream,
unsigned &BlockOrRecordId);
/// \brief Read a metadata block from \c Stream.
std::error_code readMetaBlock(llvm::BitstreamCursor &Stream);
/// \brief Read a diagnostic block from \c Stream.
std::error_code readDiagnosticBlock(llvm::BitstreamCursor &Stream);
protected:
/// \brief Visit the start of a diagnostic block.
virtual std::error_code visitStartOfDiagnostic() {
return std::error_code();
};
/// \brief Visit the end of a diagnostic block.
virtual std::error_code visitEndOfDiagnostic() { return std::error_code(); };
/// \brief Visit a category. This associates the category \c ID to a \c Name.
virtual std::error_code visitCategoryRecord(unsigned ID, StringRef Name) {
return std::error_code();
};
/// \brief Visit a flag. This associates the flag's \c ID to a \c Name.
virtual std::error_code visitDiagFlagRecord(unsigned ID, StringRef Name) {
return std::error_code();
};
/// \brief Visit a diagnostic.
virtual std::error_code
visitDiagnosticRecord(unsigned Severity, const Location &Location,
unsigned Category, unsigned Flag, StringRef Message) {
return std::error_code();
};
/// \brief Visit a filename. This associates the file's \c ID to a \c Name.
virtual std::error_code visitFilenameRecord(unsigned ID, unsigned Size,
unsigned Timestamp,
StringRef Name) {
return std::error_code();
};
/// \brief Visit a fixit hint.
virtual std::error_code
visitFixitRecord(const Location &Start, const Location &End, StringRef Text) {
return std::error_code();
};
/// \brief Visit a source range.
virtual std::error_code visitSourceRangeRecord(const Location &Start,
const Location &End) {
return std::error_code();
};
/// \brief Visit the version of the set of diagnostics.
virtual std::error_code visitVersionRecord(unsigned Version) {
return std::error_code();
};
};
} // end serialized_diags namespace
} // end clang namespace
namespace std {
template <>
struct is_error_code_enum<clang::serialized_diags::SDError> : std::true_type {};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Frontend/MigratorOptions.h | //===--- MigratorOptions.h - MigratorOptions Options ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This header contains the structures necessary for a front-end to specify
// various migration analysis.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_FRONTEND_MIGRATOROPTIONS_H
#define LLVM_CLANG_FRONTEND_MIGRATOROPTIONS_H
namespace clang {
class MigratorOptions {
public:
unsigned NoNSAllocReallocError : 1;
unsigned NoFinalizeRemoval : 1;
MigratorOptions() {
NoNSAllocReallocError = 0;
NoFinalizeRemoval = 0;
}
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Frontend/FrontendDiagnostic.h | //===--- DiagnosticFrontend.h - Diagnostics for frontend --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_FRONTEND_FRONTENDDIAGNOSTIC_H
#define LLVM_CLANG_FRONTEND_FRONTENDDIAGNOSTIC_H
#include "clang/Basic/Diagnostic.h"
namespace clang {
namespace diag {
enum {
#define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\
SFINAE,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM,
#define FRONTENDSTART
#include "clang/Basic/DiagnosticFrontendKinds.inc"
#undef DIAG
NUM_BUILTIN_FRONTEND_DIAGNOSTICS
};
} // end namespace diag
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Frontend/TextDiagnostic.h | //===--- TextDiagnostic.h - Text Diagnostic Pretty-Printing -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is a utility class that provides support for textual pretty-printing of
// diagnostics. It is used to implement the different code paths which require
// such functionality in a consistent way.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_FRONTEND_TEXTDIAGNOSTIC_H
#define LLVM_CLANG_FRONTEND_TEXTDIAGNOSTIC_H
#include "clang/Frontend/DiagnosticRenderer.h"
namespace clang {
/// \brief Class to encapsulate the logic for formatting and printing a textual
/// diagnostic message.
///
/// This class provides an interface for building and emitting a textual
/// diagnostic, including all of the macro backtraces, caret diagnostics, FixIt
/// Hints, and code snippets. In the presence of macros this involves
/// a recursive process, synthesizing notes for each macro expansion.
///
/// The purpose of this class is to isolate the implementation of printing
/// beautiful text diagnostics from any particular interfaces. The Clang
/// DiagnosticClient is implemented through this class as is diagnostic
/// printing coming out of libclang.
class TextDiagnostic : public DiagnosticRenderer {
raw_ostream &OS;
public:
TextDiagnostic(raw_ostream &OS,
const LangOptions &LangOpts,
DiagnosticOptions *DiagOpts);
~TextDiagnostic() override;
/// \brief Print the diagonstic level to a raw_ostream.
///
/// This is a static helper that handles colorizing the level and formatting
/// it into an arbitrary output stream. This is used internally by the
/// TextDiagnostic emission code, but it can also be used directly by
/// consumers that don't have a source manager or other state that the full
/// TextDiagnostic logic requires.
static void printDiagnosticLevel(raw_ostream &OS,
DiagnosticsEngine::Level Level,
bool ShowColors,
bool CLFallbackMode = false);
/// \brief Pretty-print a diagnostic message to a raw_ostream.
///
/// This is a static helper to handle the line wrapping, colorizing, and
/// rendering of a diagnostic message to a particular ostream. It is
/// publicly visible so that clients which do not have sufficient state to
/// build a complete TextDiagnostic object can still get consistent
/// formatting of their diagnostic messages.
///
/// \param OS Where the message is printed
/// \param IsSupplemental true if this is a continuation note diagnostic
/// \param Message The text actually printed
/// \param CurrentColumn The starting column of the first line, accounting
/// for any prefix.
/// \param Columns The number of columns to use in line-wrapping, 0 disables
/// all line-wrapping.
/// \param ShowColors Enable colorizing of the message.
static void printDiagnosticMessage(raw_ostream &OS, bool IsSupplemental,
StringRef Message, unsigned CurrentColumn,
unsigned Columns, bool ShowColors);
protected:
void emitDiagnosticMessage(SourceLocation Loc,PresumedLoc PLoc,
DiagnosticsEngine::Level Level,
StringRef Message,
ArrayRef<CharSourceRange> Ranges,
const SourceManager *SM,
DiagOrStoredDiag D) override;
void emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
DiagnosticsEngine::Level Level,
ArrayRef<CharSourceRange> Ranges,
const SourceManager &SM) override;
void emitCodeContext(SourceLocation Loc,
DiagnosticsEngine::Level Level,
SmallVectorImpl<CharSourceRange>& Ranges,
ArrayRef<FixItHint> Hints,
const SourceManager &SM) override {
emitSnippetAndCaret(Loc, Level, Ranges, Hints, SM);
}
void emitIncludeLocation(SourceLocation Loc, PresumedLoc PLoc,
const SourceManager &SM) override;
void emitImportLocation(SourceLocation Loc, PresumedLoc PLoc,
StringRef ModuleName,
const SourceManager &SM) override;
void emitBuildingModuleLocation(SourceLocation Loc, PresumedLoc PLoc,
StringRef ModuleName,
const SourceManager &SM) override;
private:
void emitSnippetAndCaret(SourceLocation Loc, DiagnosticsEngine::Level Level,
SmallVectorImpl<CharSourceRange>& Ranges,
ArrayRef<FixItHint> Hints,
const SourceManager &SM);
void emitSnippet(StringRef SourceLine);
void emitParseableFixits(ArrayRef<FixItHint> Hints, const SourceManager &SM);
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Frontend/SerializedDiagnostics.h | //===--- SerializedDiagnostics.h - Common data for serialized diagnostics -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_FRONTEND_SERIALIZE_DIAGNOSTICS_H_
#define LLVM_CLANG_FRONTEND_SERIALIZE_DIAGNOSTICS_H_
#include "llvm/Bitcode/BitCodes.h"
namespace clang {
namespace serialized_diags {
enum BlockIDs {
/// \brief A top-level block which represents any meta data associated
/// with the diagostics, including versioning of the format.
BLOCK_META = llvm::bitc::FIRST_APPLICATION_BLOCKID,
/// \brief The this block acts as a container for all the information
/// for a specific diagnostic.
BLOCK_DIAG
};
enum RecordIDs {
RECORD_VERSION = 1,
RECORD_DIAG,
RECORD_SOURCE_RANGE,
RECORD_DIAG_FLAG,
RECORD_CATEGORY,
RECORD_FILENAME,
RECORD_FIXIT,
RECORD_FIRST = RECORD_VERSION,
RECORD_LAST = RECORD_FIXIT
};
/// \brief A stable version of DiagnosticIDs::Level.
///
/// Do not change the order of values in this enum, and please increment the
/// serialized diagnostics version number when you add to it.
enum Level {
Ignored = 0,
Note,
Warning,
Error,
Fatal,
Remark
};
/// \brief The serialized diagnostics version number.
enum { VersionNumber = 2 };
} // end serialized_diags namespace
} // end clang namespace
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Frontend/CommandLineSourceLoc.h | //===--- CommandLineSourceLoc.h - Parsing for source locations-*- C++ -*---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Command line parsing for source locations.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_FRONTEND_COMMANDLINESOURCELOC_H
#define LLVM_CLANG_FRONTEND_COMMANDLINESOURCELOC_H
#include "clang/Basic/LLVM.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
namespace clang {
/// \brief A source location that has been parsed on the command line.
struct ParsedSourceLocation {
std::string FileName;
unsigned Line;
unsigned Column;
public:
/// Construct a parsed source location from a string; the Filename is empty on
/// error.
static ParsedSourceLocation FromString(StringRef Str) {
ParsedSourceLocation PSL;
std::pair<StringRef, StringRef> ColSplit = Str.rsplit(':');
std::pair<StringRef, StringRef> LineSplit =
ColSplit.first.rsplit(':');
// If both tail splits were valid integers, return success.
if (!ColSplit.second.getAsInteger(10, PSL.Column) &&
!LineSplit.second.getAsInteger(10, PSL.Line)) {
PSL.FileName = LineSplit.first;
// On the command-line, stdin may be specified via "-". Inside the
// compiler, stdin is called "<stdin>".
if (PSL.FileName == "-")
PSL.FileName = "<stdin>";
}
return PSL;
}
};
}
namespace llvm {
namespace cl {
/// \brief Command-line option parser that parses source locations.
///
/// Source locations are of the form filename:line:column.
template<>
class parser<clang::ParsedSourceLocation> final
: public basic_parser<clang::ParsedSourceLocation> {
public:
inline bool parse(Option &O, StringRef ArgName, StringRef ArgValue,
clang::ParsedSourceLocation &Val);
};
bool
parser<clang::ParsedSourceLocation>::
parse(Option &O, StringRef ArgName, StringRef ArgValue,
clang::ParsedSourceLocation &Val) {
using namespace clang;
Val = ParsedSourceLocation::FromString(ArgValue);
if (Val.FileName.empty()) {
errs() << "error: "
<< "source location must be of the form filename:line:column\n";
return true;
}
return false;
}
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.