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