ASTUnit.cpp revision 8c647deada0c0e8407b4ced00ff09be1261fe147
1ddb351dbec246cf1fab5ec20d2d5520909041de1Kristian Monsen//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===// 2c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott// 3c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott// The LLVM Compiler Infrastructure 4c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott// 5c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott// This file is distributed under the University of Illinois Open Source 6c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott// License. See LICENSE.TXT for details. 7c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott// 8c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott//===----------------------------------------------------------------------===// 9c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott// 103345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick// ASTUnit Implementation. 113345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick// 123345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick//===----------------------------------------------------------------------===// 133345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick 143345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick#include "clang/Frontend/ASTUnit.h" 15c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/AST/ASTContext.h" 16c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/AST/ASTConsumer.h" 17c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/AST/DeclVisitor.h" 18c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/AST/TypeOrdering.h" 19c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/AST/StmtVisitor.h" 20c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Driver/Compilation.h" 21c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Driver/Driver.h" 22c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Driver/Job.h" 23c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Driver/ArgList.h" 24c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Driver/Options.h" 25ddb351dbec246cf1fab5ec20d2d5520909041de1Kristian Monsen#include "clang/Driver/Tool.h" 26ddb351dbec246cf1fab5ec20d2d5520909041de1Kristian Monsen#include "clang/Frontend/CompilerInstance.h" 27ddb351dbec246cf1fab5ec20d2d5520909041de1Kristian Monsen#include "clang/Frontend/FrontendActions.h" 28ddb351dbec246cf1fab5ec20d2d5520909041de1Kristian Monsen#include "clang/Frontend/FrontendDiagnostic.h" 29c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Frontend/FrontendOptions.h" 30c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Frontend/Utils.h" 31c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Serialization/ASTReader.h" 32c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Serialization/ASTSerializationListener.h" 33c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Serialization/ASTWriter.h" 34c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Lex/HeaderSearch.h" 35c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Lex/Preprocessor.h" 36c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Basic/TargetOptions.h" 37c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Basic/TargetInfo.h" 38c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "clang/Basic/Diagnostic.h" 39c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "llvm/ADT/ArrayRef.h" 40c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "llvm/ADT/StringExtras.h" 41c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "llvm/ADT/StringSet.h" 42c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "llvm/Support/Atomic.h" 43c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "llvm/Support/MemoryBuffer.h" 44c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "llvm/Support/Host.h" 45c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "llvm/Support/Path.h" 46c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "llvm/Support/raw_ostream.h" 47c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "llvm/Support/Timer.h" 48c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include "llvm/Support/CrashRecoveryContext.h" 49c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include <cstdlib> 50c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include <cstdio> 51c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott#include <sys/stat.h> 52c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdochusing namespace clang; 53c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdoch 54c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdochusing llvm::TimeRecord; 55c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdoch 56c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdochnamespace { 57c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdoch class SimpleTimer { 58c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott bool WantTiming; 59c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott TimeRecord Start; 60c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott std::string Output; 61c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 62c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott public: 63c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) { 64c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdoch if (WantTiming) 65c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdoch Start = TimeRecord::getCurrentTime(); 66c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdoch } 67c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 68c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott void setOutput(const llvm::Twine &Output) { 693345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick if (WantTiming) 703345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick this->Output = Output.str(); 713345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick } 723345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick 733345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick ~SimpleTimer() { 74dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen if (WantTiming) { 753345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick TimeRecord Elapsed = TimeRecord::getCurrentTime(); 763345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick Elapsed -= Start; 773345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick llvm::errs() << Output << ':'; 783345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick Elapsed.print(Elapsed, llvm::errs()); 793345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick llvm::errs() << '\n'; 803345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick } 813345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick } 823345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick }; 833345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick} 843345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick 85c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott/// \brief After failing to build a precompiled preamble (due to 86c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott/// errors in the source that occurs in the preamble), the number of 87c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott/// reparses during which we'll skip even trying to precompile the 883345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick/// preamble. 893345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrickconst unsigned DefaultPreambleRebuildInterval = 5; 903345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick 913345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick/// \brief Tracks the number of ASTUnit objects that are currently active. 923345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick/// 93dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen/// Used for debugging purposes only. 943345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrickstatic llvm::sys::cas_flag ActiveASTUnitObjects; 953345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick 963345a6884c488ff3a535c2c9acdd33d74b37e311Iain MerrickASTUnit::ASTUnit(bool _MainFileIsAST) 973345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick : OnlyLocalDecls(false), CaptureDiagnostics(false), 983345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick MainFileIsAST(_MainFileIsAST), 993345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")), 1003345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick OwnsRemappedFileBuffers(true), 1013345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick NumStoredDiagnosticsFromDriver(0), 1023345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick ConcurrencyCheckValue(CheckUnlocked), 1033345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0), 1043345a6884c488ff3a535c2c9acdd33d74b37e311Iain Merrick ShouldCacheCodeCompletionResults(false), 105c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott CompletionCacheTopLevelHashValue(0), 106c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott PreambleTopLevelHashValue(0), 107c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott CurrentTopLevelHashValue(0), 108c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott UnsafeToFree(false) { 109c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott if (getenv("LIBCLANG_OBJTRACKING")) { 110c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott llvm::sys::AtomicIncrement(&ActiveASTUnitObjects); 111c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects); 112c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott } 113c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott} 114ddb351dbec246cf1fab5ec20d2d5520909041de1Kristian Monsen 115ddb351dbec246cf1fab5ec20d2d5520909041de1Kristian MonsenASTUnit::~ASTUnit() { 116c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott ConcurrencyCheckValue = CheckLocked; 117c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott CleanTemporaryFiles(); 118c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott if (!PreambleFile.empty()) 119c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott llvm::sys::Path(PreambleFile).eraseFromDisk(); 120c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 121c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott // Free the buffers associated with remapped files. We are required to 122c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott // perform this operation here because we explicitly request that the 123c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott // compiler instance *not* free these buffers for each invocation of the 124c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott // parser. 125c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott if (Invocation.getPtr() && OwnsRemappedFileBuffers) { 126c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 127c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott for (PreprocessorOptions::remapped_file_buffer_iterator 128c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott FB = PPOpts.remapped_file_buffer_begin(), 129c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott FBEnd = PPOpts.remapped_file_buffer_end(); 130c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott FB != FBEnd; 131c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott ++FB) 132c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott delete FB->second; 133c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott } 134c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 135c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott delete SavedMainFileBuffer; 136c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott delete PreambleBuffer; 137c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 138ddb351dbec246cf1fab5ec20d2d5520909041de1Kristian Monsen ClearCachedCompletionResults(); 139ddb351dbec246cf1fab5ec20d2d5520909041de1Kristian Monsen 140ddb351dbec246cf1fab5ec20d2d5520909041de1Kristian Monsen if (getenv("LIBCLANG_OBJTRACKING")) { 141ddb351dbec246cf1fab5ec20d2d5520909041de1Kristian Monsen llvm::sys::AtomicDecrement(&ActiveASTUnitObjects); 142ddb351dbec246cf1fab5ec20d2d5520909041de1Kristian Monsen fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects); 143ddb351dbec246cf1fab5ec20d2d5520909041de1Kristian Monsen } 144c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott} 145c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 146c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scottvoid ASTUnit::CleanTemporaryFiles() { 147c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I) 148c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott TemporaryFiles[I].eraseFromDisk(); 149c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott TemporaryFiles.clear(); 150c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott} 151c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 152c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott/// \brief Determine the set of code-completion contexts in which this 153c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott/// declaration should be shown. 154c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scottstatic unsigned getDeclShowContexts(NamedDecl *ND, 155c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott const LangOptions &LangOpts, 156c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott bool &IsNestedNameSpecifier) { 157c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott IsNestedNameSpecifier = false; 158c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 159c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott if (isa<UsingShadowDecl>(ND)) 160c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl()); 161c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott if (!ND) 162c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott return 0; 163c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 164dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen unsigned Contexts = 0; 165dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) || 166dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) { 167dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen // Types can appear in these contexts. 168dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen if (LangOpts.CPlusPlus || !isa<TagDecl>(ND)) 169dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1)) 170dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1)) 171dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1)) 172dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen | (1 << (CodeCompletionContext::CCC_Statement - 1)) 173dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen | (1 << (CodeCompletionContext::CCC_Type - 1)) 174dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1)); 175dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen 176c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott // In C++, types can appear in expressions contexts (for functional casts). 177c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott if (LangOpts.CPlusPlus) 178c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdoch Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1)); 179c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdoch 180c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdoch // In Objective-C, message sends can send interfaces. In Objective-C++, 181c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdoch // all types are available due to functional casts. 182c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND)) 183c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)); 184c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 185c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott // Deal with tag names. 186c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott if (isa<EnumDecl>(ND)) { 187c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1)); 188c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 189c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott // Part of the nested-name-specifier in C++0x. 190c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott if (LangOpts.CPlusPlus0x) 1914a5e2dc747d50c653511c68ccb2cfbfb740bd5a7Ben Murdoch IsNestedNameSpecifier = true; 192c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) { 193c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott if (Record->isUnion()) 1944a5e2dc747d50c653511c68ccb2cfbfb740bd5a7Ben Murdoch Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1)); 1954a5e2dc747d50c653511c68ccb2cfbfb740bd5a7Ben Murdoch else 1964a5e2dc747d50c653511c68ccb2cfbfb740bd5a7Ben Murdoch Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1)); 197c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 198c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott if (LangOpts.CPlusPlus) 199c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott IsNestedNameSpecifier = true; 200c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott } else if (isa<ClassTemplateDecl>(ND)) 201c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott IsNestedNameSpecifier = true; 202c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 203c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott // Values can appear in these contexts. 204c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdoch Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1)) 205c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdoch | (1 << (CodeCompletionContext::CCC_Expression - 1)) 206c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdoch | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1)) 207c407dc5cd9bdc5668497f21b26b09d988ab439deBen Murdoch | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)); 208c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott } else if (isa<ObjCProtocolDecl>(ND)) { 209c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1)); 210c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) { 211c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1)); 212c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 213c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott // Part of the nested-name-specifier. 214c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott IsNestedNameSpecifier = true; 215c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott } 216c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 217c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott return Contexts; 218c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott} 219c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 220c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scottvoid ASTUnit::CacheCodeCompletionResults() { 221c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott if (!TheSema) 222c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott return; 223c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 224c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott SimpleTimer Timer(WantTiming); 225c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott Timer.setOutput("Cache global code completions for " + getMainFileName()); 226c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 2274a5e2dc747d50c653511c68ccb2cfbfb740bd5a7Ben Murdoch // Clear out the previous results. 228c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott ClearCachedCompletionResults(); 229c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 2304a5e2dc747d50c653511c68ccb2cfbfb740bd5a7Ben Murdoch // Gather the set of global code completions. 2314a5e2dc747d50c653511c68ccb2cfbfb740bd5a7Ben Murdoch typedef CodeCompletionResult Result; 232c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott llvm::SmallVector<Result, 8> Results; 233c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott CachedCompletionAllocator = new GlobalCodeCompletionAllocator; 234c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results); 235c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott 236dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen // Translate global code completions into cached completions. 237dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen llvm::DenseMap<CanQualType, unsigned> CompletionTypes; 238dc0f95d653279beabeb9817299e2902918ba123eKristian Monsen 239c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott for (unsigned I = 0, N = Results.size(); I != N; ++I) { 240c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott switch (Results[I].Kind) { 241c7f5f8508d98d5952d42ed7648c2a8f30a4da156Patrick Scott case Result::RK_Declaration: { 242 bool IsNestedNameSpecifier = false; 243 CachedCodeCompletionResult CachedResult; 244 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema, 245 *CachedCompletionAllocator); 246 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration, 247 Ctx->getLangOptions(), 248 IsNestedNameSpecifier); 249 CachedResult.Priority = Results[I].Priority; 250 CachedResult.Kind = Results[I].CursorKind; 251 CachedResult.Availability = Results[I].Availability; 252 253 // Keep track of the type of this completion in an ASTContext-agnostic 254 // way. 255 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration); 256 if (UsageType.isNull()) { 257 CachedResult.TypeClass = STC_Void; 258 CachedResult.Type = 0; 259 } else { 260 CanQualType CanUsageType 261 = Ctx->getCanonicalType(UsageType.getUnqualifiedType()); 262 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType); 263 264 // Determine whether we have already seen this type. If so, we save 265 // ourselves the work of formatting the type string by using the 266 // temporary, CanQualType-based hash table to find the associated value. 267 unsigned &TypeValue = CompletionTypes[CanUsageType]; 268 if (TypeValue == 0) { 269 TypeValue = CompletionTypes.size(); 270 CachedCompletionTypes[QualType(CanUsageType).getAsString()] 271 = TypeValue; 272 } 273 274 CachedResult.Type = TypeValue; 275 } 276 277 CachedCompletionResults.push_back(CachedResult); 278 279 /// Handle nested-name-specifiers in C++. 280 if (TheSema->Context.getLangOptions().CPlusPlus && 281 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) { 282 // The contexts in which a nested-name-specifier can appear in C++. 283 unsigned NNSContexts 284 = (1 << (CodeCompletionContext::CCC_TopLevel - 1)) 285 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1)) 286 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1)) 287 | (1 << (CodeCompletionContext::CCC_Statement - 1)) 288 | (1 << (CodeCompletionContext::CCC_Expression - 1)) 289 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)) 290 | (1 << (CodeCompletionContext::CCC_EnumTag - 1)) 291 | (1 << (CodeCompletionContext::CCC_UnionTag - 1)) 292 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1)) 293 | (1 << (CodeCompletionContext::CCC_Type - 1)) 294 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1)) 295 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1)); 296 297 if (isa<NamespaceDecl>(Results[I].Declaration) || 298 isa<NamespaceAliasDecl>(Results[I].Declaration)) 299 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1)); 300 301 if (unsigned RemainingContexts 302 = NNSContexts & ~CachedResult.ShowInContexts) { 303 // If there any contexts where this completion can be a 304 // nested-name-specifier but isn't already an option, create a 305 // nested-name-specifier completion. 306 Results[I].StartsNestedNameSpecifier = true; 307 CachedResult.Completion 308 = Results[I].CreateCodeCompletionString(*TheSema, 309 *CachedCompletionAllocator); 310 CachedResult.ShowInContexts = RemainingContexts; 311 CachedResult.Priority = CCP_NestedNameSpecifier; 312 CachedResult.TypeClass = STC_Void; 313 CachedResult.Type = 0; 314 CachedCompletionResults.push_back(CachedResult); 315 } 316 } 317 break; 318 } 319 320 case Result::RK_Keyword: 321 case Result::RK_Pattern: 322 // Ignore keywords and patterns; we don't care, since they are so 323 // easily regenerated. 324 break; 325 326 case Result::RK_Macro: { 327 CachedCodeCompletionResult CachedResult; 328 CachedResult.Completion 329 = Results[I].CreateCodeCompletionString(*TheSema, 330 *CachedCompletionAllocator); 331 CachedResult.ShowInContexts 332 = (1 << (CodeCompletionContext::CCC_TopLevel - 1)) 333 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1)) 334 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1)) 335 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1)) 336 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1)) 337 | (1 << (CodeCompletionContext::CCC_Statement - 1)) 338 | (1 << (CodeCompletionContext::CCC_Expression - 1)) 339 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)) 340 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1)) 341 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1)) 342 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1)) 343 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1)); 344 345 CachedResult.Priority = Results[I].Priority; 346 CachedResult.Kind = Results[I].CursorKind; 347 CachedResult.Availability = Results[I].Availability; 348 CachedResult.TypeClass = STC_Void; 349 CachedResult.Type = 0; 350 CachedCompletionResults.push_back(CachedResult); 351 break; 352 } 353 } 354 } 355 356 // Save the current top-level hash value. 357 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue; 358} 359 360void ASTUnit::ClearCachedCompletionResults() { 361 CachedCompletionResults.clear(); 362 CachedCompletionTypes.clear(); 363 CachedCompletionAllocator = 0; 364} 365 366namespace { 367 368/// \brief Gathers information from ASTReader that will be used to initialize 369/// a Preprocessor. 370class ASTInfoCollector : public ASTReaderListener { 371 LangOptions &LangOpt; 372 HeaderSearch &HSI; 373 std::string &TargetTriple; 374 std::string &Predefines; 375 unsigned &Counter; 376 377 unsigned NumHeaderInfos; 378 379public: 380 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI, 381 std::string &TargetTriple, std::string &Predefines, 382 unsigned &Counter) 383 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple), 384 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {} 385 386 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) { 387 LangOpt = LangOpts; 388 return false; 389 } 390 391 virtual bool ReadTargetTriple(llvm::StringRef Triple) { 392 TargetTriple = Triple; 393 return false; 394 } 395 396 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers, 397 llvm::StringRef OriginalFileName, 398 std::string &SuggestedPredefines, 399 FileManager &FileMgr) { 400 Predefines = Buffers[0].Data; 401 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) { 402 Predefines += Buffers[I].Data; 403 } 404 return false; 405 } 406 407 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) { 408 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++); 409 } 410 411 virtual void ReadCounter(unsigned Value) { 412 Counter = Value; 413 } 414}; 415 416class StoredDiagnosticClient : public DiagnosticClient { 417 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags; 418 419public: 420 explicit StoredDiagnosticClient( 421 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags) 422 : StoredDiags(StoredDiags) { } 423 424 virtual void HandleDiagnostic(Diagnostic::Level Level, 425 const DiagnosticInfo &Info); 426}; 427 428/// \brief RAII object that optionally captures diagnostics, if 429/// there is no diagnostic client to capture them already. 430class CaptureDroppedDiagnostics { 431 Diagnostic &Diags; 432 StoredDiagnosticClient Client; 433 DiagnosticClient *PreviousClient; 434 435public: 436 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags, 437 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags) 438 : Diags(Diags), Client(StoredDiags), PreviousClient(0) 439 { 440 if (RequestCapture || Diags.getClient() == 0) { 441 PreviousClient = Diags.takeClient(); 442 Diags.setClient(&Client); 443 } 444 } 445 446 ~CaptureDroppedDiagnostics() { 447 if (Diags.getClient() == &Client) { 448 Diags.takeClient(); 449 Diags.setClient(PreviousClient); 450 } 451 } 452}; 453 454} // anonymous namespace 455 456void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level, 457 const DiagnosticInfo &Info) { 458 // Default implementation (Warnings/errors count). 459 DiagnosticClient::HandleDiagnostic(Level, Info); 460 461 StoredDiags.push_back(StoredDiagnostic(Level, Info)); 462} 463 464const std::string &ASTUnit::getOriginalSourceFileName() { 465 return OriginalSourceFile; 466} 467 468const std::string &ASTUnit::getASTFileName() { 469 assert(isMainFileAST() && "Not an ASTUnit from an AST file!"); 470 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName(); 471} 472 473llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename, 474 std::string *ErrorStr) { 475 assert(FileMgr); 476 return FileMgr->getBufferForFile(Filename, ErrorStr); 477} 478 479/// \brief Configure the diagnostics object for use with ASTUnit. 480void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags, 481 const char **ArgBegin, const char **ArgEnd, 482 ASTUnit &AST, bool CaptureDiagnostics) { 483 if (!Diags.getPtr()) { 484 // No diagnostics engine was provided, so create our own diagnostics object 485 // with the default options. 486 DiagnosticOptions DiagOpts; 487 DiagnosticClient *Client = 0; 488 if (CaptureDiagnostics) 489 Client = new StoredDiagnosticClient(AST.StoredDiagnostics); 490 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin, 491 ArgBegin, Client); 492 } else if (CaptureDiagnostics) { 493 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics)); 494 } 495} 496 497ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename, 498 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 499 const FileSystemOptions &FileSystemOpts, 500 bool OnlyLocalDecls, 501 RemappedFile *RemappedFiles, 502 unsigned NumRemappedFiles, 503 bool CaptureDiagnostics) { 504 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true)); 505 506 // Recover resources if we crash before exiting this method. 507 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> 508 ASTUnitCleanup(AST.get()); 509 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic, 510 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> > 511 DiagCleanup(Diags.getPtr()); 512 513 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics); 514 515 AST->OnlyLocalDecls = OnlyLocalDecls; 516 AST->CaptureDiagnostics = CaptureDiagnostics; 517 AST->Diagnostics = Diags; 518 AST->FileMgr = new FileManager(FileSystemOpts); 519 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), 520 AST->getFileManager()); 521 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager())); 522 523 for (unsigned I = 0; I != NumRemappedFiles; ++I) { 524 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second; 525 if (const llvm::MemoryBuffer * 526 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) { 527 // Create the file entry for the file that we're mapping from. 528 const FileEntry *FromFile 529 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first, 530 memBuf->getBufferSize(), 531 0); 532 if (!FromFile) { 533 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file) 534 << RemappedFiles[I].first; 535 delete memBuf; 536 continue; 537 } 538 539 // Override the contents of the "from" file with the contents of 540 // the "to" file. 541 AST->getSourceManager().overrideFileContents(FromFile, memBuf); 542 543 } else { 544 const char *fname = fileOrBuf.get<const char *>(); 545 const FileEntry *ToFile = AST->FileMgr->getFile(fname); 546 if (!ToFile) { 547 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file) 548 << RemappedFiles[I].first << fname; 549 continue; 550 } 551 552 // Create the file entry for the file that we're mapping from. 553 const FileEntry *FromFile 554 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first, 555 ToFile->getSize(), 556 0); 557 if (!FromFile) { 558 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file) 559 << RemappedFiles[I].first; 560 delete memBuf; 561 continue; 562 } 563 564 // Override the contents of the "from" file with the contents of 565 // the "to" file. 566 AST->getSourceManager().overrideFileContents(FromFile, ToFile); 567 } 568 } 569 570 // Gather Info for preprocessor construction later on. 571 572 LangOptions LangInfo; 573 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get(); 574 std::string TargetTriple; 575 std::string Predefines; 576 unsigned Counter; 577 578 llvm::OwningPtr<ASTReader> Reader; 579 580 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(), 581 AST->getDiagnostics())); 582 583 // Recover resources if we crash before exiting this method. 584 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader> 585 ReaderCleanup(Reader.get()); 586 587 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple, 588 Predefines, Counter)); 589 590 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) { 591 case ASTReader::Success: 592 break; 593 594 case ASTReader::Failure: 595 case ASTReader::IgnorePCH: 596 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch); 597 return NULL; 598 } 599 600 AST->OriginalSourceFile = Reader->getOriginalSourceFile(); 601 602 // AST file loaded successfully. Now create the preprocessor. 603 604 // Get information about the target being compiled for. 605 // 606 // FIXME: This is broken, we should store the TargetOptions in the AST file. 607 TargetOptions TargetOpts; 608 TargetOpts.ABI = ""; 609 TargetOpts.CXXABI = ""; 610 TargetOpts.CPU = ""; 611 TargetOpts.Features.clear(); 612 TargetOpts.Triple = TargetTriple; 613 AST->Target = TargetInfo::CreateTargetInfo(AST->getDiagnostics(), 614 TargetOpts); 615 AST->PP = new Preprocessor(AST->getDiagnostics(), LangInfo, *AST->Target, 616 AST->getSourceManager(), HeaderInfo); 617 Preprocessor &PP = *AST->PP; 618 619 PP.setPredefines(Reader->getSuggestedPredefines()); 620 PP.setCounterValue(Counter); 621 Reader->setPreprocessor(PP); 622 623 // Create and initialize the ASTContext. 624 625 AST->Ctx = new ASTContext(LangInfo, 626 AST->getSourceManager(), 627 *AST->Target, 628 PP.getIdentifierTable(), 629 PP.getSelectorTable(), 630 PP.getBuiltinInfo(), 631 /* size_reserve = */0); 632 ASTContext &Context = *AST->Ctx; 633 634 Reader->InitializeContext(Context); 635 636 // Attach the AST reader to the AST context as an external AST 637 // source, so that declarations will be deserialized from the 638 // AST file as needed. 639 ASTReader *ReaderPtr = Reader.get(); 640 llvm::OwningPtr<ExternalASTSource> Source(Reader.take()); 641 642 // Unregister the cleanup for ASTReader. It will get cleaned up 643 // by the ASTUnit cleanup. 644 ReaderCleanup.unregister(); 645 646 Context.setExternalSource(Source); 647 648 // Create an AST consumer, even though it isn't used. 649 AST->Consumer.reset(new ASTConsumer); 650 651 // Create a semantic analysis object and tell the AST reader about it. 652 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer)); 653 AST->TheSema->Initialize(); 654 ReaderPtr->InitializeSema(*AST->TheSema); 655 656 return AST.take(); 657} 658 659namespace { 660 661/// \brief Preprocessor callback class that updates a hash value with the names 662/// of all macros that have been defined by the translation unit. 663class MacroDefinitionTrackerPPCallbacks : public PPCallbacks { 664 unsigned &Hash; 665 666public: 667 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { } 668 669 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) { 670 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash); 671 } 672}; 673 674/// \brief Add the given declaration to the hash of all top-level entities. 675void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) { 676 if (!D) 677 return; 678 679 DeclContext *DC = D->getDeclContext(); 680 if (!DC) 681 return; 682 683 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit())) 684 return; 685 686 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) { 687 if (ND->getIdentifier()) 688 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash); 689 else if (DeclarationName Name = ND->getDeclName()) { 690 std::string NameStr = Name.getAsString(); 691 Hash = llvm::HashString(NameStr, Hash); 692 } 693 return; 694 } 695 696 if (ObjCForwardProtocolDecl *Forward 697 = dyn_cast<ObjCForwardProtocolDecl>(D)) { 698 for (ObjCForwardProtocolDecl::protocol_iterator 699 P = Forward->protocol_begin(), 700 PEnd = Forward->protocol_end(); 701 P != PEnd; ++P) 702 AddTopLevelDeclarationToHash(*P, Hash); 703 return; 704 } 705 706 if (ObjCClassDecl *Class = llvm::dyn_cast<ObjCClassDecl>(D)) { 707 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end(); 708 I != IEnd; ++I) 709 AddTopLevelDeclarationToHash(I->getInterface(), Hash); 710 return; 711 } 712} 713 714class TopLevelDeclTrackerConsumer : public ASTConsumer { 715 ASTUnit &Unit; 716 unsigned &Hash; 717 718public: 719 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash) 720 : Unit(_Unit), Hash(Hash) { 721 Hash = 0; 722 } 723 724 void HandleTopLevelDecl(DeclGroupRef D) { 725 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) { 726 Decl *D = *it; 727 // FIXME: Currently ObjC method declarations are incorrectly being 728 // reported as top-level declarations, even though their DeclContext 729 // is the containing ObjC @interface/@implementation. This is a 730 // fundamental problem in the parser right now. 731 if (isa<ObjCMethodDecl>(D)) 732 continue; 733 734 AddTopLevelDeclarationToHash(D, Hash); 735 Unit.addTopLevelDecl(D); 736 } 737 } 738 739 // We're not interested in "interesting" decls. 740 void HandleInterestingDecl(DeclGroupRef) {} 741}; 742 743class TopLevelDeclTrackerAction : public ASTFrontendAction { 744public: 745 ASTUnit &Unit; 746 747 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI, 748 llvm::StringRef InFile) { 749 CI.getPreprocessor().addPPCallbacks( 750 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue())); 751 return new TopLevelDeclTrackerConsumer(Unit, 752 Unit.getCurrentTopLevelHashValue()); 753 } 754 755public: 756 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {} 757 758 virtual bool hasCodeCompletionSupport() const { return false; } 759 virtual bool usesCompleteTranslationUnit() { 760 return Unit.isCompleteTranslationUnit(); 761 } 762}; 763 764class PrecompilePreambleConsumer : public PCHGenerator, 765 public ASTSerializationListener { 766 ASTUnit &Unit; 767 unsigned &Hash; 768 std::vector<Decl *> TopLevelDecls; 769 770public: 771 PrecompilePreambleConsumer(ASTUnit &Unit, 772 const Preprocessor &PP, bool Chaining, 773 const char *isysroot, llvm::raw_ostream *Out) 774 : PCHGenerator(PP, "", Chaining, isysroot, Out), Unit(Unit), 775 Hash(Unit.getCurrentTopLevelHashValue()) { 776 Hash = 0; 777 } 778 779 virtual void HandleTopLevelDecl(DeclGroupRef D) { 780 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) { 781 Decl *D = *it; 782 // FIXME: Currently ObjC method declarations are incorrectly being 783 // reported as top-level declarations, even though their DeclContext 784 // is the containing ObjC @interface/@implementation. This is a 785 // fundamental problem in the parser right now. 786 if (isa<ObjCMethodDecl>(D)) 787 continue; 788 AddTopLevelDeclarationToHash(D, Hash); 789 TopLevelDecls.push_back(D); 790 } 791 } 792 793 virtual void HandleTranslationUnit(ASTContext &Ctx) { 794 PCHGenerator::HandleTranslationUnit(Ctx); 795 if (!Unit.getDiagnostics().hasErrorOccurred()) { 796 // Translate the top-level declarations we captured during 797 // parsing into declaration IDs in the precompiled 798 // preamble. This will allow us to deserialize those top-level 799 // declarations when requested. 800 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) 801 Unit.addTopLevelDeclFromPreamble( 802 getWriter().getDeclID(TopLevelDecls[I])); 803 } 804 } 805 806 virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity, 807 uint64_t Offset) { 808 Unit.addPreprocessedEntityFromPreamble(Offset); 809 } 810 811 virtual ASTSerializationListener *GetASTSerializationListener() { 812 return this; 813 } 814}; 815 816class PrecompilePreambleAction : public ASTFrontendAction { 817 ASTUnit &Unit; 818 819public: 820 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {} 821 822 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI, 823 llvm::StringRef InFile) { 824 std::string Sysroot; 825 std::string OutputFile; 826 llvm::raw_ostream *OS = 0; 827 bool Chaining; 828 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot, 829 OutputFile, 830 OS, Chaining)) 831 return 0; 832 833 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ? 834 Sysroot.c_str() : 0; 835 CI.getPreprocessor().addPPCallbacks( 836 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue())); 837 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining, 838 isysroot, OS); 839 } 840 841 virtual bool hasCodeCompletionSupport() const { return false; } 842 virtual bool hasASTFileSupport() const { return false; } 843 virtual bool usesCompleteTranslationUnit() { return false; } 844}; 845 846} 847 848/// Parse the source file into a translation unit using the given compiler 849/// invocation, replacing the current translation unit. 850/// 851/// \returns True if a failure occurred that causes the ASTUnit not to 852/// contain any translation-unit information, false otherwise. 853bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) { 854 delete SavedMainFileBuffer; 855 SavedMainFileBuffer = 0; 856 857 if (!Invocation) { 858 delete OverrideMainBuffer; 859 return true; 860 } 861 862 // Create the compiler instance to use for building the AST. 863 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance()); 864 865 // Recover resources if we crash before exiting this method. 866 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> 867 CICleanup(Clang.get()); 868 869 Clang->setInvocation(&*Invocation); 870 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second; 871 872 // Set up diagnostics, capturing any diagnostics that would 873 // otherwise be dropped. 874 Clang->setDiagnostics(&getDiagnostics()); 875 876 // Create the target instance. 877 Clang->getTargetOpts().Features = TargetFeatures; 878 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(), 879 Clang->getTargetOpts())); 880 if (!Clang->hasTarget()) { 881 delete OverrideMainBuffer; 882 return true; 883 } 884 885 // Inform the target of the language options. 886 // 887 // FIXME: We shouldn't need to do this, the target should be immutable once 888 // created. This complexity should be lifted elsewhere. 889 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts()); 890 891 assert(Clang->getFrontendOpts().Inputs.size() == 1 && 892 "Invocation must have exactly one source file!"); 893 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST && 894 "FIXME: AST inputs not yet supported here!"); 895 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR && 896 "IR inputs not support here!"); 897 898 // Configure the various subsystems. 899 // FIXME: Should we retain the previous file manager? 900 FileSystemOpts = Clang->getFileSystemOpts(); 901 FileMgr = new FileManager(FileSystemOpts); 902 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr); 903 TheSema.reset(); 904 Ctx = 0; 905 PP = 0; 906 907 // Clear out old caches and data. 908 TopLevelDecls.clear(); 909 PreprocessedEntities.clear(); 910 CleanTemporaryFiles(); 911 PreprocessedEntitiesByFile.clear(); 912 913 if (!OverrideMainBuffer) { 914 StoredDiagnostics.erase( 915 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver, 916 StoredDiagnostics.end()); 917 TopLevelDeclsInPreamble.clear(); 918 PreprocessedEntitiesInPreamble.clear(); 919 } 920 921 // Create a file manager object to provide access to and cache the filesystem. 922 Clang->setFileManager(&getFileManager()); 923 924 // Create the source manager. 925 Clang->setSourceManager(&getSourceManager()); 926 927 // If the main file has been overridden due to the use of a preamble, 928 // make that override happen and introduce the preamble. 929 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts(); 930 std::string PriorImplicitPCHInclude; 931 if (OverrideMainBuffer) { 932 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer); 933 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size(); 934 PreprocessorOpts.PrecompiledPreambleBytes.second 935 = PreambleEndsAtStartOfLine; 936 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude; 937 PreprocessorOpts.ImplicitPCHInclude = PreambleFile; 938 PreprocessorOpts.DisablePCHValidation = true; 939 940 // The stored diagnostic has the old source manager in it; update 941 // the locations to refer into the new source manager. Since we've 942 // been careful to make sure that the source manager's state 943 // before and after are identical, so that we can reuse the source 944 // location itself. 945 for (unsigned I = NumStoredDiagnosticsFromDriver, 946 N = StoredDiagnostics.size(); 947 I < N; ++I) { 948 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), 949 getSourceManager()); 950 StoredDiagnostics[I].setLocation(Loc); 951 } 952 953 // Keep track of the override buffer; 954 SavedMainFileBuffer = OverrideMainBuffer; 955 } else { 956 PreprocessorOpts.PrecompiledPreambleBytes.first = 0; 957 PreprocessorOpts.PrecompiledPreambleBytes.second = false; 958 } 959 960 llvm::OwningPtr<TopLevelDeclTrackerAction> Act( 961 new TopLevelDeclTrackerAction(*this)); 962 963 // Recover resources if we crash before exiting this method. 964 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction> 965 ActCleanup(Act.get()); 966 967 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second, 968 Clang->getFrontendOpts().Inputs[0].first)) 969 goto error; 970 971 Act->Execute(); 972 973 // Steal the created target, context, and preprocessor. 974 TheSema.reset(Clang->takeSema()); 975 Consumer.reset(Clang->takeASTConsumer()); 976 Ctx = &Clang->getASTContext(); 977 PP = &Clang->getPreprocessor(); 978 Clang->setSourceManager(0); 979 Clang->setFileManager(0); 980 Target = &Clang->getTarget(); 981 982 Act->EndSourceFile(); 983 984 // Remove the overridden buffer we used for the preamble. 985 if (OverrideMainBuffer) { 986 PreprocessorOpts.eraseRemappedFile( 987 PreprocessorOpts.remapped_file_buffer_end() - 1); 988 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude; 989 } 990 991 return false; 992 993error: 994 // Remove the overridden buffer we used for the preamble. 995 if (OverrideMainBuffer) { 996 PreprocessorOpts.eraseRemappedFile( 997 PreprocessorOpts.remapped_file_buffer_end() - 1); 998 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude; 999 delete OverrideMainBuffer; 1000 SavedMainFileBuffer = 0; 1001 } 1002 1003 StoredDiagnostics.clear(); 1004 return true; 1005} 1006 1007/// \brief Simple function to retrieve a path for a preamble precompiled header. 1008static std::string GetPreamblePCHPath() { 1009 // FIXME: This is lame; sys::Path should provide this function (in particular, 1010 // it should know how to find the temporary files dir). 1011 // FIXME: This is really lame. I copied this code from the Driver! 1012 // FIXME: This is a hack so that we can override the preamble file during 1013 // crash-recovery testing, which is the only case where the preamble files 1014 // are not necessarily cleaned up. 1015 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE"); 1016 if (TmpFile) 1017 return TmpFile; 1018 1019 std::string Error; 1020 const char *TmpDir = ::getenv("TMPDIR"); 1021 if (!TmpDir) 1022 TmpDir = ::getenv("TEMP"); 1023 if (!TmpDir) 1024 TmpDir = ::getenv("TMP"); 1025#ifdef LLVM_ON_WIN32 1026 if (!TmpDir) 1027 TmpDir = ::getenv("USERPROFILE"); 1028#endif 1029 if (!TmpDir) 1030 TmpDir = "/tmp"; 1031 llvm::sys::Path P(TmpDir); 1032 P.createDirectoryOnDisk(true); 1033 P.appendComponent("preamble"); 1034 P.appendSuffix("pch"); 1035 if (P.createTemporaryFileOnDisk()) 1036 return std::string(); 1037 1038 return P.str(); 1039} 1040 1041/// \brief Compute the preamble for the main file, providing the source buffer 1042/// that corresponds to the main file along with a pair (bytes, start-of-line) 1043/// that describes the preamble. 1044std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > 1045ASTUnit::ComputePreamble(CompilerInvocation &Invocation, 1046 unsigned MaxLines, bool &CreatedBuffer) { 1047 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts(); 1048 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts(); 1049 CreatedBuffer = false; 1050 1051 // Try to determine if the main file has been remapped, either from the 1052 // command line (to another file) or directly through the compiler invocation 1053 // (to a memory buffer). 1054 llvm::MemoryBuffer *Buffer = 0; 1055 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second); 1056 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) { 1057 // Check whether there is a file-file remapping of the main file 1058 for (PreprocessorOptions::remapped_file_iterator 1059 M = PreprocessorOpts.remapped_file_begin(), 1060 E = PreprocessorOpts.remapped_file_end(); 1061 M != E; 1062 ++M) { 1063 llvm::sys::PathWithStatus MPath(M->first); 1064 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) { 1065 if (MainFileStatus->uniqueID == MStatus->uniqueID) { 1066 // We found a remapping. Try to load the resulting, remapped source. 1067 if (CreatedBuffer) { 1068 delete Buffer; 1069 CreatedBuffer = false; 1070 } 1071 1072 Buffer = getBufferForFile(M->second); 1073 if (!Buffer) 1074 return std::make_pair((llvm::MemoryBuffer*)0, 1075 std::make_pair(0, true)); 1076 CreatedBuffer = true; 1077 } 1078 } 1079 } 1080 1081 // Check whether there is a file-buffer remapping. It supercedes the 1082 // file-file remapping. 1083 for (PreprocessorOptions::remapped_file_buffer_iterator 1084 M = PreprocessorOpts.remapped_file_buffer_begin(), 1085 E = PreprocessorOpts.remapped_file_buffer_end(); 1086 M != E; 1087 ++M) { 1088 llvm::sys::PathWithStatus MPath(M->first); 1089 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) { 1090 if (MainFileStatus->uniqueID == MStatus->uniqueID) { 1091 // We found a remapping. 1092 if (CreatedBuffer) { 1093 delete Buffer; 1094 CreatedBuffer = false; 1095 } 1096 1097 Buffer = const_cast<llvm::MemoryBuffer *>(M->second); 1098 } 1099 } 1100 } 1101 } 1102 1103 // If the main source file was not remapped, load it now. 1104 if (!Buffer) { 1105 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second); 1106 if (!Buffer) 1107 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true)); 1108 1109 CreatedBuffer = true; 1110 } 1111 1112 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines)); 1113} 1114 1115static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old, 1116 unsigned NewSize, 1117 llvm::StringRef NewName) { 1118 llvm::MemoryBuffer *Result 1119 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName); 1120 memcpy(const_cast<char*>(Result->getBufferStart()), 1121 Old->getBufferStart(), Old->getBufferSize()); 1122 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(), 1123 ' ', NewSize - Old->getBufferSize() - 1); 1124 const_cast<char*>(Result->getBufferEnd())[-1] = '\n'; 1125 1126 return Result; 1127} 1128 1129/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing 1130/// the source file. 1131/// 1132/// This routine will compute the preamble of the main source file. If a 1133/// non-trivial preamble is found, it will precompile that preamble into a 1134/// precompiled header so that the precompiled preamble can be used to reduce 1135/// reparsing time. If a precompiled preamble has already been constructed, 1136/// this routine will determine if it is still valid and, if so, avoid 1137/// rebuilding the precompiled preamble. 1138/// 1139/// \param AllowRebuild When true (the default), this routine is 1140/// allowed to rebuild the precompiled preamble if it is found to be 1141/// out-of-date. 1142/// 1143/// \param MaxLines When non-zero, the maximum number of lines that 1144/// can occur within the preamble. 1145/// 1146/// \returns If the precompiled preamble can be used, returns a newly-allocated 1147/// buffer that should be used in place of the main file when doing so. 1148/// Otherwise, returns a NULL pointer. 1149llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble( 1150 CompilerInvocation PreambleInvocation, 1151 bool AllowRebuild, 1152 unsigned MaxLines) { 1153 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts(); 1154 PreprocessorOptions &PreprocessorOpts 1155 = PreambleInvocation.getPreprocessorOpts(); 1156 1157 bool CreatedPreambleBuffer = false; 1158 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble 1159 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer); 1160 1161 // If ComputePreamble() Take ownership of the 1162 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer; 1163 if (CreatedPreambleBuffer) 1164 OwnedPreambleBuffer.reset(NewPreamble.first); 1165 1166 if (!NewPreamble.second.first) { 1167 // We couldn't find a preamble in the main source. Clear out the current 1168 // preamble, if we have one. It's obviously no good any more. 1169 Preamble.clear(); 1170 if (!PreambleFile.empty()) { 1171 llvm::sys::Path(PreambleFile).eraseFromDisk(); 1172 PreambleFile.clear(); 1173 } 1174 1175 // The next time we actually see a preamble, precompile it. 1176 PreambleRebuildCounter = 1; 1177 return 0; 1178 } 1179 1180 if (!Preamble.empty()) { 1181 // We've previously computed a preamble. Check whether we have the same 1182 // preamble now that we did before, and that there's enough space in 1183 // the main-file buffer within the precompiled preamble to fit the 1184 // new main file. 1185 if (Preamble.size() == NewPreamble.second.first && 1186 PreambleEndsAtStartOfLine == NewPreamble.second.second && 1187 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 && 1188 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(), 1189 NewPreamble.second.first) == 0) { 1190 // The preamble has not changed. We may be able to re-use the precompiled 1191 // preamble. 1192 1193 // Check that none of the files used by the preamble have changed. 1194 bool AnyFileChanged = false; 1195 1196 // First, make a record of those files that have been overridden via 1197 // remapping or unsaved_files. 1198 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles; 1199 for (PreprocessorOptions::remapped_file_iterator 1200 R = PreprocessorOpts.remapped_file_begin(), 1201 REnd = PreprocessorOpts.remapped_file_end(); 1202 !AnyFileChanged && R != REnd; 1203 ++R) { 1204 struct stat StatBuf; 1205 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) { 1206 // If we can't stat the file we're remapping to, assume that something 1207 // horrible happened. 1208 AnyFileChanged = true; 1209 break; 1210 } 1211 1212 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size, 1213 StatBuf.st_mtime); 1214 } 1215 for (PreprocessorOptions::remapped_file_buffer_iterator 1216 R = PreprocessorOpts.remapped_file_buffer_begin(), 1217 REnd = PreprocessorOpts.remapped_file_buffer_end(); 1218 !AnyFileChanged && R != REnd; 1219 ++R) { 1220 // FIXME: Should we actually compare the contents of file->buffer 1221 // remappings? 1222 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(), 1223 0); 1224 } 1225 1226 // Check whether anything has changed. 1227 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator 1228 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end(); 1229 !AnyFileChanged && F != FEnd; 1230 ++F) { 1231 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden 1232 = OverriddenFiles.find(F->first()); 1233 if (Overridden != OverriddenFiles.end()) { 1234 // This file was remapped; check whether the newly-mapped file 1235 // matches up with the previous mapping. 1236 if (Overridden->second != F->second) 1237 AnyFileChanged = true; 1238 continue; 1239 } 1240 1241 // The file was not remapped; check whether it has changed on disk. 1242 struct stat StatBuf; 1243 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) { 1244 // If we can't stat the file, assume that something horrible happened. 1245 AnyFileChanged = true; 1246 } else if (StatBuf.st_size != F->second.first || 1247 StatBuf.st_mtime != F->second.second) 1248 AnyFileChanged = true; 1249 } 1250 1251 if (!AnyFileChanged) { 1252 // Okay! We can re-use the precompiled preamble. 1253 1254 // Set the state of the diagnostic object to mimic its state 1255 // after parsing the preamble. 1256 // FIXME: This won't catch any #pragma push warning changes that 1257 // have occurred in the preamble. 1258 getDiagnostics().Reset(); 1259 ProcessWarningOptions(getDiagnostics(), 1260 PreambleInvocation.getDiagnosticOpts()); 1261 getDiagnostics().setNumWarnings(NumWarningsInPreamble); 1262 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble) 1263 StoredDiagnostics.erase( 1264 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble, 1265 StoredDiagnostics.end()); 1266 1267 // Create a version of the main file buffer that is padded to 1268 // buffer size we reserved when creating the preamble. 1269 return CreatePaddedMainFileBuffer(NewPreamble.first, 1270 PreambleReservedSize, 1271 FrontendOpts.Inputs[0].second); 1272 } 1273 } 1274 1275 // If we aren't allowed to rebuild the precompiled preamble, just 1276 // return now. 1277 if (!AllowRebuild) 1278 return 0; 1279 1280 // We can't reuse the previously-computed preamble. Build a new one. 1281 Preamble.clear(); 1282 llvm::sys::Path(PreambleFile).eraseFromDisk(); 1283 PreambleRebuildCounter = 1; 1284 } else if (!AllowRebuild) { 1285 // We aren't allowed to rebuild the precompiled preamble; just 1286 // return now. 1287 return 0; 1288 } 1289 1290 // If the preamble rebuild counter > 1, it's because we previously 1291 // failed to build a preamble and we're not yet ready to try 1292 // again. Decrement the counter and return a failure. 1293 if (PreambleRebuildCounter > 1) { 1294 --PreambleRebuildCounter; 1295 return 0; 1296 } 1297 1298 // Create a temporary file for the precompiled preamble. In rare 1299 // circumstances, this can fail. 1300 std::string PreamblePCHPath = GetPreamblePCHPath(); 1301 if (PreamblePCHPath.empty()) { 1302 // Try again next time. 1303 PreambleRebuildCounter = 1; 1304 return 0; 1305 } 1306 1307 // We did not previously compute a preamble, or it can't be reused anyway. 1308 SimpleTimer PreambleTimer(WantTiming); 1309 PreambleTimer.setOutput("Precompiling preamble"); 1310 1311 // Create a new buffer that stores the preamble. The buffer also contains 1312 // extra space for the original contents of the file (which will be present 1313 // when we actually parse the file) along with more room in case the file 1314 // grows. 1315 PreambleReservedSize = NewPreamble.first->getBufferSize(); 1316 if (PreambleReservedSize < 4096) 1317 PreambleReservedSize = 8191; 1318 else 1319 PreambleReservedSize *= 2; 1320 1321 // Save the preamble text for later; we'll need to compare against it for 1322 // subsequent reparses. 1323 Preamble.assign(NewPreamble.first->getBufferStart(), 1324 NewPreamble.first->getBufferStart() 1325 + NewPreamble.second.first); 1326 PreambleEndsAtStartOfLine = NewPreamble.second.second; 1327 1328 delete PreambleBuffer; 1329 PreambleBuffer 1330 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize, 1331 FrontendOpts.Inputs[0].second); 1332 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()), 1333 NewPreamble.first->getBufferStart(), Preamble.size()); 1334 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(), 1335 ' ', PreambleReservedSize - Preamble.size() - 1); 1336 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n'; 1337 1338 // Remap the main source file to the preamble buffer. 1339 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second); 1340 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer); 1341 1342 // Tell the compiler invocation to generate a temporary precompiled header. 1343 FrontendOpts.ProgramAction = frontend::GeneratePCH; 1344 FrontendOpts.ChainedPCH = true; 1345 // FIXME: Generate the precompiled header into memory? 1346 FrontendOpts.OutputFile = PreamblePCHPath; 1347 PreprocessorOpts.PrecompiledPreambleBytes.first = 0; 1348 PreprocessorOpts.PrecompiledPreambleBytes.second = false; 1349 1350 // Create the compiler instance to use for building the precompiled preamble. 1351 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance()); 1352 1353 // Recover resources if we crash before exiting this method. 1354 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> 1355 CICleanup(Clang.get()); 1356 1357 Clang->setInvocation(&PreambleInvocation); 1358 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second; 1359 1360 // Set up diagnostics, capturing all of the diagnostics produced. 1361 Clang->setDiagnostics(&getDiagnostics()); 1362 1363 // Create the target instance. 1364 Clang->getTargetOpts().Features = TargetFeatures; 1365 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(), 1366 Clang->getTargetOpts())); 1367 if (!Clang->hasTarget()) { 1368 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk(); 1369 Preamble.clear(); 1370 PreambleRebuildCounter = DefaultPreambleRebuildInterval; 1371 PreprocessorOpts.eraseRemappedFile( 1372 PreprocessorOpts.remapped_file_buffer_end() - 1); 1373 return 0; 1374 } 1375 1376 // Inform the target of the language options. 1377 // 1378 // FIXME: We shouldn't need to do this, the target should be immutable once 1379 // created. This complexity should be lifted elsewhere. 1380 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts()); 1381 1382 assert(Clang->getFrontendOpts().Inputs.size() == 1 && 1383 "Invocation must have exactly one source file!"); 1384 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST && 1385 "FIXME: AST inputs not yet supported here!"); 1386 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR && 1387 "IR inputs not support here!"); 1388 1389 // Clear out old caches and data. 1390 getDiagnostics().Reset(); 1391 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts()); 1392 StoredDiagnostics.erase( 1393 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver, 1394 StoredDiagnostics.end()); 1395 TopLevelDecls.clear(); 1396 TopLevelDeclsInPreamble.clear(); 1397 PreprocessedEntities.clear(); 1398 PreprocessedEntitiesInPreamble.clear(); 1399 1400 // Create a file manager object to provide access to and cache the filesystem. 1401 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts())); 1402 1403 // Create the source manager. 1404 Clang->setSourceManager(new SourceManager(getDiagnostics(), 1405 Clang->getFileManager())); 1406 1407 llvm::OwningPtr<PrecompilePreambleAction> Act; 1408 Act.reset(new PrecompilePreambleAction(*this)); 1409 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second, 1410 Clang->getFrontendOpts().Inputs[0].first)) { 1411 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk(); 1412 Preamble.clear(); 1413 PreambleRebuildCounter = DefaultPreambleRebuildInterval; 1414 PreprocessorOpts.eraseRemappedFile( 1415 PreprocessorOpts.remapped_file_buffer_end() - 1); 1416 return 0; 1417 } 1418 1419 Act->Execute(); 1420 Act->EndSourceFile(); 1421 1422 if (Diagnostics->hasErrorOccurred()) { 1423 // There were errors parsing the preamble, so no precompiled header was 1424 // generated. Forget that we even tried. 1425 // FIXME: Should we leave a note for ourselves to try again? 1426 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk(); 1427 Preamble.clear(); 1428 TopLevelDeclsInPreamble.clear(); 1429 PreprocessedEntities.clear(); 1430 PreprocessedEntitiesInPreamble.clear(); 1431 PreambleRebuildCounter = DefaultPreambleRebuildInterval; 1432 PreprocessorOpts.eraseRemappedFile( 1433 PreprocessorOpts.remapped_file_buffer_end() - 1); 1434 return 0; 1435 } 1436 1437 // Keep track of the preamble we precompiled. 1438 PreambleFile = FrontendOpts.OutputFile; 1439 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size(); 1440 NumWarningsInPreamble = getDiagnostics().getNumWarnings(); 1441 1442 // Keep track of all of the files that the source manager knows about, 1443 // so we can verify whether they have changed or not. 1444 FilesInPreamble.clear(); 1445 SourceManager &SourceMgr = Clang->getSourceManager(); 1446 const llvm::MemoryBuffer *MainFileBuffer 1447 = SourceMgr.getBuffer(SourceMgr.getMainFileID()); 1448 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(), 1449 FEnd = SourceMgr.fileinfo_end(); 1450 F != FEnd; 1451 ++F) { 1452 const FileEntry *File = F->second->OrigEntry; 1453 if (!File || F->second->getRawBuffer() == MainFileBuffer) 1454 continue; 1455 1456 FilesInPreamble[File->getName()] 1457 = std::make_pair(F->second->getSize(), File->getModificationTime()); 1458 } 1459 1460 PreambleRebuildCounter = 1; 1461 PreprocessorOpts.eraseRemappedFile( 1462 PreprocessorOpts.remapped_file_buffer_end() - 1); 1463 1464 // If the hash of top-level entities differs from the hash of the top-level 1465 // entities the last time we rebuilt the preamble, clear out the completion 1466 // cache. 1467 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) { 1468 CompletionCacheTopLevelHashValue = 0; 1469 PreambleTopLevelHashValue = CurrentTopLevelHashValue; 1470 } 1471 1472 return CreatePaddedMainFileBuffer(NewPreamble.first, 1473 PreambleReservedSize, 1474 FrontendOpts.Inputs[0].second); 1475} 1476 1477void ASTUnit::RealizeTopLevelDeclsFromPreamble() { 1478 std::vector<Decl *> Resolved; 1479 Resolved.reserve(TopLevelDeclsInPreamble.size()); 1480 ExternalASTSource &Source = *getASTContext().getExternalSource(); 1481 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) { 1482 // Resolve the declaration ID to an actual declaration, possibly 1483 // deserializing the declaration in the process. 1484 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]); 1485 if (D) 1486 Resolved.push_back(D); 1487 } 1488 TopLevelDeclsInPreamble.clear(); 1489 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end()); 1490} 1491 1492void ASTUnit::RealizePreprocessedEntitiesFromPreamble() { 1493 if (!PP) 1494 return; 1495 1496 PreprocessingRecord *PPRec = PP->getPreprocessingRecord(); 1497 if (!PPRec) 1498 return; 1499 1500 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource(); 1501 if (!External) 1502 return; 1503 1504 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) { 1505 if (PreprocessedEntity *PE 1506 = External->ReadPreprocessedEntityAtOffset( 1507 PreprocessedEntitiesInPreamble[I])) 1508 PreprocessedEntities.push_back(PE); 1509 } 1510 1511 if (PreprocessedEntities.empty()) 1512 return; 1513 1514 PreprocessedEntities.insert(PreprocessedEntities.end(), 1515 PPRec->begin(true), PPRec->end(true)); 1516} 1517 1518ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() { 1519 if (!PreprocessedEntitiesInPreamble.empty() && 1520 PreprocessedEntities.empty()) 1521 RealizePreprocessedEntitiesFromPreamble(); 1522 1523 if (PreprocessedEntities.empty()) 1524 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord()) 1525 return PPRec->begin(true); 1526 1527 return PreprocessedEntities.begin(); 1528} 1529 1530ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() { 1531 if (!PreprocessedEntitiesInPreamble.empty() && 1532 PreprocessedEntities.empty()) 1533 RealizePreprocessedEntitiesFromPreamble(); 1534 1535 if (PreprocessedEntities.empty()) 1536 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord()) 1537 return PPRec->end(true); 1538 1539 return PreprocessedEntities.end(); 1540} 1541 1542unsigned ASTUnit::getMaxPCHLevel() const { 1543 if (!getOnlyLocalDecls()) 1544 return Decl::MaxPCHLevel; 1545 1546 return 0; 1547} 1548 1549llvm::StringRef ASTUnit::getMainFileName() const { 1550 return Invocation->getFrontendOpts().Inputs[0].second; 1551} 1552 1553ASTUnit *ASTUnit::create(CompilerInvocation *CI, 1554 llvm::IntrusiveRefCntPtr<Diagnostic> Diags) { 1555 llvm::OwningPtr<ASTUnit> AST; 1556 AST.reset(new ASTUnit(false)); 1557 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false); 1558 AST->Diagnostics = Diags; 1559 AST->Invocation = CI; 1560 AST->FileSystemOpts = CI->getFileSystemOpts(); 1561 AST->FileMgr = new FileManager(AST->FileSystemOpts); 1562 AST->SourceMgr = new SourceManager(*Diags, *AST->FileMgr); 1563 1564 return AST.take(); 1565} 1566 1567ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI, 1568 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 1569 ASTFrontendAction *Action) { 1570 assert(CI && "A CompilerInvocation is required"); 1571 1572 // Create the AST unit. 1573 llvm::OwningPtr<ASTUnit> AST; 1574 AST.reset(new ASTUnit(false)); 1575 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics*/false); 1576 AST->Diagnostics = Diags; 1577 AST->OnlyLocalDecls = false; 1578 AST->CaptureDiagnostics = false; 1579 AST->CompleteTranslationUnit = Action ? Action->usesCompleteTranslationUnit() 1580 : true; 1581 AST->ShouldCacheCodeCompletionResults = false; 1582 AST->Invocation = CI; 1583 1584 // Recover resources if we crash before exiting this method. 1585 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> 1586 ASTUnitCleanup(AST.get()); 1587 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic, 1588 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> > 1589 DiagCleanup(Diags.getPtr()); 1590 1591 // We'll manage file buffers ourselves. 1592 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true; 1593 CI->getFrontendOpts().DisableFree = false; 1594 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts()); 1595 1596 // Save the target features. 1597 AST->TargetFeatures = CI->getTargetOpts().Features; 1598 1599 // Create the compiler instance to use for building the AST. 1600 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance()); 1601 1602 // Recover resources if we crash before exiting this method. 1603 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> 1604 CICleanup(Clang.get()); 1605 1606 Clang->setInvocation(CI); 1607 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second; 1608 1609 // Set up diagnostics, capturing any diagnostics that would 1610 // otherwise be dropped. 1611 Clang->setDiagnostics(&AST->getDiagnostics()); 1612 1613 // Create the target instance. 1614 Clang->getTargetOpts().Features = AST->TargetFeatures; 1615 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(), 1616 Clang->getTargetOpts())); 1617 if (!Clang->hasTarget()) 1618 return 0; 1619 1620 // Inform the target of the language options. 1621 // 1622 // FIXME: We shouldn't need to do this, the target should be immutable once 1623 // created. This complexity should be lifted elsewhere. 1624 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts()); 1625 1626 assert(Clang->getFrontendOpts().Inputs.size() == 1 && 1627 "Invocation must have exactly one source file!"); 1628 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST && 1629 "FIXME: AST inputs not yet supported here!"); 1630 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR && 1631 "IR inputs not supported here!"); 1632 1633 // Configure the various subsystems. 1634 AST->FileSystemOpts = Clang->getFileSystemOpts(); 1635 AST->FileMgr = new FileManager(AST->FileSystemOpts); 1636 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr); 1637 AST->TheSema.reset(); 1638 AST->Ctx = 0; 1639 AST->PP = 0; 1640 1641 // Create a file manager object to provide access to and cache the filesystem. 1642 Clang->setFileManager(&AST->getFileManager()); 1643 1644 // Create the source manager. 1645 Clang->setSourceManager(&AST->getSourceManager()); 1646 1647 ASTFrontendAction *Act = Action; 1648 1649 llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct; 1650 if (!Act) { 1651 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST)); 1652 Act = TrackerAct.get(); 1653 } 1654 1655 // Recover resources if we crash before exiting this method. 1656 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction> 1657 ActCleanup(TrackerAct.get()); 1658 1659 if (!Act->BeginSourceFile(*Clang.get(), 1660 Clang->getFrontendOpts().Inputs[0].second, 1661 Clang->getFrontendOpts().Inputs[0].first)) 1662 return 0; 1663 1664 Act->Execute(); 1665 1666 // Steal the created target, context, and preprocessor. 1667 AST->TheSema.reset(Clang->takeSema()); 1668 AST->Consumer.reset(Clang->takeASTConsumer()); 1669 AST->Ctx = &Clang->getASTContext(); 1670 AST->PP = &Clang->getPreprocessor(); 1671 Clang->setSourceManager(0); 1672 Clang->setFileManager(0); 1673 AST->Target = &Clang->getTarget(); 1674 1675 Act->EndSourceFile(); 1676 1677 return AST.take(); 1678} 1679 1680bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) { 1681 if (!Invocation) 1682 return true; 1683 1684 // We'll manage file buffers ourselves. 1685 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true; 1686 Invocation->getFrontendOpts().DisableFree = false; 1687 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts()); 1688 1689 // Save the target features. 1690 TargetFeatures = Invocation->getTargetOpts().Features; 1691 1692 llvm::MemoryBuffer *OverrideMainBuffer = 0; 1693 if (PrecompilePreamble) { 1694 PreambleRebuildCounter = 2; 1695 OverrideMainBuffer 1696 = getMainBufferWithPrecompiledPreamble(*Invocation); 1697 } 1698 1699 SimpleTimer ParsingTimer(WantTiming); 1700 ParsingTimer.setOutput("Parsing " + getMainFileName()); 1701 1702 // Recover resources if we crash before exiting this method. 1703 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer> 1704 MemBufferCleanup(OverrideMainBuffer); 1705 1706 return Parse(OverrideMainBuffer); 1707} 1708 1709ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI, 1710 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 1711 bool OnlyLocalDecls, 1712 bool CaptureDiagnostics, 1713 bool PrecompilePreamble, 1714 bool CompleteTranslationUnit, 1715 bool CacheCodeCompletionResults) { 1716 // Create the AST unit. 1717 llvm::OwningPtr<ASTUnit> AST; 1718 AST.reset(new ASTUnit(false)); 1719 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics); 1720 AST->Diagnostics = Diags; 1721 AST->OnlyLocalDecls = OnlyLocalDecls; 1722 AST->CaptureDiagnostics = CaptureDiagnostics; 1723 AST->CompleteTranslationUnit = CompleteTranslationUnit; 1724 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults; 1725 AST->Invocation = CI; 1726 1727 // Recover resources if we crash before exiting this method. 1728 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> 1729 ASTUnitCleanup(AST.get()); 1730 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic, 1731 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> > 1732 DiagCleanup(Diags.getPtr()); 1733 1734 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take(); 1735} 1736 1737ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin, 1738 const char **ArgEnd, 1739 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 1740 llvm::StringRef ResourceFilesPath, 1741 bool OnlyLocalDecls, 1742 bool CaptureDiagnostics, 1743 RemappedFile *RemappedFiles, 1744 unsigned NumRemappedFiles, 1745 bool RemappedFilesKeepOriginalName, 1746 bool PrecompilePreamble, 1747 bool CompleteTranslationUnit, 1748 bool CacheCodeCompletionResults, 1749 bool CXXPrecompilePreamble, 1750 bool CXXChainedPCH) { 1751 if (!Diags.getPtr()) { 1752 // No diagnostics engine was provided, so create our own diagnostics object 1753 // with the default options. 1754 DiagnosticOptions DiagOpts; 1755 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin, 1756 ArgBegin); 1757 } 1758 1759 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics; 1760 1761 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI; 1762 1763 { 1764 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags, 1765 StoredDiagnostics); 1766 1767 CI = clang::createInvocationFromCommandLine( 1768 llvm::ArrayRef<const char *>(ArgBegin, ArgEnd-ArgBegin), 1769 Diags); 1770 if (!CI) 1771 return 0; 1772 } 1773 1774 // Override any files that need remapping 1775 for (unsigned I = 0; I != NumRemappedFiles; ++I) { 1776 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second; 1777 if (const llvm::MemoryBuffer * 1778 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) { 1779 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf); 1780 } else { 1781 const char *fname = fileOrBuf.get<const char *>(); 1782 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname); 1783 } 1784 } 1785 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName = 1786 RemappedFilesKeepOriginalName; 1787 1788 // Override the resources path. 1789 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath; 1790 1791 // Check whether we should precompile the preamble and/or use chained PCH. 1792 // FIXME: This is a temporary hack while we debug C++ chained PCH. 1793 if (CI->getLangOpts().CPlusPlus) { 1794 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble; 1795 1796 if (PrecompilePreamble && !CXXChainedPCH && 1797 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty()) 1798 PrecompilePreamble = false; 1799 } 1800 1801 // Create the AST unit. 1802 llvm::OwningPtr<ASTUnit> AST; 1803 AST.reset(new ASTUnit(false)); 1804 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics); 1805 AST->Diagnostics = Diags; 1806 1807 AST->FileSystemOpts = CI->getFileSystemOpts(); 1808 AST->FileMgr = new FileManager(AST->FileSystemOpts); 1809 AST->OnlyLocalDecls = OnlyLocalDecls; 1810 AST->CaptureDiagnostics = CaptureDiagnostics; 1811 AST->CompleteTranslationUnit = CompleteTranslationUnit; 1812 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults; 1813 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size(); 1814 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size(); 1815 AST->StoredDiagnostics.swap(StoredDiagnostics); 1816 AST->Invocation = CI; 1817 1818 // Recover resources if we crash before exiting this method. 1819 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> 1820 ASTUnitCleanup(AST.get()); 1821 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation, 1822 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> > 1823 CICleanup(CI.getPtr()); 1824 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic, 1825 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> > 1826 DiagCleanup(Diags.getPtr()); 1827 1828 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take(); 1829} 1830 1831bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) { 1832 if (!Invocation) 1833 return true; 1834 1835 SimpleTimer ParsingTimer(WantTiming); 1836 ParsingTimer.setOutput("Reparsing " + getMainFileName()); 1837 1838 // Remap files. 1839 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 1840 PPOpts.DisableStatCache = true; 1841 for (PreprocessorOptions::remapped_file_buffer_iterator 1842 R = PPOpts.remapped_file_buffer_begin(), 1843 REnd = PPOpts.remapped_file_buffer_end(); 1844 R != REnd; 1845 ++R) { 1846 delete R->second; 1847 } 1848 Invocation->getPreprocessorOpts().clearRemappedFiles(); 1849 for (unsigned I = 0; I != NumRemappedFiles; ++I) { 1850 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second; 1851 if (const llvm::MemoryBuffer * 1852 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) { 1853 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, 1854 memBuf); 1855 } else { 1856 const char *fname = fileOrBuf.get<const char *>(); 1857 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, 1858 fname); 1859 } 1860 } 1861 1862 // If we have a preamble file lying around, or if we might try to 1863 // build a precompiled preamble, do so now. 1864 llvm::MemoryBuffer *OverrideMainBuffer = 0; 1865 if (!PreambleFile.empty() || PreambleRebuildCounter > 0) 1866 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation); 1867 1868 // Clear out the diagnostics state. 1869 if (!OverrideMainBuffer) { 1870 getDiagnostics().Reset(); 1871 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts()); 1872 } 1873 1874 // Parse the sources 1875 bool Result = Parse(OverrideMainBuffer); 1876 1877 // If we're caching global code-completion results, and the top-level 1878 // declarations have changed, clear out the code-completion cache. 1879 if (!Result && ShouldCacheCodeCompletionResults && 1880 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue) 1881 CacheCodeCompletionResults(); 1882 1883 return Result; 1884} 1885 1886//----------------------------------------------------------------------------// 1887// Code completion 1888//----------------------------------------------------------------------------// 1889 1890namespace { 1891 /// \brief Code completion consumer that combines the cached code-completion 1892 /// results from an ASTUnit with the code-completion results provided to it, 1893 /// then passes the result on to 1894 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer { 1895 unsigned NormalContexts; 1896 ASTUnit &AST; 1897 CodeCompleteConsumer &Next; 1898 1899 public: 1900 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next, 1901 bool IncludeMacros, bool IncludeCodePatterns, 1902 bool IncludeGlobals) 1903 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals, 1904 Next.isOutputBinary()), AST(AST), Next(Next) 1905 { 1906 // Compute the set of contexts in which we will look when we don't have 1907 // any information about the specific context. 1908 NormalContexts 1909 = (1 << (CodeCompletionContext::CCC_TopLevel - 1)) 1910 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1)) 1911 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1)) 1912 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1)) 1913 | (1 << (CodeCompletionContext::CCC_Statement - 1)) 1914 | (1 << (CodeCompletionContext::CCC_Expression - 1)) 1915 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)) 1916 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1)) 1917 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1)) 1918 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1)) 1919 | (1 << (CodeCompletionContext::CCC_Recovery - 1)); 1920 1921 if (AST.getASTContext().getLangOptions().CPlusPlus) 1922 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1)) 1923 | (1 << (CodeCompletionContext::CCC_UnionTag - 1)) 1924 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1)); 1925 } 1926 1927 virtual void ProcessCodeCompleteResults(Sema &S, 1928 CodeCompletionContext Context, 1929 CodeCompletionResult *Results, 1930 unsigned NumResults); 1931 1932 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, 1933 OverloadCandidate *Candidates, 1934 unsigned NumCandidates) { 1935 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates); 1936 } 1937 1938 virtual CodeCompletionAllocator &getAllocator() { 1939 return Next.getAllocator(); 1940 } 1941 }; 1942} 1943 1944/// \brief Helper function that computes which global names are hidden by the 1945/// local code-completion results. 1946static void CalculateHiddenNames(const CodeCompletionContext &Context, 1947 CodeCompletionResult *Results, 1948 unsigned NumResults, 1949 ASTContext &Ctx, 1950 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){ 1951 bool OnlyTagNames = false; 1952 switch (Context.getKind()) { 1953 case CodeCompletionContext::CCC_Recovery: 1954 case CodeCompletionContext::CCC_TopLevel: 1955 case CodeCompletionContext::CCC_ObjCInterface: 1956 case CodeCompletionContext::CCC_ObjCImplementation: 1957 case CodeCompletionContext::CCC_ObjCIvarList: 1958 case CodeCompletionContext::CCC_ClassStructUnion: 1959 case CodeCompletionContext::CCC_Statement: 1960 case CodeCompletionContext::CCC_Expression: 1961 case CodeCompletionContext::CCC_ObjCMessageReceiver: 1962 case CodeCompletionContext::CCC_MemberAccess: 1963 case CodeCompletionContext::CCC_Namespace: 1964 case CodeCompletionContext::CCC_Type: 1965 case CodeCompletionContext::CCC_Name: 1966 case CodeCompletionContext::CCC_PotentiallyQualifiedName: 1967 case CodeCompletionContext::CCC_ParenthesizedExpression: 1968 break; 1969 1970 case CodeCompletionContext::CCC_EnumTag: 1971 case CodeCompletionContext::CCC_UnionTag: 1972 case CodeCompletionContext::CCC_ClassOrStructTag: 1973 OnlyTagNames = true; 1974 break; 1975 1976 case CodeCompletionContext::CCC_ObjCProtocolName: 1977 case CodeCompletionContext::CCC_MacroName: 1978 case CodeCompletionContext::CCC_MacroNameUse: 1979 case CodeCompletionContext::CCC_PreprocessorExpression: 1980 case CodeCompletionContext::CCC_PreprocessorDirective: 1981 case CodeCompletionContext::CCC_NaturalLanguage: 1982 case CodeCompletionContext::CCC_SelectorName: 1983 case CodeCompletionContext::CCC_TypeQualifiers: 1984 case CodeCompletionContext::CCC_Other: 1985 case CodeCompletionContext::CCC_OtherWithMacros: 1986 // We're looking for nothing, or we're looking for names that cannot 1987 // be hidden. 1988 return; 1989 } 1990 1991 typedef CodeCompletionResult Result; 1992 for (unsigned I = 0; I != NumResults; ++I) { 1993 if (Results[I].Kind != Result::RK_Declaration) 1994 continue; 1995 1996 unsigned IDNS 1997 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace(); 1998 1999 bool Hiding = false; 2000 if (OnlyTagNames) 2001 Hiding = (IDNS & Decl::IDNS_Tag); 2002 else { 2003 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member | 2004 Decl::IDNS_Namespace | Decl::IDNS_Ordinary | 2005 Decl::IDNS_NonMemberOperator); 2006 if (Ctx.getLangOptions().CPlusPlus) 2007 HiddenIDNS |= Decl::IDNS_Tag; 2008 Hiding = (IDNS & HiddenIDNS); 2009 } 2010 2011 if (!Hiding) 2012 continue; 2013 2014 DeclarationName Name = Results[I].Declaration->getDeclName(); 2015 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo()) 2016 HiddenNames.insert(Identifier->getName()); 2017 else 2018 HiddenNames.insert(Name.getAsString()); 2019 } 2020} 2021 2022 2023void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S, 2024 CodeCompletionContext Context, 2025 CodeCompletionResult *Results, 2026 unsigned NumResults) { 2027 // Merge the results we were given with the results we cached. 2028 bool AddedResult = false; 2029 unsigned InContexts 2030 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts 2031 : (1 << (Context.getKind() - 1))); 2032 2033 // Contains the set of names that are hidden by "local" completion results. 2034 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames; 2035 typedef CodeCompletionResult Result; 2036 llvm::SmallVector<Result, 8> AllResults; 2037 for (ASTUnit::cached_completion_iterator 2038 C = AST.cached_completion_begin(), 2039 CEnd = AST.cached_completion_end(); 2040 C != CEnd; ++C) { 2041 // If the context we are in matches any of the contexts we are 2042 // interested in, we'll add this result. 2043 if ((C->ShowInContexts & InContexts) == 0) 2044 continue; 2045 2046 // If we haven't added any results previously, do so now. 2047 if (!AddedResult) { 2048 CalculateHiddenNames(Context, Results, NumResults, S.Context, 2049 HiddenNames); 2050 AllResults.insert(AllResults.end(), Results, Results + NumResults); 2051 AddedResult = true; 2052 } 2053 2054 // Determine whether this global completion result is hidden by a local 2055 // completion result. If so, skip it. 2056 if (C->Kind != CXCursor_MacroDefinition && 2057 HiddenNames.count(C->Completion->getTypedText())) 2058 continue; 2059 2060 // Adjust priority based on similar type classes. 2061 unsigned Priority = C->Priority; 2062 CXCursorKind CursorKind = C->Kind; 2063 CodeCompletionString *Completion = C->Completion; 2064 if (!Context.getPreferredType().isNull()) { 2065 if (C->Kind == CXCursor_MacroDefinition) { 2066 Priority = getMacroUsagePriority(C->Completion->getTypedText(), 2067 S.getLangOptions(), 2068 Context.getPreferredType()->isAnyPointerType()); 2069 } else if (C->Type) { 2070 CanQualType Expected 2071 = S.Context.getCanonicalType( 2072 Context.getPreferredType().getUnqualifiedType()); 2073 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected); 2074 if (ExpectedSTC == C->TypeClass) { 2075 // We know this type is similar; check for an exact match. 2076 llvm::StringMap<unsigned> &CachedCompletionTypes 2077 = AST.getCachedCompletionTypes(); 2078 llvm::StringMap<unsigned>::iterator Pos 2079 = CachedCompletionTypes.find(QualType(Expected).getAsString()); 2080 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type) 2081 Priority /= CCF_ExactTypeMatch; 2082 else 2083 Priority /= CCF_SimilarTypeMatch; 2084 } 2085 } 2086 } 2087 2088 // Adjust the completion string, if required. 2089 if (C->Kind == CXCursor_MacroDefinition && 2090 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) { 2091 // Create a new code-completion string that just contains the 2092 // macro name, without its arguments. 2093 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern, 2094 C->Availability); 2095 Builder.AddTypedTextChunk(C->Completion->getTypedText()); 2096 CursorKind = CXCursor_NotImplemented; 2097 Priority = CCP_CodePattern; 2098 Completion = Builder.TakeString(); 2099 } 2100 2101 AllResults.push_back(Result(Completion, Priority, CursorKind, 2102 C->Availability)); 2103 } 2104 2105 // If we did not add any cached completion results, just forward the 2106 // results we were given to the next consumer. 2107 if (!AddedResult) { 2108 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults); 2109 return; 2110 } 2111 2112 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(), 2113 AllResults.size()); 2114} 2115 2116 2117 2118void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column, 2119 RemappedFile *RemappedFiles, 2120 unsigned NumRemappedFiles, 2121 bool IncludeMacros, 2122 bool IncludeCodePatterns, 2123 CodeCompleteConsumer &Consumer, 2124 Diagnostic &Diag, LangOptions &LangOpts, 2125 SourceManager &SourceMgr, FileManager &FileMgr, 2126 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics, 2127 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) { 2128 if (!Invocation) 2129 return; 2130 2131 SimpleTimer CompletionTimer(WantTiming); 2132 CompletionTimer.setOutput("Code completion @ " + File + ":" + 2133 llvm::Twine(Line) + ":" + llvm::Twine(Column)); 2134 2135 llvm::IntrusiveRefCntPtr<CompilerInvocation> 2136 CCInvocation(new CompilerInvocation(*Invocation)); 2137 2138 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts(); 2139 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts(); 2140 2141 FrontendOpts.ShowMacrosInCodeCompletion 2142 = IncludeMacros && CachedCompletionResults.empty(); 2143 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns; 2144 FrontendOpts.ShowGlobalSymbolsInCodeCompletion 2145 = CachedCompletionResults.empty(); 2146 FrontendOpts.CodeCompletionAt.FileName = File; 2147 FrontendOpts.CodeCompletionAt.Line = Line; 2148 FrontendOpts.CodeCompletionAt.Column = Column; 2149 2150 // Set the language options appropriately. 2151 LangOpts = CCInvocation->getLangOpts(); 2152 2153 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance()); 2154 2155 // Recover resources if we crash before exiting this method. 2156 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> 2157 CICleanup(Clang.get()); 2158 2159 Clang->setInvocation(&*CCInvocation); 2160 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second; 2161 2162 // Set up diagnostics, capturing any diagnostics produced. 2163 Clang->setDiagnostics(&Diag); 2164 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts()); 2165 CaptureDroppedDiagnostics Capture(true, 2166 Clang->getDiagnostics(), 2167 StoredDiagnostics); 2168 2169 // Create the target instance. 2170 Clang->getTargetOpts().Features = TargetFeatures; 2171 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(), 2172 Clang->getTargetOpts())); 2173 if (!Clang->hasTarget()) { 2174 Clang->setInvocation(0); 2175 return; 2176 } 2177 2178 // Inform the target of the language options. 2179 // 2180 // FIXME: We shouldn't need to do this, the target should be immutable once 2181 // created. This complexity should be lifted elsewhere. 2182 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts()); 2183 2184 assert(Clang->getFrontendOpts().Inputs.size() == 1 && 2185 "Invocation must have exactly one source file!"); 2186 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST && 2187 "FIXME: AST inputs not yet supported here!"); 2188 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR && 2189 "IR inputs not support here!"); 2190 2191 2192 // Use the source and file managers that we were given. 2193 Clang->setFileManager(&FileMgr); 2194 Clang->setSourceManager(&SourceMgr); 2195 2196 // Remap files. 2197 PreprocessorOpts.clearRemappedFiles(); 2198 PreprocessorOpts.RetainRemappedFileBuffers = true; 2199 for (unsigned I = 0; I != NumRemappedFiles; ++I) { 2200 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second; 2201 if (const llvm::MemoryBuffer * 2202 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) { 2203 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf); 2204 OwnedBuffers.push_back(memBuf); 2205 } else { 2206 const char *fname = fileOrBuf.get<const char *>(); 2207 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname); 2208 } 2209 } 2210 2211 // Use the code completion consumer we were given, but adding any cached 2212 // code-completion results. 2213 AugmentedCodeCompleteConsumer *AugmentedConsumer 2214 = new AugmentedCodeCompleteConsumer(*this, Consumer, 2215 FrontendOpts.ShowMacrosInCodeCompletion, 2216 FrontendOpts.ShowCodePatternsInCodeCompletion, 2217 FrontendOpts.ShowGlobalSymbolsInCodeCompletion); 2218 Clang->setCodeCompletionConsumer(AugmentedConsumer); 2219 2220 // If we have a precompiled preamble, try to use it. We only allow 2221 // the use of the precompiled preamble if we're if the completion 2222 // point is within the main file, after the end of the precompiled 2223 // preamble. 2224 llvm::MemoryBuffer *OverrideMainBuffer = 0; 2225 if (!PreambleFile.empty()) { 2226 using llvm::sys::FileStatus; 2227 llvm::sys::PathWithStatus CompleteFilePath(File); 2228 llvm::sys::PathWithStatus MainPath(OriginalSourceFile); 2229 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus()) 2230 if (const FileStatus *MainStatus = MainPath.getFileStatus()) 2231 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID()) 2232 OverrideMainBuffer 2233 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false, 2234 Line - 1); 2235 } 2236 2237 // If the main file has been overridden due to the use of a preamble, 2238 // make that override happen and introduce the preamble. 2239 PreprocessorOpts.DisableStatCache = true; 2240 StoredDiagnostics.insert(StoredDiagnostics.end(), 2241 this->StoredDiagnostics.begin(), 2242 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver); 2243 if (OverrideMainBuffer) { 2244 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer); 2245 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size(); 2246 PreprocessorOpts.PrecompiledPreambleBytes.second 2247 = PreambleEndsAtStartOfLine; 2248 PreprocessorOpts.ImplicitPCHInclude = PreambleFile; 2249 PreprocessorOpts.DisablePCHValidation = true; 2250 2251 // The stored diagnostics have the old source manager. Copy them 2252 // to our output set of stored diagnostics, updating the source 2253 // manager to the one we were given. 2254 for (unsigned I = NumStoredDiagnosticsFromDriver, 2255 N = this->StoredDiagnostics.size(); 2256 I < N; ++I) { 2257 StoredDiagnostics.push_back(this->StoredDiagnostics[I]); 2258 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr); 2259 StoredDiagnostics[I].setLocation(Loc); 2260 } 2261 2262 OwnedBuffers.push_back(OverrideMainBuffer); 2263 } else { 2264 PreprocessorOpts.PrecompiledPreambleBytes.first = 0; 2265 PreprocessorOpts.PrecompiledPreambleBytes.second = false; 2266 } 2267 2268 llvm::OwningPtr<SyntaxOnlyAction> Act; 2269 Act.reset(new SyntaxOnlyAction); 2270 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second, 2271 Clang->getFrontendOpts().Inputs[0].first)) { 2272 Act->Execute(); 2273 Act->EndSourceFile(); 2274 } 2275} 2276 2277bool ASTUnit::Save(llvm::StringRef File) { 2278 if (getDiagnostics().hasErrorOccurred()) 2279 return true; 2280 2281 // FIXME: Can we somehow regenerate the stat cache here, or do we need to 2282 // unconditionally create a stat cache when we parse the file? 2283 std::string ErrorInfo; 2284 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo, 2285 llvm::raw_fd_ostream::F_Binary); 2286 if (!ErrorInfo.empty() || Out.has_error()) 2287 return true; 2288 2289 serialize(Out); 2290 Out.close(); 2291 return Out.has_error(); 2292} 2293 2294bool ASTUnit::serialize(llvm::raw_ostream &OS) { 2295 if (getDiagnostics().hasErrorOccurred()) 2296 return true; 2297 2298 std::vector<unsigned char> Buffer; 2299 llvm::BitstreamWriter Stream(Buffer); 2300 ASTWriter Writer(Stream); 2301 Writer.WriteAST(getSema(), 0, std::string(), 0); 2302 2303 // Write the generated bitstream to "Out". 2304 if (!Buffer.empty()) 2305 OS.write((char *)&Buffer.front(), Buffer.size()); 2306 2307 return false; 2308} 2309