25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
29 #include <system_error>
31 using namespace clang;
37 std::unique_ptr<ASTConsumer>
39 return llvm::make_unique<ASTConsumer>();
42 void InitOnlyAction::ExecuteAction() {
49 std::unique_ptr<ASTConsumer>
51 if (std::unique_ptr<raw_ostream> OS =
57 std::unique_ptr<ASTConsumer>
64 std::unique_ptr<ASTConsumer>
69 std::unique_ptr<ASTConsumer>
74 std::unique_ptr<ASTConsumer>
80 std::unique_ptr<ASTConsumer>
83 std::string OutputFile;
84 std::unique_ptr<raw_pwrite_stream> OS =
92 auto Buffer = std::make_shared<PCHBuffer>();
93 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
94 Consumers.push_back(llvm::make_unique<PCHGenerator>(
101 CI, InFile, OutputFile, std::move(OS), Buffer));
103 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
106 std::unique_ptr<raw_pwrite_stream>
109 std::string &Sysroot,
110 std::string &OutputFile) {
120 std::unique_ptr<raw_pwrite_stream> OS =
131 std::unique_ptr<ASTConsumer>
135 std::string OutputFile;
136 std::unique_ptr<raw_pwrite_stream> OS =
141 auto Buffer = std::make_shared<PCHBuffer>();
142 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
144 Consumers.push_back(llvm::make_unique<PCHGenerator>(
151 CI, InFile, OutputFile, std::move(OS), Buffer));
152 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
157 Includes.append(RHS.begin(), RHS.end());
162 SmallVectorImpl<char> &Includes,
165 if (IsExternC && LangOpts.CPlusPlus)
166 Includes +=
"extern \"C\" {\n";
168 Includes +=
"#import \"";
170 Includes +=
"#include \"";
172 Includes += HeaderName;
175 if (IsExternC && LangOpts.CPlusPlus)
186 static std::error_code
189 SmallVectorImpl<char> &Includes) {
192 return std::error_code();
217 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
221 Dir !=
End && !EC; Dir.increment(EC)) {
224 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName()))
225 .Cases(
".h",
".H",
".hh",
".hpp",
true)
242 auto PathIt = llvm::sys::path::rbegin(Dir->getName());
243 for (
int I = 0;
I != Dir.level() + 1; ++
I, ++PathIt)
244 Components.push_back(*PathIt);
246 for (
auto It = Components.rbegin(),
End = Components.rend(); It !=
End;
248 llvm::sys::path::append(RelativeHeader, *It);
262 Sub != SubEnd; ++Sub)
264 LangOpts, FileMgr, ModMap, *Sub, Includes))
267 return std::error_code();
334 diag::err_module_header_missing)
339 << Requirement.second << Requirement.first;
345 if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
349 ModuleMapForUniquing = ModuleMap;
356 std::error_code Err = std::error_code();
375 std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
376 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
384 std::unique_ptr<raw_pwrite_stream>
387 std::string &Sysroot,
388 std::string &OutputFile) {
395 ModuleMapForUniquing->
getName());
401 std::unique_ptr<raw_pwrite_stream> OS =
416 std::unique_ptr<ASTConsumer>
418 return llvm::make_unique<ASTConsumer>();
421 std::unique_ptr<ASTConsumer>
424 return llvm::make_unique<ASTConsumer>();
427 std::unique_ptr<ASTConsumer>
429 return llvm::make_unique<ASTConsumer>();
436 std::unique_ptr<ASTReader> Reader(
new ASTReader(
439 Sysroot.empty() ?
"" : Sysroot.c_str(),
456 llvm::raw_ostream &Out;
459 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
461 #define DUMP_BOOLEAN(Value, Text) \
462 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
464 bool ReadFullVersionInformation(StringRef FullVersion)
override {
469 <<
" Clang: " << FullVersion <<
"\n";
473 void ReadModuleName(StringRef ModuleName)
override {
474 Out.indent(2) <<
"Module name: " << ModuleName <<
"\n";
476 void ReadModuleMapFile(StringRef ModuleMapPath)
override {
477 Out.indent(2) <<
"Module map file: " << ModuleMapPath <<
"\n";
480 bool ReadLanguageOptions(
const LangOptions &LangOpts,
bool Complain,
481 bool AllowCompatibleDifferences)
override {
482 Out.indent(2) <<
"Language options:\n";
483 #define LANGOPT(Name, Bits, Default, Description) \
484 DUMP_BOOLEAN(LangOpts.Name, Description);
485 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
486 Out.indent(4) << Description << ": " \
487 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
488 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
489 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
490 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
491 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
492 #include "clang/Basic/LangOptions.def"
495 Out.indent(4) <<
"Module features:\n";
497 Out.indent(6) << Feature <<
"\n";
503 bool ReadTargetOptions(
const TargetOptions &TargetOpts,
bool Complain,
504 bool AllowCompatibleDifferences)
override {
505 Out.indent(2) <<
"Target options:\n";
506 Out.indent(4) <<
" Triple: " << TargetOpts.
Triple <<
"\n";
507 Out.indent(4) <<
" CPU: " << TargetOpts.
CPU <<
"\n";
508 Out.indent(4) <<
" ABI: " << TargetOpts.
ABI <<
"\n";
511 Out.indent(4) <<
"Target features:\n";
522 bool Complain)
override {
523 Out.indent(2) <<
"Diagnostic options:\n";
524 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
525 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
526 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
527 #define VALUE_DIAGOPT(Name, Bits, Default) \
528 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
529 #include "clang/Basic/DiagnosticOptions.def"
531 Out.indent(4) <<
"Diagnostic flags:\n";
532 for (
const std::string &
Warning : DiagOpts->Warnings)
533 Out.indent(6) <<
"-W" << Warning <<
"\n";
534 for (
const std::string &
Remark : DiagOpts->Remarks)
535 Out.indent(6) <<
"-R" << Remark <<
"\n";
541 StringRef SpecificModuleCachePath,
542 bool Complain)
override {
543 Out.indent(2) <<
"Header search options:\n";
544 Out.indent(4) <<
"System root [-isysroot=]: '" << HSOpts.
Sysroot <<
"'\n";
545 Out.indent(4) <<
"Module Cache: '" << SpecificModuleCachePath <<
"'\n";
547 "Use builtin include directories [-nobuiltininc]");
549 "Use standard system include directories [-nostdinc]");
551 "Use standard C++ include directories [-nostdinc++]");
553 "Use libc++ (rather than libstdc++) [-stdlib=]");
559 std::string &SuggestedPredefines)
override {
560 Out.indent(2) <<
"Preprocessor options:\n";
562 "Uses compiler/target-specific predefines [-undef]");
564 "Uses detailed preprocessing record (for indexing)");
566 if (!PPOpts.
Macros.empty()) {
567 Out.indent(4) <<
"Predefined macros:\n";
570 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
578 Out <<
I->first <<
"\n";
584 void readModuleFileExtension(
586 Out.indent(2) <<
"Module file extension '"
591 Out.write_escaped(Metadata.
UserInfo);
602 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
604 if (!OutputFileName.empty() && OutputFileName !=
"-") {
606 OutFile.reset(
new llvm::raw_fd_ostream(OutputFileName.str(), EC,
607 llvm::sys::fs::F_Text));
609 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
611 Out <<
"Information for module file '" <<
getCurrentFile() <<
"':\n";
612 DumpModuleInfoListener Listener(Out);
633 RawLex.LexFromRawLexer(RawTok);
636 llvm::errs() <<
"\n";
637 RawLex.LexFromRawLexer(RawTok);
649 llvm::errs() <<
"\n";
655 std::unique_ptr<raw_pwrite_stream> OS =
692 bool BinaryMode =
true;
693 bool InvalidFile =
false;
698 const char *cur = Buffer->getBufferStart();
699 const char *
end = Buffer->getBufferEnd();
700 const char *next = (cur !=
end) ? cur + 1 : end;
705 if (end - cur > 256) end = cur + 256;
713 }
else if (*cur == 0x0A)
721 std::unique_ptr<raw_ostream> OS =
758 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
std::string OutputFile
The output file, if any.
SourceManager & getSourceManager() const
LangOptions & getLangOpts()
ASTContext & getASTContext() const
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
PreprocessorOptions & getPreprocessorOpts()
Header getUmbrellaHeader() const
Retrieve the header that serves as the umbrella header for this module.
std::vector< std::pair< std::string, bool > > Macros
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
bool BeginSourceFileAction(CompilerInstance &CI, StringRef Filename) override
Callback at the start of processing a single input.
Implements support for file system lookup, file system caching, and directory search management...
static std::pair< unsigned, bool > ComputePreamble(StringRef Buffer, const LangOptions &LangOpts, unsigned MaxLines=0)
Compute the preamble of the given file.
Defines the clang::FileManager interface and associated types.
submodule_iterator submodule_begin()
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "...
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
CompilerInstance & getCompilerInstance() const
llvm::MemoryBuffer * getBuffer(FileID FID, SourceLocation Loc, bool *Invalid=nullptr) const
Return the buffer for the specified FileID.
std::unique_ptr< llvm::MemoryBuffer > Buffer
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
static std::unique_ptr< raw_pwrite_stream > ComputeASTConsumerArguments(CompilerInstance &CI, StringRef InFile, std::string &Sysroot, std::string &OutputFile)
Compute the AST consumer arguments that will be used to create the PCHGenerator instance returned by ...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::string ASTDumpFilter
If given, filter dumped AST Decl nodes by this substring.
TargetInfo & getTarget() const
SourceManager & getSourceManager() const
Return the current source manager.
void IgnorePragmas()
Install empty handlers for all pragmas (making them ignored).
Options for controlling the target.
InputKind getCurrentFileKind() const
bool isHeaderUnavailableInModule(const FileEntry *Header, const Module *RequestingModule) const
Determine whether the given header is unavailable as part of the specified module.
void DumpToken(const Token &Tok, bool DumpFlags=false) const
Print the token to stderr, used for debugging.
std::string getFullModuleName() const
Retrieve the full name of this module, including the path from its top-level module.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
The virtual file system interface.
static StringRef getModuleInputBufferName()
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener)
Read the control block for the named AST file.
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
const LangOptions & getLangOpts() const
Token - This structure provides full information about a lexed token.
unsigned DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
An input iterator over the recursive contents of a virtual path, similar to llvm::sys::fs::recursive_...
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
unsigned BuildingImplicitModule
Whether we are performing an implicit module build.
std::vector< std::string > ModulesEmbedFiles
The list of files to embed into the compiled module file.
Describes a module or submodule.
unsigned RelocatablePCH
When generating PCH files, instruct the AST writer to create relocatable PCH files.
bool isAvailable() const
Determine whether this module is available for use within the current translation unit...
FrontendOptions & getFrontendOpts()
IntrusiveRefCntPtr< vfs::FileSystem > getVirtualFileSystem() const
PreprocessorOutputOptions & getPreprocessorOutputOpts()
HeaderSearch & getHeaderSearchInfo() const
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Module * Parent
The parent of this module.
unsigned IsInferred
Whether this is an inferred submodule (module * { ... }).
submodule_iterator submodule_end()
void CacheTokens(Preprocessor &PP, raw_pwrite_stream *OS)
Cache tokens for use with PCH. Note that this requires a seekable stream.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
#define DUMP_BOOLEAN(Value, Text)
HeaderSearchOptions & getHeaderSearchOpts()
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer...
detail::InMemoryDirectory::const_iterator I
Preprocessor & getPreprocessor() const
Return the current preprocessor.
std::vector< Module * >::iterator submodule_iterator
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers)...
const FileEntry * getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
std::string CurrentModule
The name of the current module, of which the main source file is a part.
void setCurrentInput(const FrontendInputFile &CurrentInput, std::unique_ptr< ASTUnit > AST=nullptr)
void setFileIsTransient(const FileEntry *SourceFile)
Specify that a file is transient.
unsigned UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS, const PreprocessorOutputOptions &Opts)
DoPrintPreprocessedInput - Implement -E mode.
ModuleBuildStack getModuleBuildStack() const
Retrieve the module build stack.
static SmallVectorImpl< char > & operator+=(SmallVectorImpl< char > &Includes, StringRef RHS)
void EnterMainSourceFile()
Enter the specified FileID as the main source file, which implicitly adds the builtin defines etc...
Defines the clang::Preprocessor interface.
unsigned ModulesEmbedAllFiles
Whether we should embed all used files into the PCM file.
bool isNot(tok::TokenKind K) const
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
DirectoryName getUmbrellaDir() const
Retrieve the directory for which this module serves as the umbrella.
static std::error_code collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr, ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl< char > &Includes)
Collect the set of header includes needed to construct the given module and update the TopHeaders fil...
std::unique_ptr< raw_pwrite_stream > createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, StringRef BaseInput, StringRef Extension, bool UseTemporary, bool CreateMissingDirectories=false)
Create a new output file and add it to the list of tracked output files, optionally deriving the outp...
std::string CPU
If given, the name of the target CPU to generate code for.
const DirectoryEntry * Directory
The build directory of this module.
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
std::string ABI
If given, the name of the target ABI to use.
File is a PCH file treated as the preamble.
const char * getName() const
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Encodes a location in the source.
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
File is a PCH file treated as such.
bool isValid() const
Return true if this is a valid SourceLocation object.
const StringRef getCurrentFile() const
Information about a directory name as found in the module map file.
std::unique_ptr< raw_pwrite_stream > ComputeASTConsumerArguments(CompilerInstance &CI, StringRef InFile, std::string &Sysroot, std::string &OutputFile)
Compute the AST consumer arguments that will be used to create the PCHGenerator instance returned by ...
Cached information about one file (either on disk or in the virtual file system). ...
unsigned IncludeTimestamps
Whether timestamps should be written to the produced PCH file.
SmallVector< Header, 2 > Headers[5]
The headers that are part of this module.
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
void Lex(Token &Result)
Lex the next token for this preprocessor.
virtual bool ReadFullVersionInformation(StringRef FullVersion)
Receives the full Clang version information.
unsigned ASTDumpLookups
Whether we include lookup table dumps in AST dumps.
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line...
void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc)
Push an entry to the module build stack.
FileID getMainFileID() const
Returns the FileID of the main source file.
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Reads an AST files chain containing the contents of a translation unit.
FileManager & getFileManager() const
Return the current file manager to the caller.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const FileEntry *Entry, bool isVolatile=false, bool ShouldCloseOpenFile=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
virtual std::unique_ptr< ASTConsumer > CreatePCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName, const std::string &OutputFileName, std::unique_ptr< llvm::raw_pwrite_stream > OS, std::shared_ptr< PCHBuffer > Buffer) const =0
Return an ASTConsumer that can be chained with a PCHGenerator that produces a wrapper file format con...
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
void addTopHeader(const FileEntry *File)
Add a top-level header associated with this module.
static void addHeaderInclude(StringRef HeaderName, SmallVectorImpl< char > &Includes, const LangOptions &LangOpts, bool IsExternC)
Abstract interface for callback invocations by the ASTReader.
std::unique_ptr< ASTConsumer > CreateDeclContextPrinter()
std::pair< std::string, bool > Requirement
An individual requirement: a feature name and a flag indicating the required state of that feature...
~SyntaxOnlyAction() override
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="")
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
std::unique_ptr< ASTConsumer > CreateASTViewer()
const PCHContainerWriter & getPCHContainerWriter() const
Return the appropriate PCHContainerWriter depending on the current CodeGenOptions.
std::unique_ptr< ASTConsumer > CreateASTDeclNodeLister()
void setMainFileDir(const DirectoryEntry *Dir)
Set the directory in which the main file should be considered to have been found, if it is not a real...
unsigned ASTDumpDecls
Whether we include declaration dumps in AST dumps.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
std::vector< IntrusiveRefCntPtr< ModuleFileExtension > > ModuleFileExtensions
The list of module file extensions.
A SourceLocation and its associated SourceManager.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
std::unique_ptr< ASTConsumer > CreateASTDumper(StringRef FilterString, bool DumpDecls, bool DumpLookups)
void setAllFilesAreTransient(bool Transient)
Specify that all files that are read during this compilation are transient.
std::unique_ptr< ASTConsumer > CreateASTPrinter(std::unique_ptr< raw_ostream > OS, StringRef FilterString)
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
void SetKeepWhitespaceMode(bool Val)
SetKeepWhitespaceMode - This method lets clients enable or disable whitespace retention mode...
std::string Triple
If given, the name of the target triple to compile for.
void setInferredModuleAllowedBy(Module *M, const FileEntry *ModuleMap)
This class handles loading and caching of source files into memory.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer...