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