1 //===- ASTUnit.cpp - ASTUnit utility --------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // ASTUnit Implementation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Frontend/ASTUnit.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CommentCommandTraits.h" 17 #include "clang/AST/Decl.h" 18 #include "clang/AST/DeclBase.h" 19 #include "clang/AST/DeclCXX.h" 20 #include "clang/AST/DeclGroup.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/ExternalASTSource.h" 25 #include "clang/AST/PrettyPrinter.h" 26 #include "clang/AST/Type.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/Diagnostic.h" 29 #include "clang/Basic/FileManager.h" 30 #include "clang/Basic/IdentifierTable.h" 31 #include "clang/Basic/LLVM.h" 32 #include "clang/Basic/LangOptions.h" 33 #include "clang/Basic/LangStandard.h" 34 #include "clang/Basic/Module.h" 35 #include "clang/Basic/SourceLocation.h" 36 #include "clang/Basic/SourceManager.h" 37 #include "clang/Basic/TargetInfo.h" 38 #include "clang/Basic/TargetOptions.h" 39 #include "clang/Frontend/CompilerInstance.h" 40 #include "clang/Frontend/CompilerInvocation.h" 41 #include "clang/Frontend/FrontendAction.h" 42 #include "clang/Frontend/FrontendActions.h" 43 #include "clang/Frontend/FrontendDiagnostic.h" 44 #include "clang/Frontend/FrontendOptions.h" 45 #include "clang/Frontend/MultiplexConsumer.h" 46 #include "clang/Frontend/PrecompiledPreamble.h" 47 #include "clang/Frontend/Utils.h" 48 #include "clang/Lex/HeaderSearch.h" 49 #include "clang/Lex/HeaderSearchOptions.h" 50 #include "clang/Lex/Lexer.h" 51 #include "clang/Lex/PPCallbacks.h" 52 #include "clang/Lex/PreprocessingRecord.h" 53 #include "clang/Lex/Preprocessor.h" 54 #include "clang/Lex/PreprocessorOptions.h" 55 #include "clang/Lex/Token.h" 56 #include "clang/Sema/CodeCompleteConsumer.h" 57 #include "clang/Sema/CodeCompleteOptions.h" 58 #include "clang/Sema/Sema.h" 59 #include "clang/Serialization/ASTBitCodes.h" 60 #include "clang/Serialization/ASTReader.h" 61 #include "clang/Serialization/ASTWriter.h" 62 #include "clang/Serialization/ContinuousRangeMap.h" 63 #include "clang/Serialization/InMemoryModuleCache.h" 64 #include "clang/Serialization/ModuleFile.h" 65 #include "clang/Serialization/PCHContainerOperations.h" 66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/DenseMap.h" 68 #include "llvm/ADT/IntrusiveRefCntPtr.h" 69 #include "llvm/ADT/None.h" 70 #include "llvm/ADT/Optional.h" 71 #include "llvm/ADT/STLExtras.h" 72 #include "llvm/ADT/ScopeExit.h" 73 #include "llvm/ADT/SmallString.h" 74 #include "llvm/ADT/SmallVector.h" 75 #include "llvm/ADT/StringMap.h" 76 #include "llvm/ADT/StringRef.h" 77 #include "llvm/ADT/StringSet.h" 78 #include "llvm/ADT/Twine.h" 79 #include "llvm/ADT/iterator_range.h" 80 #include "llvm/Bitstream/BitstreamWriter.h" 81 #include "llvm/Support/Allocator.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/CrashRecoveryContext.h" 84 #include "llvm/Support/DJB.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/ErrorOr.h" 87 #include "llvm/Support/FileSystem.h" 88 #include "llvm/Support/FileUtilities.h" 89 #include "llvm/Support/MemoryBuffer.h" 90 #include "llvm/Support/Timer.h" 91 #include "llvm/Support/VirtualFileSystem.h" 92 #include "llvm/Support/raw_ostream.h" 93 #include <algorithm> 94 #include <atomic> 95 #include <cassert> 96 #include <cstdint> 97 #include <cstdio> 98 #include <cstdlib> 99 #include <memory> 100 #include <mutex> 101 #include <string> 102 #include <tuple> 103 #include <utility> 104 #include <vector> 105 106 using namespace clang; 107 108 using llvm::TimeRecord; 109 110 namespace { 111 112 class SimpleTimer { 113 bool WantTiming; 114 TimeRecord Start; 115 std::string Output; 116 117 public: 118 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) { 119 if (WantTiming) 120 Start = TimeRecord::getCurrentTime(); 121 } 122 123 ~SimpleTimer() { 124 if (WantTiming) { 125 TimeRecord Elapsed = TimeRecord::getCurrentTime(); 126 Elapsed -= Start; 127 llvm::errs() << Output << ':'; 128 Elapsed.print(Elapsed, llvm::errs()); 129 llvm::errs() << '\n'; 130 } 131 } 132 133 void setOutput(const Twine &Output) { 134 if (WantTiming) 135 this->Output = Output.str(); 136 } 137 }; 138 139 } // namespace 140 141 template <class T> 142 static std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) { 143 if (!Val) 144 return nullptr; 145 return std::move(*Val); 146 } 147 148 template <class T> 149 static bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) { 150 if (!Val) 151 return false; 152 Output = std::move(*Val); 153 return true; 154 } 155 156 /// Get a source buffer for \p MainFilePath, handling all file-to-file 157 /// and file-to-buffer remappings inside \p Invocation. 158 static std::unique_ptr<llvm::MemoryBuffer> 159 getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation, 160 llvm::vfs::FileSystem *VFS, 161 StringRef FilePath, bool isVolatile) { 162 const auto &PreprocessorOpts = Invocation.getPreprocessorOpts(); 163 164 // Try to determine if the main file has been remapped, either from the 165 // command line (to another file) or directly through the compiler 166 // invocation (to a memory buffer). 167 llvm::MemoryBuffer *Buffer = nullptr; 168 std::unique_ptr<llvm::MemoryBuffer> BufferOwner; 169 auto FileStatus = VFS->status(FilePath); 170 if (FileStatus) { 171 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID(); 172 173 // Check whether there is a file-file remapping of the main file 174 for (const auto &RF : PreprocessorOpts.RemappedFiles) { 175 std::string MPath(RF.first); 176 auto MPathStatus = VFS->status(MPath); 177 if (MPathStatus) { 178 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID(); 179 if (MainFileID == MID) { 180 // We found a remapping. Try to load the resulting, remapped source. 181 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second, -1, true, isVolatile)); 182 if (!BufferOwner) 183 return nullptr; 184 } 185 } 186 } 187 188 // Check whether there is a file-buffer remapping. It supercedes the 189 // file-file remapping. 190 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) { 191 std::string MPath(RB.first); 192 auto MPathStatus = VFS->status(MPath); 193 if (MPathStatus) { 194 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID(); 195 if (MainFileID == MID) { 196 // We found a remapping. 197 BufferOwner.reset(); 198 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second); 199 } 200 } 201 } 202 } 203 204 // If the main source file was not remapped, load it now. 205 if (!Buffer && !BufferOwner) { 206 BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath, -1, true, isVolatile)); 207 if (!BufferOwner) 208 return nullptr; 209 } 210 211 if (BufferOwner) 212 return BufferOwner; 213 if (!Buffer) 214 return nullptr; 215 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath); 216 } 217 218 struct ASTUnit::ASTWriterData { 219 SmallString<128> Buffer; 220 llvm::BitstreamWriter Stream; 221 ASTWriter Writer; 222 223 ASTWriterData(InMemoryModuleCache &ModuleCache) 224 : Stream(Buffer), Writer(Stream, Buffer, ModuleCache, {}) {} 225 }; 226 227 void ASTUnit::clearFileLevelDecls() { 228 FileDecls.clear(); 229 } 230 231 /// After failing to build a precompiled preamble (due to 232 /// errors in the source that occurs in the preamble), the number of 233 /// reparses during which we'll skip even trying to precompile the 234 /// preamble. 235 const unsigned DefaultPreambleRebuildInterval = 5; 236 237 /// Tracks the number of ASTUnit objects that are currently active. 238 /// 239 /// Used for debugging purposes only. 240 static std::atomic<unsigned> ActiveASTUnitObjects; 241 242 ASTUnit::ASTUnit(bool _MainFileIsAST) 243 : MainFileIsAST(_MainFileIsAST), WantTiming(getenv("LIBCLANG_TIMING")), 244 ShouldCacheCodeCompletionResults(false), 245 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false), 246 UnsafeToFree(false) { 247 if (getenv("LIBCLANG_OBJTRACKING")) 248 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects); 249 } 250 251 ASTUnit::~ASTUnit() { 252 // If we loaded from an AST file, balance out the BeginSourceFile call. 253 if (MainFileIsAST && getDiagnostics().getClient()) { 254 getDiagnostics().getClient()->EndSourceFile(); 255 } 256 257 clearFileLevelDecls(); 258 259 // Free the buffers associated with remapped files. We are required to 260 // perform this operation here because we explicitly request that the 261 // compiler instance *not* free these buffers for each invocation of the 262 // parser. 263 if (Invocation && OwnsRemappedFileBuffers) { 264 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 265 for (const auto &RB : PPOpts.RemappedFileBuffers) 266 delete RB.second; 267 } 268 269 ClearCachedCompletionResults(); 270 271 if (getenv("LIBCLANG_OBJTRACKING")) 272 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects); 273 } 274 275 void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) { 276 this->PP = std::move(PP); 277 } 278 279 void ASTUnit::enableSourceFileDiagnostics() { 280 assert(getDiagnostics().getClient() && Ctx && 281 "Bad context for source file"); 282 getDiagnostics().getClient()->BeginSourceFile(Ctx->getLangOpts(), PP.get()); 283 } 284 285 /// Determine the set of code-completion contexts in which this 286 /// declaration should be shown. 287 static uint64_t getDeclShowContexts(const NamedDecl *ND, 288 const LangOptions &LangOpts, 289 bool &IsNestedNameSpecifier) { 290 IsNestedNameSpecifier = false; 291 292 if (isa<UsingShadowDecl>(ND)) 293 ND = ND->getUnderlyingDecl(); 294 if (!ND) 295 return 0; 296 297 uint64_t Contexts = 0; 298 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) || 299 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) || 300 isa<TypeAliasTemplateDecl>(ND)) { 301 // Types can appear in these contexts. 302 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND)) 303 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel) 304 | (1LL << CodeCompletionContext::CCC_ObjCIvarList) 305 | (1LL << CodeCompletionContext::CCC_ClassStructUnion) 306 | (1LL << CodeCompletionContext::CCC_Statement) 307 | (1LL << CodeCompletionContext::CCC_Type) 308 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression); 309 310 // In C++, types can appear in expressions contexts (for functional casts). 311 if (LangOpts.CPlusPlus) 312 Contexts |= (1LL << CodeCompletionContext::CCC_Expression); 313 314 // In Objective-C, message sends can send interfaces. In Objective-C++, 315 // all types are available due to functional casts. 316 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND)) 317 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver); 318 319 // In Objective-C, you can only be a subclass of another Objective-C class 320 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) { 321 // Objective-C interfaces can be used in a class property expression. 322 if (ID->getDefinition()) 323 Contexts |= (1LL << CodeCompletionContext::CCC_Expression); 324 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName); 325 } 326 327 // Deal with tag names. 328 if (isa<EnumDecl>(ND)) { 329 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag); 330 331 // Part of the nested-name-specifier in C++0x. 332 if (LangOpts.CPlusPlus11) 333 IsNestedNameSpecifier = true; 334 } else if (const auto *Record = dyn_cast<RecordDecl>(ND)) { 335 if (Record->isUnion()) 336 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag); 337 else 338 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag); 339 340 if (LangOpts.CPlusPlus) 341 IsNestedNameSpecifier = true; 342 } else if (isa<ClassTemplateDecl>(ND)) 343 IsNestedNameSpecifier = true; 344 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 345 // Values can appear in these contexts. 346 Contexts = (1LL << CodeCompletionContext::CCC_Statement) 347 | (1LL << CodeCompletionContext::CCC_Expression) 348 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression) 349 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver); 350 } else if (isa<ObjCProtocolDecl>(ND)) { 351 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName); 352 } else if (isa<ObjCCategoryDecl>(ND)) { 353 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName); 354 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) { 355 Contexts = (1LL << CodeCompletionContext::CCC_Namespace); 356 357 // Part of the nested-name-specifier. 358 IsNestedNameSpecifier = true; 359 } 360 361 return Contexts; 362 } 363 364 void ASTUnit::CacheCodeCompletionResults() { 365 if (!TheSema) 366 return; 367 368 SimpleTimer Timer(WantTiming); 369 Timer.setOutput("Cache global code completions for " + getMainFileName()); 370 371 // Clear out the previous results. 372 ClearCachedCompletionResults(); 373 374 // Gather the set of global code completions. 375 using Result = CodeCompletionResult; 376 SmallVector<Result, 8> Results; 377 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>(); 378 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator); 379 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, 380 CCTUInfo, Results); 381 382 // Translate global code completions into cached completions. 383 llvm::DenseMap<CanQualType, unsigned> CompletionTypes; 384 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel); 385 386 for (auto &R : Results) { 387 switch (R.Kind) { 388 case Result::RK_Declaration: { 389 bool IsNestedNameSpecifier = false; 390 CachedCodeCompletionResult CachedResult; 391 CachedResult.Completion = R.CreateCodeCompletionString( 392 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo, 393 IncludeBriefCommentsInCodeCompletion); 394 CachedResult.ShowInContexts = getDeclShowContexts( 395 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier); 396 CachedResult.Priority = R.Priority; 397 CachedResult.Kind = R.CursorKind; 398 CachedResult.Availability = R.Availability; 399 400 // Keep track of the type of this completion in an ASTContext-agnostic 401 // way. 402 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration); 403 if (UsageType.isNull()) { 404 CachedResult.TypeClass = STC_Void; 405 CachedResult.Type = 0; 406 } else { 407 CanQualType CanUsageType 408 = Ctx->getCanonicalType(UsageType.getUnqualifiedType()); 409 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType); 410 411 // Determine whether we have already seen this type. If so, we save 412 // ourselves the work of formatting the type string by using the 413 // temporary, CanQualType-based hash table to find the associated value. 414 unsigned &TypeValue = CompletionTypes[CanUsageType]; 415 if (TypeValue == 0) { 416 TypeValue = CompletionTypes.size(); 417 CachedCompletionTypes[QualType(CanUsageType).getAsString()] 418 = TypeValue; 419 } 420 421 CachedResult.Type = TypeValue; 422 } 423 424 CachedCompletionResults.push_back(CachedResult); 425 426 /// Handle nested-name-specifiers in C++. 427 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier && 428 !R.StartsNestedNameSpecifier) { 429 // The contexts in which a nested-name-specifier can appear in C++. 430 uint64_t NNSContexts 431 = (1LL << CodeCompletionContext::CCC_TopLevel) 432 | (1LL << CodeCompletionContext::CCC_ObjCIvarList) 433 | (1LL << CodeCompletionContext::CCC_ClassStructUnion) 434 | (1LL << CodeCompletionContext::CCC_Statement) 435 | (1LL << CodeCompletionContext::CCC_Expression) 436 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver) 437 | (1LL << CodeCompletionContext::CCC_EnumTag) 438 | (1LL << CodeCompletionContext::CCC_UnionTag) 439 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag) 440 | (1LL << CodeCompletionContext::CCC_Type) 441 | (1LL << CodeCompletionContext::CCC_SymbolOrNewName) 442 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression); 443 444 if (isa<NamespaceDecl>(R.Declaration) || 445 isa<NamespaceAliasDecl>(R.Declaration)) 446 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace); 447 448 if (uint64_t RemainingContexts 449 = NNSContexts & ~CachedResult.ShowInContexts) { 450 // If there any contexts where this completion can be a 451 // nested-name-specifier but isn't already an option, create a 452 // nested-name-specifier completion. 453 R.StartsNestedNameSpecifier = true; 454 CachedResult.Completion = R.CreateCodeCompletionString( 455 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo, 456 IncludeBriefCommentsInCodeCompletion); 457 CachedResult.ShowInContexts = RemainingContexts; 458 CachedResult.Priority = CCP_NestedNameSpecifier; 459 CachedResult.TypeClass = STC_Void; 460 CachedResult.Type = 0; 461 CachedCompletionResults.push_back(CachedResult); 462 } 463 } 464 break; 465 } 466 467 case Result::RK_Keyword: 468 case Result::RK_Pattern: 469 // Ignore keywords and patterns; we don't care, since they are so 470 // easily regenerated. 471 break; 472 473 case Result::RK_Macro: { 474 CachedCodeCompletionResult CachedResult; 475 CachedResult.Completion = R.CreateCodeCompletionString( 476 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo, 477 IncludeBriefCommentsInCodeCompletion); 478 CachedResult.ShowInContexts 479 = (1LL << CodeCompletionContext::CCC_TopLevel) 480 | (1LL << CodeCompletionContext::CCC_ObjCInterface) 481 | (1LL << CodeCompletionContext::CCC_ObjCImplementation) 482 | (1LL << CodeCompletionContext::CCC_ObjCIvarList) 483 | (1LL << CodeCompletionContext::CCC_ClassStructUnion) 484 | (1LL << CodeCompletionContext::CCC_Statement) 485 | (1LL << CodeCompletionContext::CCC_Expression) 486 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver) 487 | (1LL << CodeCompletionContext::CCC_MacroNameUse) 488 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression) 489 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression) 490 | (1LL << CodeCompletionContext::CCC_OtherWithMacros); 491 492 CachedResult.Priority = R.Priority; 493 CachedResult.Kind = R.CursorKind; 494 CachedResult.Availability = R.Availability; 495 CachedResult.TypeClass = STC_Void; 496 CachedResult.Type = 0; 497 CachedCompletionResults.push_back(CachedResult); 498 break; 499 } 500 } 501 } 502 503 // Save the current top-level hash value. 504 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue; 505 } 506 507 void ASTUnit::ClearCachedCompletionResults() { 508 CachedCompletionResults.clear(); 509 CachedCompletionTypes.clear(); 510 CachedCompletionAllocator = nullptr; 511 } 512 513 namespace { 514 515 /// Gathers information from ASTReader that will be used to initialize 516 /// a Preprocessor. 517 class ASTInfoCollector : public ASTReaderListener { 518 Preprocessor &PP; 519 ASTContext *Context; 520 HeaderSearchOptions &HSOpts; 521 PreprocessorOptions &PPOpts; 522 LangOptions &LangOpt; 523 std::shared_ptr<TargetOptions> &TargetOpts; 524 IntrusiveRefCntPtr<TargetInfo> &Target; 525 unsigned &Counter; 526 bool InitializedLanguage = false; 527 528 public: 529 ASTInfoCollector(Preprocessor &PP, ASTContext *Context, 530 HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts, 531 LangOptions &LangOpt, 532 std::shared_ptr<TargetOptions> &TargetOpts, 533 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter) 534 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts), 535 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target), 536 Counter(Counter) {} 537 538 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, 539 bool AllowCompatibleDifferences) override { 540 if (InitializedLanguage) 541 return false; 542 543 LangOpt = LangOpts; 544 InitializedLanguage = true; 545 546 updated(); 547 return false; 548 } 549 550 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 551 StringRef SpecificModuleCachePath, 552 bool Complain) override { 553 this->HSOpts = HSOpts; 554 return false; 555 } 556 557 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, 558 std::string &SuggestedPredefines) override { 559 this->PPOpts = PPOpts; 560 return false; 561 } 562 563 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, 564 bool AllowCompatibleDifferences) override { 565 // If we've already initialized the target, don't do it again. 566 if (Target) 567 return false; 568 569 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts); 570 Target = 571 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts); 572 573 updated(); 574 return false; 575 } 576 577 void ReadCounter(const serialization::ModuleFile &M, 578 unsigned Value) override { 579 Counter = Value; 580 } 581 582 private: 583 void updated() { 584 if (!Target || !InitializedLanguage) 585 return; 586 587 // Inform the target of the language options. 588 // 589 // FIXME: We shouldn't need to do this, the target should be immutable once 590 // created. This complexity should be lifted elsewhere. 591 Target->adjust(LangOpt); 592 593 // Initialize the preprocessor. 594 PP.Initialize(*Target); 595 596 if (!Context) 597 return; 598 599 // Initialize the ASTContext 600 Context->InitBuiltinTypes(*Target); 601 602 // Adjust printing policy based on language options. 603 Context->setPrintingPolicy(PrintingPolicy(LangOpt)); 604 605 // We didn't have access to the comment options when the ASTContext was 606 // constructed, so register them now. 607 Context->getCommentCommandTraits().registerCommentOptions( 608 LangOpt.CommentOpts); 609 } 610 }; 611 612 /// Diagnostic consumer that saves each diagnostic it is given. 613 class FilterAndStoreDiagnosticConsumer : public DiagnosticConsumer { 614 SmallVectorImpl<StoredDiagnostic> *StoredDiags; 615 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags; 616 bool CaptureNonErrorsFromIncludes = true; 617 const LangOptions *LangOpts = nullptr; 618 SourceManager *SourceMgr = nullptr; 619 620 public: 621 FilterAndStoreDiagnosticConsumer( 622 SmallVectorImpl<StoredDiagnostic> *StoredDiags, 623 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags, 624 bool CaptureNonErrorsFromIncludes) 625 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags), 626 CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes) { 627 assert((StoredDiags || StandaloneDiags) && 628 "No output collections were passed to StoredDiagnosticConsumer."); 629 } 630 631 void BeginSourceFile(const LangOptions &LangOpts, 632 const Preprocessor *PP = nullptr) override { 633 this->LangOpts = &LangOpts; 634 if (PP) 635 SourceMgr = &PP->getSourceManager(); 636 } 637 638 void HandleDiagnostic(DiagnosticsEngine::Level Level, 639 const Diagnostic &Info) override; 640 }; 641 642 /// RAII object that optionally captures and filters diagnostics, if 643 /// there is no diagnostic client to capture them already. 644 class CaptureDroppedDiagnostics { 645 DiagnosticsEngine &Diags; 646 FilterAndStoreDiagnosticConsumer Client; 647 DiagnosticConsumer *PreviousClient = nullptr; 648 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient; 649 650 public: 651 CaptureDroppedDiagnostics( 652 CaptureDiagsKind CaptureDiagnostics, DiagnosticsEngine &Diags, 653 SmallVectorImpl<StoredDiagnostic> *StoredDiags, 654 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags) 655 : Diags(Diags), 656 Client(StoredDiags, StandaloneDiags, 657 CaptureDiagnostics != 658 CaptureDiagsKind::AllWithoutNonErrorsFromIncludes) { 659 if (CaptureDiagnostics != CaptureDiagsKind::None || 660 Diags.getClient() == nullptr) { 661 OwningPreviousClient = Diags.takeClient(); 662 PreviousClient = Diags.getClient(); 663 Diags.setClient(&Client, false); 664 } 665 } 666 667 ~CaptureDroppedDiagnostics() { 668 if (Diags.getClient() == &Client) 669 Diags.setClient(PreviousClient, !!OwningPreviousClient.release()); 670 } 671 }; 672 673 } // namespace 674 675 static ASTUnit::StandaloneDiagnostic 676 makeStandaloneDiagnostic(const LangOptions &LangOpts, 677 const StoredDiagnostic &InDiag); 678 679 static bool isInMainFile(const clang::Diagnostic &D) { 680 if (!D.hasSourceManager() || !D.getLocation().isValid()) 681 return false; 682 683 auto &M = D.getSourceManager(); 684 return M.isWrittenInMainFile(M.getExpansionLoc(D.getLocation())); 685 } 686 687 void FilterAndStoreDiagnosticConsumer::HandleDiagnostic( 688 DiagnosticsEngine::Level Level, const Diagnostic &Info) { 689 // Default implementation (Warnings/errors count). 690 DiagnosticConsumer::HandleDiagnostic(Level, Info); 691 692 // Only record the diagnostic if it's part of the source manager we know 693 // about. This effectively drops diagnostics from modules we're building. 694 // FIXME: In the long run, ee don't want to drop source managers from modules. 695 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) { 696 if (!CaptureNonErrorsFromIncludes && Level <= DiagnosticsEngine::Warning && 697 !isInMainFile(Info)) { 698 return; 699 } 700 701 StoredDiagnostic *ResultDiag = nullptr; 702 if (StoredDiags) { 703 StoredDiags->emplace_back(Level, Info); 704 ResultDiag = &StoredDiags->back(); 705 } 706 707 if (StandaloneDiags) { 708 llvm::Optional<StoredDiagnostic> StoredDiag = None; 709 if (!ResultDiag) { 710 StoredDiag.emplace(Level, Info); 711 ResultDiag = StoredDiag.getPointer(); 712 } 713 StandaloneDiags->push_back( 714 makeStandaloneDiagnostic(*LangOpts, *ResultDiag)); 715 } 716 } 717 } 718 719 IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const { 720 return Reader; 721 } 722 723 ASTMutationListener *ASTUnit::getASTMutationListener() { 724 if (WriterData) 725 return &WriterData->Writer; 726 return nullptr; 727 } 728 729 ASTDeserializationListener *ASTUnit::getDeserializationListener() { 730 if (WriterData) 731 return &WriterData->Writer; 732 return nullptr; 733 } 734 735 std::unique_ptr<llvm::MemoryBuffer> 736 ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) { 737 assert(FileMgr); 738 auto Buffer = FileMgr->getBufferForFile(Filename, UserFilesAreVolatile); 739 if (Buffer) 740 return std::move(*Buffer); 741 if (ErrorStr) 742 *ErrorStr = Buffer.getError().message(); 743 return nullptr; 744 } 745 746 /// Configure the diagnostics object for use with ASTUnit. 747 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags, 748 ASTUnit &AST, 749 CaptureDiagsKind CaptureDiagnostics) { 750 assert(Diags.get() && "no DiagnosticsEngine was provided"); 751 if (CaptureDiagnostics != CaptureDiagsKind::None) 752 Diags->setClient(new FilterAndStoreDiagnosticConsumer( 753 &AST.StoredDiagnostics, nullptr, 754 CaptureDiagnostics != CaptureDiagsKind::AllWithoutNonErrorsFromIncludes)); 755 } 756 757 std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile( 758 const std::string &Filename, const PCHContainerReader &PCHContainerRdr, 759 WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags, 760 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo, 761 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles, 762 CaptureDiagsKind CaptureDiagnostics, bool AllowASTWithCompilerErrors, 763 bool UserFilesAreVolatile) { 764 std::unique_ptr<ASTUnit> AST(new ASTUnit(true)); 765 766 // Recover resources if we crash before exiting this method. 767 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> 768 ASTUnitCleanup(AST.get()); 769 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, 770 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>> 771 DiagCleanup(Diags.get()); 772 773 ConfigureDiags(Diags, *AST, CaptureDiagnostics); 774 775 AST->LangOpts = std::make_shared<LangOptions>(); 776 AST->OnlyLocalDecls = OnlyLocalDecls; 777 AST->CaptureDiagnostics = CaptureDiagnostics; 778 AST->Diagnostics = Diags; 779 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = 780 llvm::vfs::getRealFileSystem(); 781 AST->FileMgr = new FileManager(FileSystemOpts, VFS); 782 AST->UserFilesAreVolatile = UserFilesAreVolatile; 783 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), 784 AST->getFileManager(), 785 UserFilesAreVolatile); 786 AST->ModuleCache = new InMemoryModuleCache; 787 AST->HSOpts = std::make_shared<HeaderSearchOptions>(); 788 AST->HSOpts->ModuleFormat = std::string(PCHContainerRdr.getFormat()); 789 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts, 790 AST->getSourceManager(), 791 AST->getDiagnostics(), 792 AST->getLangOpts(), 793 /*Target=*/nullptr)); 794 AST->PPOpts = std::make_shared<PreprocessorOptions>(); 795 796 for (const auto &RemappedFile : RemappedFiles) 797 AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second); 798 799 // Gather Info for preprocessor construction later on. 800 801 HeaderSearch &HeaderInfo = *AST->HeaderInfo; 802 unsigned Counter; 803 804 AST->PP = std::make_shared<Preprocessor>( 805 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts, 806 AST->getSourceManager(), HeaderInfo, AST->ModuleLoader, 807 /*IILookup=*/nullptr, 808 /*OwnsHeaderSearch=*/false); 809 Preprocessor &PP = *AST->PP; 810 811 if (ToLoad >= LoadASTOnly) 812 AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(), 813 PP.getIdentifierTable(), PP.getSelectorTable(), 814 PP.getBuiltinInfo()); 815 816 bool disableValid = false; 817 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION")) 818 disableValid = true; 819 AST->Reader = new ASTReader( 820 PP, *AST->ModuleCache, AST->Ctx.get(), PCHContainerRdr, {}, 821 /*isysroot=*/"", 822 /*DisableValidation=*/disableValid, AllowASTWithCompilerErrors); 823 824 AST->Reader->setListener(std::make_unique<ASTInfoCollector>( 825 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts, 826 AST->TargetOpts, AST->Target, Counter)); 827 828 // Attach the AST reader to the AST context as an external AST 829 // source, so that declarations will be deserialized from the 830 // AST file as needed. 831 // We need the external source to be set up before we read the AST, because 832 // eagerly-deserialized declarations may use it. 833 if (AST->Ctx) 834 AST->Ctx->setExternalSource(AST->Reader); 835 836 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile, 837 SourceLocation(), ASTReader::ARR_None)) { 838 case ASTReader::Success: 839 break; 840 841 case ASTReader::Failure: 842 case ASTReader::Missing: 843 case ASTReader::OutOfDate: 844 case ASTReader::VersionMismatch: 845 case ASTReader::ConfigurationMismatch: 846 case ASTReader::HadErrors: 847 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch); 848 return nullptr; 849 } 850 851 AST->OriginalSourceFile = std::string(AST->Reader->getOriginalSourceFile()); 852 853 PP.setCounterValue(Counter); 854 855 // Create an AST consumer, even though it isn't used. 856 if (ToLoad >= LoadASTOnly) 857 AST->Consumer.reset(new ASTConsumer); 858 859 // Create a semantic analysis object and tell the AST reader about it. 860 if (ToLoad >= LoadEverything) { 861 AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer)); 862 AST->TheSema->Initialize(); 863 AST->Reader->InitializeSema(*AST->TheSema); 864 } 865 866 // Tell the diagnostic client that we have started a source file. 867 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP); 868 869 return AST; 870 } 871 872 /// Add the given macro to the hash of all top-level entities. 873 static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) { 874 Hash = llvm::djbHash(MacroNameTok.getIdentifierInfo()->getName(), Hash); 875 } 876 877 namespace { 878 879 /// Preprocessor callback class that updates a hash value with the names 880 /// of all macros that have been defined by the translation unit. 881 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks { 882 unsigned &Hash; 883 884 public: 885 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) {} 886 887 void MacroDefined(const Token &MacroNameTok, 888 const MacroDirective *MD) override { 889 AddDefinedMacroToHash(MacroNameTok, Hash); 890 } 891 }; 892 893 } // namespace 894 895 /// Add the given declaration to the hash of all top-level entities. 896 static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) { 897 if (!D) 898 return; 899 900 DeclContext *DC = D->getDeclContext(); 901 if (!DC) 902 return; 903 904 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit())) 905 return; 906 907 if (const auto *ND = dyn_cast<NamedDecl>(D)) { 908 if (const auto *EnumD = dyn_cast<EnumDecl>(D)) { 909 // For an unscoped enum include the enumerators in the hash since they 910 // enter the top-level namespace. 911 if (!EnumD->isScoped()) { 912 for (const auto *EI : EnumD->enumerators()) { 913 if (EI->getIdentifier()) 914 Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash); 915 } 916 } 917 } 918 919 if (ND->getIdentifier()) 920 Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash); 921 else if (DeclarationName Name = ND->getDeclName()) { 922 std::string NameStr = Name.getAsString(); 923 Hash = llvm::djbHash(NameStr, Hash); 924 } 925 return; 926 } 927 928 if (const auto *ImportD = dyn_cast<ImportDecl>(D)) { 929 if (const Module *Mod = ImportD->getImportedModule()) { 930 std::string ModName = Mod->getFullModuleName(); 931 Hash = llvm::djbHash(ModName, Hash); 932 } 933 return; 934 } 935 } 936 937 namespace { 938 939 class TopLevelDeclTrackerConsumer : public ASTConsumer { 940 ASTUnit &Unit; 941 unsigned &Hash; 942 943 public: 944 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash) 945 : Unit(_Unit), Hash(Hash) { 946 Hash = 0; 947 } 948 949 void handleTopLevelDecl(Decl *D) { 950 if (!D) 951 return; 952 953 // FIXME: Currently ObjC method declarations are incorrectly being 954 // reported as top-level declarations, even though their DeclContext 955 // is the containing ObjC @interface/@implementation. This is a 956 // fundamental problem in the parser right now. 957 if (isa<ObjCMethodDecl>(D)) 958 return; 959 960 AddTopLevelDeclarationToHash(D, Hash); 961 Unit.addTopLevelDecl(D); 962 963 handleFileLevelDecl(D); 964 } 965 966 void handleFileLevelDecl(Decl *D) { 967 Unit.addFileLevelDecl(D); 968 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) { 969 for (auto *I : NSD->decls()) 970 handleFileLevelDecl(I); 971 } 972 } 973 974 bool HandleTopLevelDecl(DeclGroupRef D) override { 975 for (auto *TopLevelDecl : D) 976 handleTopLevelDecl(TopLevelDecl); 977 return true; 978 } 979 980 // We're not interested in "interesting" decls. 981 void HandleInterestingDecl(DeclGroupRef) override {} 982 983 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override { 984 for (auto *TopLevelDecl : D) 985 handleTopLevelDecl(TopLevelDecl); 986 } 987 988 ASTMutationListener *GetASTMutationListener() override { 989 return Unit.getASTMutationListener(); 990 } 991 992 ASTDeserializationListener *GetASTDeserializationListener() override { 993 return Unit.getDeserializationListener(); 994 } 995 }; 996 997 class TopLevelDeclTrackerAction : public ASTFrontendAction { 998 public: 999 ASTUnit &Unit; 1000 1001 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, 1002 StringRef InFile) override { 1003 CI.getPreprocessor().addPPCallbacks( 1004 std::make_unique<MacroDefinitionTrackerPPCallbacks>( 1005 Unit.getCurrentTopLevelHashValue())); 1006 return std::make_unique<TopLevelDeclTrackerConsumer>( 1007 Unit, Unit.getCurrentTopLevelHashValue()); 1008 } 1009 1010 public: 1011 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {} 1012 1013 bool hasCodeCompletionSupport() const override { return false; } 1014 1015 TranslationUnitKind getTranslationUnitKind() override { 1016 return Unit.getTranslationUnitKind(); 1017 } 1018 }; 1019 1020 class ASTUnitPreambleCallbacks : public PreambleCallbacks { 1021 public: 1022 unsigned getHash() const { return Hash; } 1023 1024 std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); } 1025 1026 std::vector<serialization::DeclID> takeTopLevelDeclIDs() { 1027 return std::move(TopLevelDeclIDs); 1028 } 1029 1030 void AfterPCHEmitted(ASTWriter &Writer) override { 1031 TopLevelDeclIDs.reserve(TopLevelDecls.size()); 1032 for (const auto *D : TopLevelDecls) { 1033 // Invalid top-level decls may not have been serialized. 1034 if (D->isInvalidDecl()) 1035 continue; 1036 TopLevelDeclIDs.push_back(Writer.getDeclID(D)); 1037 } 1038 } 1039 1040 void HandleTopLevelDecl(DeclGroupRef DG) override { 1041 for (auto *D : DG) { 1042 // FIXME: Currently ObjC method declarations are incorrectly being 1043 // reported as top-level declarations, even though their DeclContext 1044 // is the containing ObjC @interface/@implementation. This is a 1045 // fundamental problem in the parser right now. 1046 if (isa<ObjCMethodDecl>(D)) 1047 continue; 1048 AddTopLevelDeclarationToHash(D, Hash); 1049 TopLevelDecls.push_back(D); 1050 } 1051 } 1052 1053 std::unique_ptr<PPCallbacks> createPPCallbacks() override { 1054 return std::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash); 1055 } 1056 1057 private: 1058 unsigned Hash = 0; 1059 std::vector<Decl *> TopLevelDecls; 1060 std::vector<serialization::DeclID> TopLevelDeclIDs; 1061 llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags; 1062 }; 1063 1064 } // namespace 1065 1066 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) { 1067 return StoredDiag.getLocation().isValid(); 1068 } 1069 1070 static void 1071 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) { 1072 // Get rid of stored diagnostics except the ones from the driver which do not 1073 // have a source location. 1074 StoredDiags.erase( 1075 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag), 1076 StoredDiags.end()); 1077 } 1078 1079 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> & 1080 StoredDiagnostics, 1081 SourceManager &SM) { 1082 // The stored diagnostic has the old source manager in it; update 1083 // the locations to refer into the new source manager. Since we've 1084 // been careful to make sure that the source manager's state 1085 // before and after are identical, so that we can reuse the source 1086 // location itself. 1087 for (auto &SD : StoredDiagnostics) { 1088 if (SD.getLocation().isValid()) { 1089 FullSourceLoc Loc(SD.getLocation(), SM); 1090 SD.setLocation(Loc); 1091 } 1092 } 1093 } 1094 1095 /// Parse the source file into a translation unit using the given compiler 1096 /// invocation, replacing the current translation unit. 1097 /// 1098 /// \returns True if a failure occurred that causes the ASTUnit not to 1099 /// contain any translation-unit information, false otherwise. 1100 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, 1101 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer, 1102 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { 1103 if (!Invocation) 1104 return true; 1105 1106 if (VFS && FileMgr) 1107 assert(VFS == &FileMgr->getVirtualFileSystem() && 1108 "VFS passed to Parse and VFS in FileMgr are different"); 1109 1110 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation); 1111 if (OverrideMainBuffer) { 1112 assert(Preamble && 1113 "No preamble was built, but OverrideMainBuffer is not null"); 1114 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get()); 1115 // VFS may have changed... 1116 } 1117 1118 // Create the compiler instance to use for building the AST. 1119 std::unique_ptr<CompilerInstance> Clang( 1120 new CompilerInstance(std::move(PCHContainerOps))); 1121 1122 // Clean up on error, disengage it if the function returns successfully. 1123 auto CleanOnError = llvm::make_scope_exit([&]() { 1124 // Remove the overridden buffer we used for the preamble. 1125 SavedMainFileBuffer = nullptr; 1126 1127 // Keep the ownership of the data in the ASTUnit because the client may 1128 // want to see the diagnostics. 1129 transferASTDataFromCompilerInstance(*Clang); 1130 FailedParseDiagnostics.swap(StoredDiagnostics); 1131 StoredDiagnostics.clear(); 1132 NumStoredDiagnosticsFromDriver = 0; 1133 }); 1134 1135 // Ensure that Clang has a FileManager with the right VFS, which may have 1136 // changed above in AddImplicitPreamble. If VFS is nullptr, rely on 1137 // createFileManager to create one. 1138 if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS) 1139 Clang->setFileManager(&*FileMgr); 1140 else 1141 FileMgr = Clang->createFileManager(std::move(VFS)); 1142 1143 // Recover resources if we crash before exiting this method. 1144 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> 1145 CICleanup(Clang.get()); 1146 1147 Clang->setInvocation(CCInvocation); 1148 OriginalSourceFile = 1149 std::string(Clang->getFrontendOpts().Inputs[0].getFile()); 1150 1151 // Set up diagnostics, capturing any diagnostics that would 1152 // otherwise be dropped. 1153 Clang->setDiagnostics(&getDiagnostics()); 1154 1155 // Create the target instance. 1156 Clang->setTarget(TargetInfo::CreateTargetInfo( 1157 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts)); 1158 if (!Clang->hasTarget()) 1159 return true; 1160 1161 // Inform the target of the language options. 1162 // 1163 // FIXME: We shouldn't need to do this, the target should be immutable once 1164 // created. This complexity should be lifted elsewhere. 1165 Clang->getTarget().adjust(Clang->getLangOpts()); 1166 1167 assert(Clang->getFrontendOpts().Inputs.size() == 1 && 1168 "Invocation must have exactly one source file!"); 1169 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() == 1170 InputKind::Source && 1171 "FIXME: AST inputs not yet supported here!"); 1172 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() != 1173 Language::LLVM_IR && 1174 "IR inputs not support here!"); 1175 1176 // Configure the various subsystems. 1177 LangOpts = Clang->getInvocation().LangOpts; 1178 FileSystemOpts = Clang->getFileSystemOpts(); 1179 1180 ResetForParse(); 1181 1182 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr, 1183 UserFilesAreVolatile); 1184 if (!OverrideMainBuffer) { 1185 checkAndRemoveNonDriverDiags(StoredDiagnostics); 1186 TopLevelDeclsInPreamble.clear(); 1187 } 1188 1189 // Create the source manager. 1190 Clang->setSourceManager(&getSourceManager()); 1191 1192 // If the main file has been overridden due to the use of a preamble, 1193 // make that override happen and introduce the preamble. 1194 if (OverrideMainBuffer) { 1195 // The stored diagnostic has the old source manager in it; update 1196 // the locations to refer into the new source manager. Since we've 1197 // been careful to make sure that the source manager's state 1198 // before and after are identical, so that we can reuse the source 1199 // location itself. 1200 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager()); 1201 1202 // Keep track of the override buffer; 1203 SavedMainFileBuffer = std::move(OverrideMainBuffer); 1204 } 1205 1206 std::unique_ptr<TopLevelDeclTrackerAction> Act( 1207 new TopLevelDeclTrackerAction(*this)); 1208 1209 // Recover resources if we crash before exiting this method. 1210 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction> 1211 ActCleanup(Act.get()); 1212 1213 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) 1214 return true; 1215 1216 if (SavedMainFileBuffer) 1217 TranslateStoredDiagnostics(getFileManager(), getSourceManager(), 1218 PreambleDiagnostics, StoredDiagnostics); 1219 else 1220 PreambleSrcLocCache.clear(); 1221 1222 if (llvm::Error Err = Act->Execute()) { 1223 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 1224 return true; 1225 } 1226 1227 transferASTDataFromCompilerInstance(*Clang); 1228 1229 Act->EndSourceFile(); 1230 1231 FailedParseDiagnostics.clear(); 1232 1233 CleanOnError.release(); 1234 1235 return false; 1236 } 1237 1238 static std::pair<unsigned, unsigned> 1239 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM, 1240 const LangOptions &LangOpts) { 1241 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts); 1242 unsigned Offset = SM.getFileOffset(FileRange.getBegin()); 1243 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd()); 1244 return std::make_pair(Offset, EndOffset); 1245 } 1246 1247 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM, 1248 const LangOptions &LangOpts, 1249 const FixItHint &InFix) { 1250 ASTUnit::StandaloneFixIt OutFix; 1251 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts); 1252 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM, 1253 LangOpts); 1254 OutFix.CodeToInsert = InFix.CodeToInsert; 1255 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions; 1256 return OutFix; 1257 } 1258 1259 static ASTUnit::StandaloneDiagnostic 1260 makeStandaloneDiagnostic(const LangOptions &LangOpts, 1261 const StoredDiagnostic &InDiag) { 1262 ASTUnit::StandaloneDiagnostic OutDiag; 1263 OutDiag.ID = InDiag.getID(); 1264 OutDiag.Level = InDiag.getLevel(); 1265 OutDiag.Message = std::string(InDiag.getMessage()); 1266 OutDiag.LocOffset = 0; 1267 if (InDiag.getLocation().isInvalid()) 1268 return OutDiag; 1269 const SourceManager &SM = InDiag.getLocation().getManager(); 1270 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation()); 1271 OutDiag.Filename = std::string(SM.getFilename(FileLoc)); 1272 if (OutDiag.Filename.empty()) 1273 return OutDiag; 1274 OutDiag.LocOffset = SM.getFileOffset(FileLoc); 1275 for (const auto &Range : InDiag.getRanges()) 1276 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts)); 1277 for (const auto &FixIt : InDiag.getFixIts()) 1278 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt)); 1279 1280 return OutDiag; 1281 } 1282 1283 /// Attempt to build or re-use a precompiled preamble when (re-)parsing 1284 /// the source file. 1285 /// 1286 /// This routine will compute the preamble of the main source file. If a 1287 /// non-trivial preamble is found, it will precompile that preamble into a 1288 /// precompiled header so that the precompiled preamble can be used to reduce 1289 /// reparsing time. If a precompiled preamble has already been constructed, 1290 /// this routine will determine if it is still valid and, if so, avoid 1291 /// rebuilding the precompiled preamble. 1292 /// 1293 /// \param AllowRebuild When true (the default), this routine is 1294 /// allowed to rebuild the precompiled preamble if it is found to be 1295 /// out-of-date. 1296 /// 1297 /// \param MaxLines When non-zero, the maximum number of lines that 1298 /// can occur within the preamble. 1299 /// 1300 /// \returns If the precompiled preamble can be used, returns a newly-allocated 1301 /// buffer that should be used in place of the main file when doing so. 1302 /// Otherwise, returns a NULL pointer. 1303 std::unique_ptr<llvm::MemoryBuffer> 1304 ASTUnit::getMainBufferWithPrecompiledPreamble( 1305 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 1306 CompilerInvocation &PreambleInvocationIn, 1307 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, bool AllowRebuild, 1308 unsigned MaxLines) { 1309 auto MainFilePath = 1310 PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile(); 1311 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer = 1312 getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(), 1313 MainFilePath, UserFilesAreVolatile); 1314 if (!MainFileBuffer) 1315 return nullptr; 1316 1317 PreambleBounds Bounds = ComputePreambleBounds( 1318 *PreambleInvocationIn.getLangOpts(), *MainFileBuffer, MaxLines); 1319 if (!Bounds.Size) 1320 return nullptr; 1321 1322 if (Preamble) { 1323 if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds, 1324 VFS.get())) { 1325 // Okay! We can re-use the precompiled preamble. 1326 1327 // Set the state of the diagnostic object to mimic its state 1328 // after parsing the preamble. 1329 getDiagnostics().Reset(); 1330 ProcessWarningOptions(getDiagnostics(), 1331 PreambleInvocationIn.getDiagnosticOpts()); 1332 getDiagnostics().setNumWarnings(NumWarningsInPreamble); 1333 1334 PreambleRebuildCountdown = 1; 1335 return MainFileBuffer; 1336 } else { 1337 Preamble.reset(); 1338 PreambleDiagnostics.clear(); 1339 TopLevelDeclsInPreamble.clear(); 1340 PreambleSrcLocCache.clear(); 1341 PreambleRebuildCountdown = 1; 1342 } 1343 } 1344 1345 // If the preamble rebuild counter > 1, it's because we previously 1346 // failed to build a preamble and we're not yet ready to try 1347 // again. Decrement the counter and return a failure. 1348 if (PreambleRebuildCountdown > 1) { 1349 --PreambleRebuildCountdown; 1350 return nullptr; 1351 } 1352 1353 assert(!Preamble && "No Preamble should be stored at that point"); 1354 // If we aren't allowed to rebuild the precompiled preamble, just 1355 // return now. 1356 if (!AllowRebuild) 1357 return nullptr; 1358 1359 ++PreambleCounter; 1360 1361 SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone; 1362 SmallVector<StoredDiagnostic, 4> NewPreambleDiags; 1363 ASTUnitPreambleCallbacks Callbacks; 1364 { 1365 llvm::Optional<CaptureDroppedDiagnostics> Capture; 1366 if (CaptureDiagnostics != CaptureDiagsKind::None) 1367 Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags, 1368 &NewPreambleDiagsStandalone); 1369 1370 // We did not previously compute a preamble, or it can't be reused anyway. 1371 SimpleTimer PreambleTimer(WantTiming); 1372 PreambleTimer.setOutput("Precompiling preamble"); 1373 1374 const bool PreviousSkipFunctionBodies = 1375 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies; 1376 if (SkipFunctionBodies == SkipFunctionBodiesScope::Preamble) 1377 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true; 1378 1379 llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build( 1380 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS, 1381 PCHContainerOps, /*StoreInMemory=*/false, Callbacks); 1382 1383 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = 1384 PreviousSkipFunctionBodies; 1385 1386 if (NewPreamble) { 1387 Preamble = std::move(*NewPreamble); 1388 PreambleRebuildCountdown = 1; 1389 } else { 1390 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) { 1391 case BuildPreambleError::CouldntCreateTempFile: 1392 // Try again next time. 1393 PreambleRebuildCountdown = 1; 1394 return nullptr; 1395 case BuildPreambleError::CouldntCreateTargetInfo: 1396 case BuildPreambleError::BeginSourceFileFailed: 1397 case BuildPreambleError::CouldntEmitPCH: 1398 case BuildPreambleError::BadInputs: 1399 // These erros are more likely to repeat, retry after some period. 1400 PreambleRebuildCountdown = DefaultPreambleRebuildInterval; 1401 return nullptr; 1402 } 1403 llvm_unreachable("unexpected BuildPreambleError"); 1404 } 1405 } 1406 1407 assert(Preamble && "Preamble wasn't built"); 1408 1409 TopLevelDecls.clear(); 1410 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs(); 1411 PreambleTopLevelHashValue = Callbacks.getHash(); 1412 1413 NumWarningsInPreamble = getDiagnostics().getNumWarnings(); 1414 1415 checkAndRemoveNonDriverDiags(NewPreambleDiags); 1416 StoredDiagnostics = std::move(NewPreambleDiags); 1417 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone); 1418 1419 // If the hash of top-level entities differs from the hash of the top-level 1420 // entities the last time we rebuilt the preamble, clear out the completion 1421 // cache. 1422 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) { 1423 CompletionCacheTopLevelHashValue = 0; 1424 PreambleTopLevelHashValue = CurrentTopLevelHashValue; 1425 } 1426 1427 return MainFileBuffer; 1428 } 1429 1430 void ASTUnit::RealizeTopLevelDeclsFromPreamble() { 1431 assert(Preamble && "Should only be called when preamble was built"); 1432 1433 std::vector<Decl *> Resolved; 1434 Resolved.reserve(TopLevelDeclsInPreamble.size()); 1435 ExternalASTSource &Source = *getASTContext().getExternalSource(); 1436 for (const auto TopLevelDecl : TopLevelDeclsInPreamble) { 1437 // Resolve the declaration ID to an actual declaration, possibly 1438 // deserializing the declaration in the process. 1439 if (Decl *D = Source.GetExternalDecl(TopLevelDecl)) 1440 Resolved.push_back(D); 1441 } 1442 TopLevelDeclsInPreamble.clear(); 1443 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end()); 1444 } 1445 1446 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) { 1447 // Steal the created target, context, and preprocessor if they have been 1448 // created. 1449 assert(CI.hasInvocation() && "missing invocation"); 1450 LangOpts = CI.getInvocation().LangOpts; 1451 TheSema = CI.takeSema(); 1452 Consumer = CI.takeASTConsumer(); 1453 if (CI.hasASTContext()) 1454 Ctx = &CI.getASTContext(); 1455 if (CI.hasPreprocessor()) 1456 PP = CI.getPreprocessorPtr(); 1457 CI.setSourceManager(nullptr); 1458 CI.setFileManager(nullptr); 1459 if (CI.hasTarget()) 1460 Target = &CI.getTarget(); 1461 Reader = CI.getASTReader(); 1462 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure(); 1463 } 1464 1465 StringRef ASTUnit::getMainFileName() const { 1466 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) { 1467 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0]; 1468 if (Input.isFile()) 1469 return Input.getFile(); 1470 else 1471 return Input.getBuffer().getBufferIdentifier(); 1472 } 1473 1474 if (SourceMgr) { 1475 if (const FileEntry * 1476 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID())) 1477 return FE->getName(); 1478 } 1479 1480 return {}; 1481 } 1482 1483 StringRef ASTUnit::getASTFileName() const { 1484 if (!isMainFileAST()) 1485 return {}; 1486 1487 serialization::ModuleFile & 1488 Mod = Reader->getModuleManager().getPrimaryModule(); 1489 return Mod.FileName; 1490 } 1491 1492 std::unique_ptr<ASTUnit> 1493 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI, 1494 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, 1495 CaptureDiagsKind CaptureDiagnostics, 1496 bool UserFilesAreVolatile) { 1497 std::unique_ptr<ASTUnit> AST(new ASTUnit(false)); 1498 ConfigureDiags(Diags, *AST, CaptureDiagnostics); 1499 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = 1500 createVFSFromCompilerInvocation(*CI, *Diags); 1501 AST->Diagnostics = Diags; 1502 AST->FileSystemOpts = CI->getFileSystemOpts(); 1503 AST->Invocation = std::move(CI); 1504 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS); 1505 AST->UserFilesAreVolatile = UserFilesAreVolatile; 1506 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr, 1507 UserFilesAreVolatile); 1508 AST->ModuleCache = new InMemoryModuleCache; 1509 1510 return AST; 1511 } 1512 1513 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction( 1514 std::shared_ptr<CompilerInvocation> CI, 1515 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 1516 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action, 1517 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath, 1518 bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics, 1519 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults, 1520 bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) { 1521 assert(CI && "A CompilerInvocation is required"); 1522 1523 std::unique_ptr<ASTUnit> OwnAST; 1524 ASTUnit *AST = Unit; 1525 if (!AST) { 1526 // Create the AST unit. 1527 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile); 1528 AST = OwnAST.get(); 1529 if (!AST) 1530 return nullptr; 1531 } 1532 1533 if (!ResourceFilesPath.empty()) { 1534 // Override the resources path. 1535 CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath); 1536 } 1537 AST->OnlyLocalDecls = OnlyLocalDecls; 1538 AST->CaptureDiagnostics = CaptureDiagnostics; 1539 if (PrecompilePreambleAfterNParses > 0) 1540 AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses; 1541 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete; 1542 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults; 1543 AST->IncludeBriefCommentsInCodeCompletion = false; 1544 1545 // Recover resources if we crash before exiting this method. 1546 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> 1547 ASTUnitCleanup(OwnAST.get()); 1548 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, 1549 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>> 1550 DiagCleanup(Diags.get()); 1551 1552 // We'll manage file buffers ourselves. 1553 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true; 1554 CI->getFrontendOpts().DisableFree = false; 1555 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts()); 1556 1557 // Create the compiler instance to use for building the AST. 1558 std::unique_ptr<CompilerInstance> Clang( 1559 new CompilerInstance(std::move(PCHContainerOps))); 1560 1561 // Recover resources if we crash before exiting this method. 1562 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> 1563 CICleanup(Clang.get()); 1564 1565 Clang->setInvocation(std::move(CI)); 1566 AST->OriginalSourceFile = 1567 std::string(Clang->getFrontendOpts().Inputs[0].getFile()); 1568 1569 // Set up diagnostics, capturing any diagnostics that would 1570 // otherwise be dropped. 1571 Clang->setDiagnostics(&AST->getDiagnostics()); 1572 1573 // Create the target instance. 1574 Clang->setTarget(TargetInfo::CreateTargetInfo( 1575 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts)); 1576 if (!Clang->hasTarget()) 1577 return nullptr; 1578 1579 // Inform the target of the language options. 1580 // 1581 // FIXME: We shouldn't need to do this, the target should be immutable once 1582 // created. This complexity should be lifted elsewhere. 1583 Clang->getTarget().adjust(Clang->getLangOpts()); 1584 1585 assert(Clang->getFrontendOpts().Inputs.size() == 1 && 1586 "Invocation must have exactly one source file!"); 1587 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() == 1588 InputKind::Source && 1589 "FIXME: AST inputs not yet supported here!"); 1590 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() != 1591 Language::LLVM_IR && 1592 "IR inputs not support here!"); 1593 1594 // Configure the various subsystems. 1595 AST->TheSema.reset(); 1596 AST->Ctx = nullptr; 1597 AST->PP = nullptr; 1598 AST->Reader = nullptr; 1599 1600 // Create a file manager object to provide access to and cache the filesystem. 1601 Clang->setFileManager(&AST->getFileManager()); 1602 1603 // Create the source manager. 1604 Clang->setSourceManager(&AST->getSourceManager()); 1605 1606 FrontendAction *Act = Action; 1607 1608 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct; 1609 if (!Act) { 1610 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST)); 1611 Act = TrackerAct.get(); 1612 } 1613 1614 // Recover resources if we crash before exiting this method. 1615 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction> 1616 ActCleanup(TrackerAct.get()); 1617 1618 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) { 1619 AST->transferASTDataFromCompilerInstance(*Clang); 1620 if (OwnAST && ErrAST) 1621 ErrAST->swap(OwnAST); 1622 1623 return nullptr; 1624 } 1625 1626 if (Persistent && !TrackerAct) { 1627 Clang->getPreprocessor().addPPCallbacks( 1628 std::make_unique<MacroDefinitionTrackerPPCallbacks>( 1629 AST->getCurrentTopLevelHashValue())); 1630 std::vector<std::unique_ptr<ASTConsumer>> Consumers; 1631 if (Clang->hasASTConsumer()) 1632 Consumers.push_back(Clang->takeASTConsumer()); 1633 Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>( 1634 *AST, AST->getCurrentTopLevelHashValue())); 1635 Clang->setASTConsumer( 1636 std::make_unique<MultiplexConsumer>(std::move(Consumers))); 1637 } 1638 if (llvm::Error Err = Act->Execute()) { 1639 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 1640 AST->transferASTDataFromCompilerInstance(*Clang); 1641 if (OwnAST && ErrAST) 1642 ErrAST->swap(OwnAST); 1643 1644 return nullptr; 1645 } 1646 1647 // Steal the created target, context, and preprocessor. 1648 AST->transferASTDataFromCompilerInstance(*Clang); 1649 1650 Act->EndSourceFile(); 1651 1652 if (OwnAST) 1653 return OwnAST.release(); 1654 else 1655 return AST; 1656 } 1657 1658 bool ASTUnit::LoadFromCompilerInvocation( 1659 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 1660 unsigned PrecompilePreambleAfterNParses, 1661 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { 1662 if (!Invocation) 1663 return true; 1664 1665 assert(VFS && "VFS is null"); 1666 1667 // We'll manage file buffers ourselves. 1668 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true; 1669 Invocation->getFrontendOpts().DisableFree = false; 1670 getDiagnostics().Reset(); 1671 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts()); 1672 1673 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer; 1674 if (PrecompilePreambleAfterNParses > 0) { 1675 PreambleRebuildCountdown = PrecompilePreambleAfterNParses; 1676 OverrideMainBuffer = 1677 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS); 1678 getDiagnostics().Reset(); 1679 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts()); 1680 } 1681 1682 SimpleTimer ParsingTimer(WantTiming); 1683 ParsingTimer.setOutput("Parsing " + getMainFileName()); 1684 1685 // Recover resources if we crash before exiting this method. 1686 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer> 1687 MemBufferCleanup(OverrideMainBuffer.get()); 1688 1689 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS); 1690 } 1691 1692 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation( 1693 std::shared_ptr<CompilerInvocation> CI, 1694 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 1695 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr, 1696 bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics, 1697 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind, 1698 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion, 1699 bool UserFilesAreVolatile) { 1700 // Create the AST unit. 1701 std::unique_ptr<ASTUnit> AST(new ASTUnit(false)); 1702 ConfigureDiags(Diags, *AST, CaptureDiagnostics); 1703 AST->Diagnostics = Diags; 1704 AST->OnlyLocalDecls = OnlyLocalDecls; 1705 AST->CaptureDiagnostics = CaptureDiagnostics; 1706 AST->TUKind = TUKind; 1707 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults; 1708 AST->IncludeBriefCommentsInCodeCompletion 1709 = IncludeBriefCommentsInCodeCompletion; 1710 AST->Invocation = std::move(CI); 1711 AST->FileSystemOpts = FileMgr->getFileSystemOpts(); 1712 AST->FileMgr = FileMgr; 1713 AST->UserFilesAreVolatile = UserFilesAreVolatile; 1714 1715 // Recover resources if we crash before exiting this method. 1716 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> 1717 ASTUnitCleanup(AST.get()); 1718 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, 1719 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>> 1720 DiagCleanup(Diags.get()); 1721 1722 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps), 1723 PrecompilePreambleAfterNParses, 1724 &AST->FileMgr->getVirtualFileSystem())) 1725 return nullptr; 1726 return AST; 1727 } 1728 1729 ASTUnit *ASTUnit::LoadFromCommandLine( 1730 const char **ArgBegin, const char **ArgEnd, 1731 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 1732 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath, 1733 bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics, 1734 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName, 1735 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind, 1736 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion, 1737 bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies, 1738 bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization, 1739 bool RetainExcludedConditionalBlocks, 1740 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST, 1741 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { 1742 assert(Diags.get() && "no DiagnosticsEngine was provided"); 1743 1744 SmallVector<StoredDiagnostic, 4> StoredDiagnostics; 1745 1746 std::shared_ptr<CompilerInvocation> CI; 1747 1748 { 1749 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags, 1750 &StoredDiagnostics, nullptr); 1751 1752 CI = createInvocationFromCommandLine( 1753 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS); 1754 if (!CI) 1755 return nullptr; 1756 } 1757 1758 // Override any files that need remapping 1759 for (const auto &RemappedFile : RemappedFiles) { 1760 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first, 1761 RemappedFile.second); 1762 } 1763 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts(); 1764 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName; 1765 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors; 1766 PPOpts.SingleFileParseMode = SingleFileParse; 1767 PPOpts.RetainExcludedConditionalBlocks = RetainExcludedConditionalBlocks; 1768 1769 // Override the resources path. 1770 CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath); 1771 1772 CI->getFrontendOpts().SkipFunctionBodies = 1773 SkipFunctionBodies == SkipFunctionBodiesScope::PreambleAndMainFile; 1774 1775 if (ModuleFormat) 1776 CI->getHeaderSearchOpts().ModuleFormat = 1777 std::string(ModuleFormat.getValue()); 1778 1779 // Create the AST unit. 1780 std::unique_ptr<ASTUnit> AST; 1781 AST.reset(new ASTUnit(false)); 1782 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size(); 1783 AST->StoredDiagnostics.swap(StoredDiagnostics); 1784 ConfigureDiags(Diags, *AST, CaptureDiagnostics); 1785 AST->Diagnostics = Diags; 1786 AST->FileSystemOpts = CI->getFileSystemOpts(); 1787 if (!VFS) 1788 VFS = llvm::vfs::getRealFileSystem(); 1789 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS); 1790 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS); 1791 AST->ModuleCache = new InMemoryModuleCache; 1792 AST->OnlyLocalDecls = OnlyLocalDecls; 1793 AST->CaptureDiagnostics = CaptureDiagnostics; 1794 AST->TUKind = TUKind; 1795 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults; 1796 AST->IncludeBriefCommentsInCodeCompletion 1797 = IncludeBriefCommentsInCodeCompletion; 1798 AST->UserFilesAreVolatile = UserFilesAreVolatile; 1799 AST->Invocation = CI; 1800 AST->SkipFunctionBodies = SkipFunctionBodies; 1801 if (ForSerialization) 1802 AST->WriterData.reset(new ASTWriterData(*AST->ModuleCache)); 1803 // Zero out now to ease cleanup during crash recovery. 1804 CI = nullptr; 1805 Diags = nullptr; 1806 1807 // Recover resources if we crash before exiting this method. 1808 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> 1809 ASTUnitCleanup(AST.get()); 1810 1811 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps), 1812 PrecompilePreambleAfterNParses, 1813 VFS)) { 1814 // Some error occurred, if caller wants to examine diagnostics, pass it the 1815 // ASTUnit. 1816 if (ErrAST) { 1817 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics); 1818 ErrAST->swap(AST); 1819 } 1820 return nullptr; 1821 } 1822 1823 return AST.release(); 1824 } 1825 1826 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, 1827 ArrayRef<RemappedFile> RemappedFiles, 1828 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { 1829 if (!Invocation) 1830 return true; 1831 1832 if (!VFS) { 1833 assert(FileMgr && "FileMgr is null on Reparse call"); 1834 VFS = &FileMgr->getVirtualFileSystem(); 1835 } 1836 1837 clearFileLevelDecls(); 1838 1839 SimpleTimer ParsingTimer(WantTiming); 1840 ParsingTimer.setOutput("Reparsing " + getMainFileName()); 1841 1842 // Remap files. 1843 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 1844 for (const auto &RB : PPOpts.RemappedFileBuffers) 1845 delete RB.second; 1846 1847 Invocation->getPreprocessorOpts().clearRemappedFiles(); 1848 for (const auto &RemappedFile : RemappedFiles) { 1849 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first, 1850 RemappedFile.second); 1851 } 1852 1853 // If we have a preamble file lying around, or if we might try to 1854 // build a precompiled preamble, do so now. 1855 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer; 1856 if (Preamble || PreambleRebuildCountdown > 0) 1857 OverrideMainBuffer = 1858 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS); 1859 1860 // Clear out the diagnostics state. 1861 FileMgr.reset(); 1862 getDiagnostics().Reset(); 1863 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts()); 1864 if (OverrideMainBuffer) 1865 getDiagnostics().setNumWarnings(NumWarningsInPreamble); 1866 1867 // Parse the sources 1868 bool Result = 1869 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS); 1870 1871 // If we're caching global code-completion results, and the top-level 1872 // declarations have changed, clear out the code-completion cache. 1873 if (!Result && ShouldCacheCodeCompletionResults && 1874 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue) 1875 CacheCodeCompletionResults(); 1876 1877 // We now need to clear out the completion info related to this translation 1878 // unit; it'll be recreated if necessary. 1879 CCTUInfo.reset(); 1880 1881 return Result; 1882 } 1883 1884 void ASTUnit::ResetForParse() { 1885 SavedMainFileBuffer.reset(); 1886 1887 SourceMgr.reset(); 1888 TheSema.reset(); 1889 Ctx.reset(); 1890 PP.reset(); 1891 Reader.reset(); 1892 1893 TopLevelDecls.clear(); 1894 clearFileLevelDecls(); 1895 } 1896 1897 //----------------------------------------------------------------------------// 1898 // Code completion 1899 //----------------------------------------------------------------------------// 1900 1901 namespace { 1902 1903 /// Code completion consumer that combines the cached code-completion 1904 /// results from an ASTUnit with the code-completion results provided to it, 1905 /// then passes the result on to 1906 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer { 1907 uint64_t NormalContexts; 1908 ASTUnit &AST; 1909 CodeCompleteConsumer &Next; 1910 1911 public: 1912 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next, 1913 const CodeCompleteOptions &CodeCompleteOpts) 1914 : CodeCompleteConsumer(CodeCompleteOpts), AST(AST), Next(Next) { 1915 // Compute the set of contexts in which we will look when we don't have 1916 // any information about the specific context. 1917 NormalContexts 1918 = (1LL << CodeCompletionContext::CCC_TopLevel) 1919 | (1LL << CodeCompletionContext::CCC_ObjCInterface) 1920 | (1LL << CodeCompletionContext::CCC_ObjCImplementation) 1921 | (1LL << CodeCompletionContext::CCC_ObjCIvarList) 1922 | (1LL << CodeCompletionContext::CCC_Statement) 1923 | (1LL << CodeCompletionContext::CCC_Expression) 1924 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver) 1925 | (1LL << CodeCompletionContext::CCC_DotMemberAccess) 1926 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess) 1927 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess) 1928 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName) 1929 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression) 1930 | (1LL << CodeCompletionContext::CCC_Recovery); 1931 1932 if (AST.getASTContext().getLangOpts().CPlusPlus) 1933 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag) 1934 | (1LL << CodeCompletionContext::CCC_UnionTag) 1935 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag); 1936 } 1937 1938 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context, 1939 CodeCompletionResult *Results, 1940 unsigned NumResults) override; 1941 1942 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, 1943 OverloadCandidate *Candidates, 1944 unsigned NumCandidates, 1945 SourceLocation OpenParLoc) override { 1946 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates, 1947 OpenParLoc); 1948 } 1949 1950 CodeCompletionAllocator &getAllocator() override { 1951 return Next.getAllocator(); 1952 } 1953 1954 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { 1955 return Next.getCodeCompletionTUInfo(); 1956 } 1957 }; 1958 1959 } // namespace 1960 1961 /// Helper function that computes which global names are hidden by the 1962 /// local code-completion results. 1963 static void CalculateHiddenNames(const CodeCompletionContext &Context, 1964 CodeCompletionResult *Results, 1965 unsigned NumResults, 1966 ASTContext &Ctx, 1967 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){ 1968 bool OnlyTagNames = false; 1969 switch (Context.getKind()) { 1970 case CodeCompletionContext::CCC_Recovery: 1971 case CodeCompletionContext::CCC_TopLevel: 1972 case CodeCompletionContext::CCC_ObjCInterface: 1973 case CodeCompletionContext::CCC_ObjCImplementation: 1974 case CodeCompletionContext::CCC_ObjCIvarList: 1975 case CodeCompletionContext::CCC_ClassStructUnion: 1976 case CodeCompletionContext::CCC_Statement: 1977 case CodeCompletionContext::CCC_Expression: 1978 case CodeCompletionContext::CCC_ObjCMessageReceiver: 1979 case CodeCompletionContext::CCC_DotMemberAccess: 1980 case CodeCompletionContext::CCC_ArrowMemberAccess: 1981 case CodeCompletionContext::CCC_ObjCPropertyAccess: 1982 case CodeCompletionContext::CCC_Namespace: 1983 case CodeCompletionContext::CCC_Type: 1984 case CodeCompletionContext::CCC_Symbol: 1985 case CodeCompletionContext::CCC_SymbolOrNewName: 1986 case CodeCompletionContext::CCC_ParenthesizedExpression: 1987 case CodeCompletionContext::CCC_ObjCInterfaceName: 1988 break; 1989 1990 case CodeCompletionContext::CCC_EnumTag: 1991 case CodeCompletionContext::CCC_UnionTag: 1992 case CodeCompletionContext::CCC_ClassOrStructTag: 1993 OnlyTagNames = true; 1994 break; 1995 1996 case CodeCompletionContext::CCC_ObjCProtocolName: 1997 case CodeCompletionContext::CCC_MacroName: 1998 case CodeCompletionContext::CCC_MacroNameUse: 1999 case CodeCompletionContext::CCC_PreprocessorExpression: 2000 case CodeCompletionContext::CCC_PreprocessorDirective: 2001 case CodeCompletionContext::CCC_NaturalLanguage: 2002 case CodeCompletionContext::CCC_SelectorName: 2003 case CodeCompletionContext::CCC_TypeQualifiers: 2004 case CodeCompletionContext::CCC_Other: 2005 case CodeCompletionContext::CCC_OtherWithMacros: 2006 case CodeCompletionContext::CCC_ObjCInstanceMessage: 2007 case CodeCompletionContext::CCC_ObjCClassMessage: 2008 case CodeCompletionContext::CCC_ObjCCategoryName: 2009 case CodeCompletionContext::CCC_IncludedFile: 2010 case CodeCompletionContext::CCC_NewName: 2011 // We're looking for nothing, or we're looking for names that cannot 2012 // be hidden. 2013 return; 2014 } 2015 2016 using Result = CodeCompletionResult; 2017 for (unsigned I = 0; I != NumResults; ++I) { 2018 if (Results[I].Kind != Result::RK_Declaration) 2019 continue; 2020 2021 unsigned IDNS 2022 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace(); 2023 2024 bool Hiding = false; 2025 if (OnlyTagNames) 2026 Hiding = (IDNS & Decl::IDNS_Tag); 2027 else { 2028 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member | 2029 Decl::IDNS_Namespace | Decl::IDNS_Ordinary | 2030 Decl::IDNS_NonMemberOperator); 2031 if (Ctx.getLangOpts().CPlusPlus) 2032 HiddenIDNS |= Decl::IDNS_Tag; 2033 Hiding = (IDNS & HiddenIDNS); 2034 } 2035 2036 if (!Hiding) 2037 continue; 2038 2039 DeclarationName Name = Results[I].Declaration->getDeclName(); 2040 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo()) 2041 HiddenNames.insert(Identifier->getName()); 2042 else 2043 HiddenNames.insert(Name.getAsString()); 2044 } 2045 } 2046 2047 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S, 2048 CodeCompletionContext Context, 2049 CodeCompletionResult *Results, 2050 unsigned NumResults) { 2051 // Merge the results we were given with the results we cached. 2052 bool AddedResult = false; 2053 uint64_t InContexts = 2054 Context.getKind() == CodeCompletionContext::CCC_Recovery 2055 ? NormalContexts : (1LL << Context.getKind()); 2056 // Contains the set of names that are hidden by "local" completion results. 2057 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames; 2058 using Result = CodeCompletionResult; 2059 SmallVector<Result, 8> AllResults; 2060 for (ASTUnit::cached_completion_iterator 2061 C = AST.cached_completion_begin(), 2062 CEnd = AST.cached_completion_end(); 2063 C != CEnd; ++C) { 2064 // If the context we are in matches any of the contexts we are 2065 // interested in, we'll add this result. 2066 if ((C->ShowInContexts & InContexts) == 0) 2067 continue; 2068 2069 // If we haven't added any results previously, do so now. 2070 if (!AddedResult) { 2071 CalculateHiddenNames(Context, Results, NumResults, S.Context, 2072 HiddenNames); 2073 AllResults.insert(AllResults.end(), Results, Results + NumResults); 2074 AddedResult = true; 2075 } 2076 2077 // Determine whether this global completion result is hidden by a local 2078 // completion result. If so, skip it. 2079 if (C->Kind != CXCursor_MacroDefinition && 2080 HiddenNames.count(C->Completion->getTypedText())) 2081 continue; 2082 2083 // Adjust priority based on similar type classes. 2084 unsigned Priority = C->Priority; 2085 CodeCompletionString *Completion = C->Completion; 2086 if (!Context.getPreferredType().isNull()) { 2087 if (C->Kind == CXCursor_MacroDefinition) { 2088 Priority = getMacroUsagePriority(C->Completion->getTypedText(), 2089 S.getLangOpts(), 2090 Context.getPreferredType()->isAnyPointerType()); 2091 } else if (C->Type) { 2092 CanQualType Expected 2093 = S.Context.getCanonicalType( 2094 Context.getPreferredType().getUnqualifiedType()); 2095 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected); 2096 if (ExpectedSTC == C->TypeClass) { 2097 // We know this type is similar; check for an exact match. 2098 llvm::StringMap<unsigned> &CachedCompletionTypes 2099 = AST.getCachedCompletionTypes(); 2100 llvm::StringMap<unsigned>::iterator Pos 2101 = CachedCompletionTypes.find(QualType(Expected).getAsString()); 2102 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type) 2103 Priority /= CCF_ExactTypeMatch; 2104 else 2105 Priority /= CCF_SimilarTypeMatch; 2106 } 2107 } 2108 } 2109 2110 // Adjust the completion string, if required. 2111 if (C->Kind == CXCursor_MacroDefinition && 2112 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) { 2113 // Create a new code-completion string that just contains the 2114 // macro name, without its arguments. 2115 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(), 2116 CCP_CodePattern, C->Availability); 2117 Builder.AddTypedTextChunk(C->Completion->getTypedText()); 2118 Priority = CCP_CodePattern; 2119 Completion = Builder.TakeString(); 2120 } 2121 2122 AllResults.push_back(Result(Completion, Priority, C->Kind, 2123 C->Availability)); 2124 } 2125 2126 // If we did not add any cached completion results, just forward the 2127 // results we were given to the next consumer. 2128 if (!AddedResult) { 2129 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults); 2130 return; 2131 } 2132 2133 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(), 2134 AllResults.size()); 2135 } 2136 2137 void ASTUnit::CodeComplete( 2138 StringRef File, unsigned Line, unsigned Column, 2139 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros, 2140 bool IncludeCodePatterns, bool IncludeBriefComments, 2141 CodeCompleteConsumer &Consumer, 2142 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 2143 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr, 2144 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics, 2145 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) { 2146 if (!Invocation) 2147 return; 2148 2149 SimpleTimer CompletionTimer(WantTiming); 2150 CompletionTimer.setOutput("Code completion @ " + File + ":" + 2151 Twine(Line) + ":" + Twine(Column)); 2152 2153 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation); 2154 2155 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts(); 2156 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts; 2157 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts(); 2158 2159 CodeCompleteOpts.IncludeMacros = IncludeMacros && 2160 CachedCompletionResults.empty(); 2161 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns; 2162 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty(); 2163 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments; 2164 CodeCompleteOpts.LoadExternal = Consumer.loadExternal(); 2165 CodeCompleteOpts.IncludeFixIts = Consumer.includeFixIts(); 2166 2167 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion); 2168 2169 FrontendOpts.CodeCompletionAt.FileName = std::string(File); 2170 FrontendOpts.CodeCompletionAt.Line = Line; 2171 FrontendOpts.CodeCompletionAt.Column = Column; 2172 2173 // Set the language options appropriately. 2174 LangOpts = *CCInvocation->getLangOpts(); 2175 2176 // Spell-checking and warnings are wasteful during code-completion. 2177 LangOpts.SpellChecking = false; 2178 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true; 2179 2180 std::unique_ptr<CompilerInstance> Clang( 2181 new CompilerInstance(PCHContainerOps)); 2182 2183 // Recover resources if we crash before exiting this method. 2184 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> 2185 CICleanup(Clang.get()); 2186 2187 auto &Inv = *CCInvocation; 2188 Clang->setInvocation(std::move(CCInvocation)); 2189 OriginalSourceFile = 2190 std::string(Clang->getFrontendOpts().Inputs[0].getFile()); 2191 2192 // Set up diagnostics, capturing any diagnostics produced. 2193 Clang->setDiagnostics(&Diag); 2194 CaptureDroppedDiagnostics Capture(CaptureDiagsKind::All, 2195 Clang->getDiagnostics(), 2196 &StoredDiagnostics, nullptr); 2197 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts()); 2198 2199 // Create the target instance. 2200 Clang->setTarget(TargetInfo::CreateTargetInfo( 2201 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts)); 2202 if (!Clang->hasTarget()) { 2203 Clang->setInvocation(nullptr); 2204 return; 2205 } 2206 2207 // Inform the target of the language options. 2208 // 2209 // FIXME: We shouldn't need to do this, the target should be immutable once 2210 // created. This complexity should be lifted elsewhere. 2211 Clang->getTarget().adjust(Clang->getLangOpts()); 2212 2213 assert(Clang->getFrontendOpts().Inputs.size() == 1 && 2214 "Invocation must have exactly one source file!"); 2215 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() == 2216 InputKind::Source && 2217 "FIXME: AST inputs not yet supported here!"); 2218 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() != 2219 Language::LLVM_IR && 2220 "IR inputs not support here!"); 2221 2222 // Use the source and file managers that we were given. 2223 Clang->setFileManager(&FileMgr); 2224 Clang->setSourceManager(&SourceMgr); 2225 2226 // Remap files. 2227 PreprocessorOpts.clearRemappedFiles(); 2228 PreprocessorOpts.RetainRemappedFileBuffers = true; 2229 for (const auto &RemappedFile : RemappedFiles) { 2230 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second); 2231 OwnedBuffers.push_back(RemappedFile.second); 2232 } 2233 2234 // Use the code completion consumer we were given, but adding any cached 2235 // code-completion results. 2236 AugmentedCodeCompleteConsumer *AugmentedConsumer 2237 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts); 2238 Clang->setCodeCompletionConsumer(AugmentedConsumer); 2239 2240 // If we have a precompiled preamble, try to use it. We only allow 2241 // the use of the precompiled preamble if we're if the completion 2242 // point is within the main file, after the end of the precompiled 2243 // preamble. 2244 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer; 2245 if (Preamble) { 2246 std::string CompleteFilePath(File); 2247 2248 auto &VFS = FileMgr.getVirtualFileSystem(); 2249 auto CompleteFileStatus = VFS.status(CompleteFilePath); 2250 if (CompleteFileStatus) { 2251 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID(); 2252 2253 std::string MainPath(OriginalSourceFile); 2254 auto MainStatus = VFS.status(MainPath); 2255 if (MainStatus) { 2256 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID(); 2257 if (CompleteFileID == MainID && Line > 1) 2258 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble( 2259 PCHContainerOps, Inv, &VFS, false, Line - 1); 2260 } 2261 } 2262 } 2263 2264 // If the main file has been overridden due to the use of a preamble, 2265 // make that override happen and introduce the preamble. 2266 if (OverrideMainBuffer) { 2267 assert(Preamble && 2268 "No preamble was built, but OverrideMainBuffer is not null"); 2269 2270 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = 2271 &FileMgr.getVirtualFileSystem(); 2272 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS, 2273 OverrideMainBuffer.get()); 2274 // FIXME: there is no way to update VFS if it was changed by 2275 // AddImplicitPreamble as FileMgr is accepted as a parameter by this method. 2276 // We use on-disk preambles instead and rely on FileMgr's VFS to ensure the 2277 // PCH files are always readable. 2278 OwnedBuffers.push_back(OverrideMainBuffer.release()); 2279 } else { 2280 PreprocessorOpts.PrecompiledPreambleBytes.first = 0; 2281 PreprocessorOpts.PrecompiledPreambleBytes.second = false; 2282 } 2283 2284 // Disable the preprocessing record if modules are not enabled. 2285 if (!Clang->getLangOpts().Modules) 2286 PreprocessorOpts.DetailedRecord = false; 2287 2288 std::unique_ptr<SyntaxOnlyAction> Act; 2289 Act.reset(new SyntaxOnlyAction); 2290 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) { 2291 if (llvm::Error Err = Act->Execute()) { 2292 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 2293 } 2294 Act->EndSourceFile(); 2295 } 2296 } 2297 2298 bool ASTUnit::Save(StringRef File) { 2299 if (HadModuleLoaderFatalFailure) 2300 return true; 2301 2302 // Write to a temporary file and later rename it to the actual file, to avoid 2303 // possible race conditions. 2304 SmallString<128> TempPath; 2305 TempPath = File; 2306 TempPath += "-%%%%%%%%"; 2307 // FIXME: Can we somehow regenerate the stat cache here, or do we need to 2308 // unconditionally create a stat cache when we parse the file? 2309 2310 if (llvm::Error Err = llvm::writeFileAtomically( 2311 TempPath, File, [this](llvm::raw_ostream &Out) { 2312 return serialize(Out) ? llvm::make_error<llvm::StringError>( 2313 "ASTUnit serialization failed", 2314 llvm::inconvertibleErrorCode()) 2315 : llvm::Error::success(); 2316 })) { 2317 consumeError(std::move(Err)); 2318 return true; 2319 } 2320 return false; 2321 } 2322 2323 static bool serializeUnit(ASTWriter &Writer, 2324 SmallVectorImpl<char> &Buffer, 2325 Sema &S, 2326 bool hasErrors, 2327 raw_ostream &OS) { 2328 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors); 2329 2330 // Write the generated bitstream to "Out". 2331 if (!Buffer.empty()) 2332 OS.write(Buffer.data(), Buffer.size()); 2333 2334 return false; 2335 } 2336 2337 bool ASTUnit::serialize(raw_ostream &OS) { 2338 // For serialization we are lenient if the errors were only warn-as-error kind. 2339 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred(); 2340 2341 if (WriterData) 2342 return serializeUnit(WriterData->Writer, WriterData->Buffer, 2343 getSema(), hasErrors, OS); 2344 2345 SmallString<128> Buffer; 2346 llvm::BitstreamWriter Stream(Buffer); 2347 InMemoryModuleCache ModuleCache; 2348 ASTWriter Writer(Stream, Buffer, ModuleCache, {}); 2349 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS); 2350 } 2351 2352 using SLocRemap = ContinuousRangeMap<unsigned, int, 2>; 2353 2354 void ASTUnit::TranslateStoredDiagnostics( 2355 FileManager &FileMgr, 2356 SourceManager &SrcMgr, 2357 const SmallVectorImpl<StandaloneDiagnostic> &Diags, 2358 SmallVectorImpl<StoredDiagnostic> &Out) { 2359 // Map the standalone diagnostic into the new source manager. We also need to 2360 // remap all the locations to the new view. This includes the diag location, 2361 // any associated source ranges, and the source ranges of associated fix-its. 2362 // FIXME: There should be a cleaner way to do this. 2363 SmallVector<StoredDiagnostic, 4> Result; 2364 Result.reserve(Diags.size()); 2365 2366 for (const auto &SD : Diags) { 2367 // Rebuild the StoredDiagnostic. 2368 if (SD.Filename.empty()) 2369 continue; 2370 auto FE = FileMgr.getFile(SD.Filename); 2371 if (!FE) 2372 continue; 2373 SourceLocation FileLoc; 2374 auto ItFileID = PreambleSrcLocCache.find(SD.Filename); 2375 if (ItFileID == PreambleSrcLocCache.end()) { 2376 FileID FID = SrcMgr.translateFile(*FE); 2377 FileLoc = SrcMgr.getLocForStartOfFile(FID); 2378 PreambleSrcLocCache[SD.Filename] = FileLoc; 2379 } else { 2380 FileLoc = ItFileID->getValue(); 2381 } 2382 2383 if (FileLoc.isInvalid()) 2384 continue; 2385 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset); 2386 FullSourceLoc Loc(L, SrcMgr); 2387 2388 SmallVector<CharSourceRange, 4> Ranges; 2389 Ranges.reserve(SD.Ranges.size()); 2390 for (const auto &Range : SD.Ranges) { 2391 SourceLocation BL = FileLoc.getLocWithOffset(Range.first); 2392 SourceLocation EL = FileLoc.getLocWithOffset(Range.second); 2393 Ranges.push_back(CharSourceRange::getCharRange(BL, EL)); 2394 } 2395 2396 SmallVector<FixItHint, 2> FixIts; 2397 FixIts.reserve(SD.FixIts.size()); 2398 for (const auto &FixIt : SD.FixIts) { 2399 FixIts.push_back(FixItHint()); 2400 FixItHint &FH = FixIts.back(); 2401 FH.CodeToInsert = FixIt.CodeToInsert; 2402 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first); 2403 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second); 2404 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL); 2405 } 2406 2407 Result.push_back(StoredDiagnostic(SD.Level, SD.ID, 2408 SD.Message, Loc, Ranges, FixIts)); 2409 } 2410 Result.swap(Out); 2411 } 2412 2413 void ASTUnit::addFileLevelDecl(Decl *D) { 2414 assert(D); 2415 2416 // We only care about local declarations. 2417 if (D->isFromASTFile()) 2418 return; 2419 2420 SourceManager &SM = *SourceMgr; 2421 SourceLocation Loc = D->getLocation(); 2422 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc)) 2423 return; 2424 2425 // We only keep track of the file-level declarations of each file. 2426 if (!D->getLexicalDeclContext()->isFileContext()) 2427 return; 2428 2429 SourceLocation FileLoc = SM.getFileLoc(Loc); 2430 assert(SM.isLocalSourceLocation(FileLoc)); 2431 FileID FID; 2432 unsigned Offset; 2433 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc); 2434 if (FID.isInvalid()) 2435 return; 2436 2437 std::unique_ptr<LocDeclsTy> &Decls = FileDecls[FID]; 2438 if (!Decls) 2439 Decls = std::make_unique<LocDeclsTy>(); 2440 2441 std::pair<unsigned, Decl *> LocDecl(Offset, D); 2442 2443 if (Decls->empty() || Decls->back().first <= Offset) { 2444 Decls->push_back(LocDecl); 2445 return; 2446 } 2447 2448 LocDeclsTy::iterator I = 2449 llvm::upper_bound(*Decls, LocDecl, llvm::less_first()); 2450 2451 Decls->insert(I, LocDecl); 2452 } 2453 2454 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length, 2455 SmallVectorImpl<Decl *> &Decls) { 2456 if (File.isInvalid()) 2457 return; 2458 2459 if (SourceMgr->isLoadedFileID(File)) { 2460 assert(Ctx->getExternalSource() && "No external source!"); 2461 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length, 2462 Decls); 2463 } 2464 2465 FileDeclsTy::iterator I = FileDecls.find(File); 2466 if (I == FileDecls.end()) 2467 return; 2468 2469 LocDeclsTy &LocDecls = *I->second; 2470 if (LocDecls.empty()) 2471 return; 2472 2473 LocDeclsTy::iterator BeginIt = 2474 llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) { 2475 return LD.first < Offset; 2476 }); 2477 if (BeginIt != LocDecls.begin()) 2478 --BeginIt; 2479 2480 // If we are pointing at a top-level decl inside an objc container, we need 2481 // to backtrack until we find it otherwise we will fail to report that the 2482 // region overlaps with an objc container. 2483 while (BeginIt != LocDecls.begin() && 2484 BeginIt->second->isTopLevelDeclInObjCContainer()) 2485 --BeginIt; 2486 2487 LocDeclsTy::iterator EndIt = llvm::upper_bound( 2488 LocDecls, std::make_pair(Offset + Length, (Decl *)nullptr), 2489 llvm::less_first()); 2490 if (EndIt != LocDecls.end()) 2491 ++EndIt; 2492 2493 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt) 2494 Decls.push_back(DIt->second); 2495 } 2496 2497 SourceLocation ASTUnit::getLocation(const FileEntry *File, 2498 unsigned Line, unsigned Col) const { 2499 const SourceManager &SM = getSourceManager(); 2500 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col); 2501 return SM.getMacroArgExpandedLocation(Loc); 2502 } 2503 2504 SourceLocation ASTUnit::getLocation(const FileEntry *File, 2505 unsigned Offset) const { 2506 const SourceManager &SM = getSourceManager(); 2507 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1); 2508 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset)); 2509 } 2510 2511 /// If \arg Loc is a loaded location from the preamble, returns 2512 /// the corresponding local location of the main file, otherwise it returns 2513 /// \arg Loc. 2514 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const { 2515 FileID PreambleID; 2516 if (SourceMgr) 2517 PreambleID = SourceMgr->getPreambleFileID(); 2518 2519 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid()) 2520 return Loc; 2521 2522 unsigned Offs; 2523 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) { 2524 SourceLocation FileLoc 2525 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID()); 2526 return FileLoc.getLocWithOffset(Offs); 2527 } 2528 2529 return Loc; 2530 } 2531 2532 /// If \arg Loc is a local location of the main file but inside the 2533 /// preamble chunk, returns the corresponding loaded location from the 2534 /// preamble, otherwise it returns \arg Loc. 2535 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const { 2536 FileID PreambleID; 2537 if (SourceMgr) 2538 PreambleID = SourceMgr->getPreambleFileID(); 2539 2540 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid()) 2541 return Loc; 2542 2543 unsigned Offs; 2544 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) && 2545 Offs < Preamble->getBounds().Size) { 2546 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID); 2547 return FileLoc.getLocWithOffset(Offs); 2548 } 2549 2550 return Loc; 2551 } 2552 2553 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const { 2554 FileID FID; 2555 if (SourceMgr) 2556 FID = SourceMgr->getPreambleFileID(); 2557 2558 if (Loc.isInvalid() || FID.isInvalid()) 2559 return false; 2560 2561 return SourceMgr->isInFileID(Loc, FID); 2562 } 2563 2564 bool ASTUnit::isInMainFileID(SourceLocation Loc) const { 2565 FileID FID; 2566 if (SourceMgr) 2567 FID = SourceMgr->getMainFileID(); 2568 2569 if (Loc.isInvalid() || FID.isInvalid()) 2570 return false; 2571 2572 return SourceMgr->isInFileID(Loc, FID); 2573 } 2574 2575 SourceLocation ASTUnit::getEndOfPreambleFileID() const { 2576 FileID FID; 2577 if (SourceMgr) 2578 FID = SourceMgr->getPreambleFileID(); 2579 2580 if (FID.isInvalid()) 2581 return {}; 2582 2583 return SourceMgr->getLocForEndOfFile(FID); 2584 } 2585 2586 SourceLocation ASTUnit::getStartOfMainFileID() const { 2587 FileID FID; 2588 if (SourceMgr) 2589 FID = SourceMgr->getMainFileID(); 2590 2591 if (FID.isInvalid()) 2592 return {}; 2593 2594 return SourceMgr->getLocForStartOfFile(FID); 2595 } 2596 2597 llvm::iterator_range<PreprocessingRecord::iterator> 2598 ASTUnit::getLocalPreprocessingEntities() const { 2599 if (isMainFileAST()) { 2600 serialization::ModuleFile & 2601 Mod = Reader->getModuleManager().getPrimaryModule(); 2602 return Reader->getModulePreprocessedEntities(Mod); 2603 } 2604 2605 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord()) 2606 return llvm::make_range(PPRec->local_begin(), PPRec->local_end()); 2607 2608 return llvm::make_range(PreprocessingRecord::iterator(), 2609 PreprocessingRecord::iterator()); 2610 } 2611 2612 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) { 2613 if (isMainFileAST()) { 2614 serialization::ModuleFile & 2615 Mod = Reader->getModuleManager().getPrimaryModule(); 2616 for (const auto *D : Reader->getModuleFileLevelDecls(Mod)) { 2617 if (!Fn(context, D)) 2618 return false; 2619 } 2620 2621 return true; 2622 } 2623 2624 for (ASTUnit::top_level_iterator TL = top_level_begin(), 2625 TLEnd = top_level_end(); 2626 TL != TLEnd; ++TL) { 2627 if (!Fn(context, *TL)) 2628 return false; 2629 } 2630 2631 return true; 2632 } 2633 2634 const FileEntry *ASTUnit::getPCHFile() { 2635 if (!Reader) 2636 return nullptr; 2637 2638 serialization::ModuleFile *Mod = nullptr; 2639 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) { 2640 switch (M.Kind) { 2641 case serialization::MK_ImplicitModule: 2642 case serialization::MK_ExplicitModule: 2643 case serialization::MK_PrebuiltModule: 2644 return true; // skip dependencies. 2645 case serialization::MK_PCH: 2646 Mod = &M; 2647 return true; // found it. 2648 case serialization::MK_Preamble: 2649 return false; // look in dependencies. 2650 case serialization::MK_MainFile: 2651 return false; // look in dependencies. 2652 } 2653 2654 return true; 2655 }); 2656 if (Mod) 2657 return Mod->File; 2658 2659 return nullptr; 2660 } 2661 2662 bool ASTUnit::isModuleFile() const { 2663 return isMainFileAST() && getLangOpts().isCompilingModule(); 2664 } 2665 2666 InputKind ASTUnit::getInputKind() const { 2667 auto &LangOpts = getLangOpts(); 2668 2669 Language Lang; 2670 if (LangOpts.OpenCL) 2671 Lang = Language::OpenCL; 2672 else if (LangOpts.CUDA) 2673 Lang = Language::CUDA; 2674 else if (LangOpts.RenderScript) 2675 Lang = Language::RenderScript; 2676 else if (LangOpts.CPlusPlus) 2677 Lang = LangOpts.ObjC ? Language::ObjCXX : Language::CXX; 2678 else 2679 Lang = LangOpts.ObjC ? Language::ObjC : Language::C; 2680 2681 InputKind::Format Fmt = InputKind::Source; 2682 if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap) 2683 Fmt = InputKind::ModuleMap; 2684 2685 // We don't know if input was preprocessed. Assume not. 2686 bool PP = false; 2687 2688 return InputKind(Lang, Fmt, PP); 2689 } 2690 2691 #ifndef NDEBUG 2692 ASTUnit::ConcurrencyState::ConcurrencyState() { 2693 Mutex = new std::recursive_mutex; 2694 } 2695 2696 ASTUnit::ConcurrencyState::~ConcurrencyState() { 2697 delete static_cast<std::recursive_mutex *>(Mutex); 2698 } 2699 2700 void ASTUnit::ConcurrencyState::start() { 2701 bool acquired = static_cast<std::recursive_mutex *>(Mutex)->try_lock(); 2702 assert(acquired && "Concurrent access to ASTUnit!"); 2703 } 2704 2705 void ASTUnit::ConcurrencyState::finish() { 2706 static_cast<std::recursive_mutex *>(Mutex)->unlock(); 2707 } 2708 2709 #else // NDEBUG 2710 2711 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; } 2712 ASTUnit::ConcurrencyState::~ConcurrencyState() {} 2713 void ASTUnit::ConcurrencyState::start() {} 2714 void ASTUnit::ConcurrencyState::finish() {} 2715 2716 #endif // NDEBUG 2717