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>
56 std::unique_ptr<ASTConsumer>
63 std::unique_ptr<ASTConsumer>
68 std::unique_ptr<ASTConsumer>
73 std::unique_ptr<ASTConsumer>
79 std::unique_ptr<ASTConsumer>
82 std::string OutputFile;
83 raw_pwrite_stream *OS =
91 auto Buffer = std::make_shared<PCHBuffer>();
92 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
93 Consumers.push_back(llvm::make_unique<PCHGenerator>(
97 CI, InFile, OutputFile, OS, Buffer));
99 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
104 std::string &OutputFile) {
114 raw_pwrite_stream *OS =
125 std::unique_ptr<ASTConsumer>
129 std::string OutputFile;
130 raw_pwrite_stream *OS =
135 auto Buffer = std::make_shared<PCHBuffer>();
136 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
138 Consumers.push_back(llvm::make_unique<PCHGenerator>(
145 CI, InFile, OutputFile, OS, Buffer));
146 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
151 Includes.append(RHS.begin(), RHS.end());
156 SmallVectorImpl<char> &Includes,
159 if (IsExternC && LangOpts.CPlusPlus)
160 Includes +=
"extern \"C\" {\n";
162 Includes +=
"#import \"";
164 Includes +=
"#include \"";
166 Includes += HeaderName;
169 if (IsExternC && LangOpts.CPlusPlus)
171 return std::error_code();
181 static std::error_code
184 SmallVectorImpl<char> &Includes) {
187 return std::error_code();
217 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
218 for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative, EC),
220 Dir != DirEnd && !EC; Dir.increment(EC)) {
223 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
224 .Cases(
".h",
".H",
".hh",
".hpp",
true)
241 auto PathIt = llvm::sys::path::rbegin(Dir->path());
242 for (
int I = 0;
I != Dir.level() + 1; ++
I, ++PathIt)
243 Components.push_back(*PathIt);
245 for (
auto It = Components.rbegin(),
End = Components.rend(); It !=
End;
247 llvm::sys::path::append(RelativeHeader, *It);
263 Sub != SubEnd; ++Sub)
265 LangOpts, FileMgr, ModMap, *Sub, Includes))
268 return std::error_code();
333 diag::err_module_header_missing)
338 << Requirement.second << Requirement.first;
344 if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
348 ModuleMapForUniquing = ModuleMap;
355 std::error_code Err = std::error_code();
375 std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
376 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
386 std::string &OutputFile) {
393 ModuleMapForUniquing->
getName());
399 raw_pwrite_stream *OS =
411 std::unique_ptr<ASTConsumer>
413 return llvm::make_unique<ASTConsumer>();
416 std::unique_ptr<ASTConsumer>
419 return llvm::make_unique<ASTConsumer>();
422 std::unique_ptr<ASTConsumer>
424 return llvm::make_unique<ASTConsumer>();
431 std::unique_ptr<ASTReader> Reader(
new ASTReader(
434 Sysroot.empty() ?
"" : Sysroot.c_str(),
451 llvm::raw_ostream &Out;
454 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
456 #define DUMP_BOOLEAN(Value, Text) \
457 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
459 bool ReadFullVersionInformation(StringRef FullVersion)
override {
464 <<
" Clang: " << FullVersion <<
"\n";
468 void ReadModuleName(StringRef ModuleName)
override {
469 Out.indent(2) <<
"Module name: " << ModuleName <<
"\n";
471 void ReadModuleMapFile(StringRef ModuleMapPath)
override {
472 Out.indent(2) <<
"Module map file: " << ModuleMapPath <<
"\n";
475 bool ReadLanguageOptions(
const LangOptions &LangOpts,
bool Complain,
476 bool AllowCompatibleDifferences)
override {
477 Out.indent(2) <<
"Language options:\n";
478 #define LANGOPT(Name, Bits, Default, Description) \
479 DUMP_BOOLEAN(LangOpts.Name, Description);
480 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
481 Out.indent(4) << Description << ": " \
482 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
483 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
484 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
485 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
486 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
487 #include "clang/Basic/LangOptions.def"
490 Out.indent(4) <<
"Module features:\n";
492 Out.indent(6) << Feature <<
"\n";
498 bool ReadTargetOptions(
const TargetOptions &TargetOpts,
bool Complain,
499 bool AllowCompatibleDifferences)
override {
500 Out.indent(2) <<
"Target options:\n";
501 Out.indent(4) <<
" Triple: " << TargetOpts.
Triple <<
"\n";
502 Out.indent(4) <<
" CPU: " << TargetOpts.
CPU <<
"\n";
503 Out.indent(4) <<
" ABI: " << TargetOpts.
ABI <<
"\n";
506 Out.indent(4) <<
"Target features:\n";
517 bool Complain)
override {
518 Out.indent(2) <<
"Diagnostic options:\n";
519 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
520 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
521 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
522 #define VALUE_DIAGOPT(Name, Bits, Default) \
523 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
524 #include "clang/Basic/DiagnosticOptions.def"
526 Out.indent(4) <<
"Diagnostic flags:\n";
527 for (
const std::string &
Warning : DiagOpts->Warnings)
528 Out.indent(6) <<
"-W" << Warning <<
"\n";
529 for (
const std::string &
Remark : DiagOpts->Remarks)
530 Out.indent(6) <<
"-R" << Remark <<
"\n";
536 StringRef SpecificModuleCachePath,
537 bool Complain)
override {
538 Out.indent(2) <<
"Header search options:\n";
539 Out.indent(4) <<
"System root [-isysroot=]: '" << HSOpts.
Sysroot <<
"'\n";
540 Out.indent(4) <<
"Module Cache: '" << SpecificModuleCachePath <<
"'\n";
542 "Use builtin include directories [-nobuiltininc]");
544 "Use standard system include directories [-nostdinc]");
546 "Use standard C++ include directories [-nostdinc++]");
548 "Use libc++ (rather than libstdc++) [-stdlib=]");
554 std::string &SuggestedPredefines)
override {
555 Out.indent(2) <<
"Preprocessor options:\n";
557 "Uses compiler/target-specific predefines [-undef]");
559 "Uses detailed preprocessing record (for indexing)");
561 if (!PPOpts.
Macros.empty()) {
562 Out.indent(4) <<
"Predefined macros:\n";
565 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
573 Out <<
I->first <<
"\n";
579 void readModuleFileExtension(
581 Out.indent(2) <<
"Module file extension '"
586 Out.write_escaped(Metadata.
UserInfo);
597 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
599 if (!OutputFileName.empty() && OutputFileName !=
"-") {
601 OutFile.reset(
new llvm::raw_fd_ostream(OutputFileName.str(), EC,
602 llvm::sys::fs::F_Text));
604 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
606 Out <<
"Information for module file '" <<
getCurrentFile() <<
"':\n";
607 DumpModuleInfoListener Listener(Out);
628 RawLex.LexFromRawLexer(RawTok);
631 llvm::errs() <<
"\n";
632 RawLex.LexFromRawLexer(RawTok);
644 llvm::errs() <<
"\n";
686 bool BinaryMode =
true;
687 bool InvalidFile =
false;
692 const char *cur = Buffer->getBufferStart();
693 const char *
end = Buffer->getBufferEnd();
694 const char *next = (cur !=
end) ? cur + 1 : end;
699 if (end - cur > 256) end = cur + 256;
707 }
else if (*cur == 0x0A)
749 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.
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.
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.
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.
virtual std::unique_ptr< ASTConsumer > CreatePCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName, const std::string &OutputFileName, 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...
bool isAvailable() const
Determine whether this module is available for use within the current translation unit...
FrontendOptions & getFrontendOpts()
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.
static std::error_code addHeaderInclude(StringRef HeaderName, SmallVectorImpl< char > &Includes, const LangOptions &LangOpts, bool IsExternC)
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::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.
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 ...
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.
Cached information about one file (either on disk or in the virtual file system). ...
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.
std::unique_ptr< ASTConsumer > CreateASTPrinter(raw_ostream *OS, StringRef FilterString)
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.
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.
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...
std::unique_ptr< ASTConsumer > CreateASTViewer()
const PCHContainerWriter & getPCHContainerWriter() const
Return the appropriate PCHContainerWriter depending on the current CodeGenOptions.
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 > 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.
static 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 ...
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 > 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...
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 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...