1 //===--- ParsedAST.cpp -------------------------------------------*- C++-*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "ParsedAST.h" 10 #include "../clang-tidy/ClangTidyCheck.h" 11 #include "../clang-tidy/ClangTidyDiagnosticConsumer.h" 12 #include "../clang-tidy/ClangTidyModuleRegistry.h" 13 #include "AST.h" 14 #include "Compiler.h" 15 #include "Config.h" 16 #include "Diagnostics.h" 17 #include "Feature.h" 18 #include "FeatureModule.h" 19 #include "Headers.h" 20 #include "HeuristicResolver.h" 21 #include "IncludeCleaner.h" 22 #include "IncludeFixer.h" 23 #include "Preamble.h" 24 #include "SourceCode.h" 25 #include "TidyProvider.h" 26 #include "index/CanonicalIncludes.h" 27 #include "index/Index.h" 28 #include "support/Logger.h" 29 #include "support/Trace.h" 30 #include "clang/AST/ASTContext.h" 31 #include "clang/AST/Decl.h" 32 #include "clang/Basic/Diagnostic.h" 33 #include "clang/Basic/DiagnosticSema.h" 34 #include "clang/Basic/LangOptions.h" 35 #include "clang/Basic/SourceLocation.h" 36 #include "clang/Basic/SourceManager.h" 37 #include "clang/Basic/TokenKinds.h" 38 #include "clang/Frontend/CompilerInstance.h" 39 #include "clang/Frontend/CompilerInvocation.h" 40 #include "clang/Frontend/FrontendActions.h" 41 #include "clang/Lex/Lexer.h" 42 #include "clang/Lex/PPCallbacks.h" 43 #include "clang/Lex/Preprocessor.h" 44 #include "clang/Serialization/ASTWriter.h" 45 #include "clang/Tooling/CompilationDatabase.h" 46 #include "clang/Tooling/Syntax/Tokens.h" 47 #include "llvm/ADT/ArrayRef.h" 48 #include "llvm/ADT/STLExtras.h" 49 #include "llvm/ADT/SmallVector.h" 50 #include "llvm/ADT/StringRef.h" 51 #include <algorithm> 52 #include <memory> 53 #include <vector> 54 55 // Force the linker to link in Clang-tidy modules. 56 // clangd doesn't support the static analyzer. 57 #if CLANGD_TIDY_CHECKS 58 #define CLANG_TIDY_DISABLE_STATIC_ANALYZER_CHECKS 59 #include "../clang-tidy/ClangTidyForceLinker.h" 60 #endif 61 62 namespace clang { 63 namespace clangd { 64 namespace { 65 66 template <class T> std::size_t getUsedBytes(const std::vector<T> &Vec) { 67 return Vec.capacity() * sizeof(T); 68 } 69 70 class DeclTrackingASTConsumer : public ASTConsumer { 71 public: 72 DeclTrackingASTConsumer(std::vector<Decl *> &TopLevelDecls) 73 : TopLevelDecls(TopLevelDecls) {} 74 75 bool HandleTopLevelDecl(DeclGroupRef DG) override { 76 for (Decl *D : DG) { 77 auto &SM = D->getASTContext().getSourceManager(); 78 if (!isInsideMainFile(D->getLocation(), SM)) 79 continue; 80 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 81 if (isImplicitTemplateInstantiation(ND)) 82 continue; 83 84 // ObjCMethodDecl are not actually top-level decls. 85 if (isa<ObjCMethodDecl>(D)) 86 continue; 87 88 TopLevelDecls.push_back(D); 89 } 90 return true; 91 } 92 93 private: 94 std::vector<Decl *> &TopLevelDecls; 95 }; 96 97 class ClangdFrontendAction : public SyntaxOnlyAction { 98 public: 99 std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); } 100 101 protected: 102 std::unique_ptr<ASTConsumer> 103 CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) override { 104 return std::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls); 105 } 106 107 private: 108 std::vector<Decl *> TopLevelDecls; 109 }; 110 111 // When using a preamble, only preprocessor events outside its bounds are seen. 112 // This is almost what we want: replaying transitive preprocessing wastes time. 113 // However this confuses clang-tidy checks: they don't see any #includes! 114 // So we replay the *non-transitive* #includes that appear in the main-file. 115 // It would be nice to replay other events (macro definitions, ifdefs etc) but 116 // this addresses the most common cases fairly cheaply. 117 class ReplayPreamble : private PPCallbacks { 118 public: 119 // Attach preprocessor hooks such that preamble events will be injected at 120 // the appropriate time. 121 // Events will be delivered to the *currently registered* PP callbacks. 122 static void attach(std::vector<Inclusion> Includes, CompilerInstance &Clang, 123 const PreambleBounds &PB) { 124 auto &PP = Clang.getPreprocessor(); 125 auto *ExistingCallbacks = PP.getPPCallbacks(); 126 // No need to replay events if nobody is listening. 127 if (!ExistingCallbacks) 128 return; 129 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(new ReplayPreamble( 130 std::move(Includes), ExistingCallbacks, Clang.getSourceManager(), PP, 131 Clang.getLangOpts(), PB))); 132 // We're relying on the fact that addPPCallbacks keeps the old PPCallbacks 133 // around, creating a chaining wrapper. Guard against other implementations. 134 assert(PP.getPPCallbacks() != ExistingCallbacks && 135 "Expected chaining implementation"); 136 } 137 138 private: 139 ReplayPreamble(std::vector<Inclusion> Includes, PPCallbacks *Delegate, 140 const SourceManager &SM, Preprocessor &PP, 141 const LangOptions &LangOpts, const PreambleBounds &PB) 142 : Includes(std::move(Includes)), Delegate(Delegate), SM(SM), PP(PP) { 143 // Only tokenize the preamble section of the main file, as we are not 144 // interested in the rest of the tokens. 145 MainFileTokens = syntax::tokenize( 146 syntax::FileRange(SM.getMainFileID(), 0, PB.Size), SM, LangOpts); 147 } 148 149 // In a normal compile, the preamble traverses the following structure: 150 // 151 // mainfile.cpp 152 // <built-in> 153 // ... macro definitions like __cplusplus ... 154 // <command-line> 155 // ... macro definitions for args like -Dfoo=bar ... 156 // "header1.h" 157 // ... header file contents ... 158 // "header2.h" 159 // ... header file contents ... 160 // ... main file contents ... 161 // 162 // When using a preamble, the "header1" and "header2" subtrees get skipped. 163 // We insert them right after the built-in header, which still appears. 164 void FileChanged(SourceLocation Loc, FileChangeReason Reason, 165 SrcMgr::CharacteristicKind Kind, FileID PrevFID) override { 166 // It'd be nice if there was a better way to identify built-in headers... 167 if (Reason == FileChangeReason::ExitFile && 168 SM.getBufferOrFake(PrevFID).getBufferIdentifier() == "<built-in>") 169 replay(); 170 } 171 172 void replay() { 173 for (const auto &Inc : Includes) { 174 llvm::Optional<FileEntryRef> File; 175 if (Inc.Resolved != "") 176 File = expectedToOptional(SM.getFileManager().getFileRef(Inc.Resolved)); 177 178 // Re-lex the #include directive to find its interesting parts. 179 auto HashLoc = SM.getComposedLoc(SM.getMainFileID(), Inc.HashOffset); 180 auto HashTok = llvm::partition_point(MainFileTokens, 181 [&HashLoc](const syntax::Token &T) { 182 return T.location() < HashLoc; 183 }); 184 assert(HashTok != MainFileTokens.end() && HashTok->kind() == tok::hash); 185 186 auto IncludeTok = std::next(HashTok); 187 assert(IncludeTok != MainFileTokens.end()); 188 189 auto FileTok = std::next(IncludeTok); 190 assert(FileTok != MainFileTokens.end()); 191 192 // Create a fake import/include token, none of the callers seem to care 193 // about clang::Token::Flags. 194 Token SynthesizedIncludeTok; 195 SynthesizedIncludeTok.startToken(); 196 SynthesizedIncludeTok.setLocation(IncludeTok->location()); 197 SynthesizedIncludeTok.setLength(IncludeTok->length()); 198 SynthesizedIncludeTok.setKind(tok::raw_identifier); 199 SynthesizedIncludeTok.setRawIdentifierData(IncludeTok->text(SM).data()); 200 PP.LookUpIdentifierInfo(SynthesizedIncludeTok); 201 202 // Same here, create a fake one for Filename, including angles or quotes. 203 Token SynthesizedFilenameTok; 204 SynthesizedFilenameTok.startToken(); 205 SynthesizedFilenameTok.setLocation(FileTok->location()); 206 // Note that we can't make use of FileTok->length/text in here as in the 207 // case of angled includes this will contain tok::less instead of 208 // filename. Whereas Inc.Written contains the full header name including 209 // quotes/angles. 210 SynthesizedFilenameTok.setLength(Inc.Written.length()); 211 SynthesizedFilenameTok.setKind(tok::header_name); 212 SynthesizedFilenameTok.setLiteralData(Inc.Written.data()); 213 214 llvm::StringRef WrittenFilename = 215 llvm::StringRef(Inc.Written).drop_front().drop_back(); 216 Delegate->InclusionDirective( 217 HashTok->location(), SynthesizedIncludeTok, WrittenFilename, 218 Inc.Written.front() == '<', 219 syntax::FileRange(SM, SynthesizedFilenameTok.getLocation(), 220 SynthesizedFilenameTok.getEndLoc()) 221 .toCharRange(SM), 222 File, "SearchPath", "RelPath", 223 /*Imported=*/nullptr, Inc.FileKind); 224 if (File) 225 Delegate->FileSkipped(*File, SynthesizedFilenameTok, Inc.FileKind); 226 } 227 } 228 229 const std::vector<Inclusion> Includes; 230 PPCallbacks *Delegate; 231 const SourceManager &SM; 232 Preprocessor &PP; 233 std::vector<syntax::Token> MainFileTokens; 234 }; 235 236 // Find -W<group> and -Wno-<group> options in ExtraArgs and apply them to Diags. 237 // 238 // This is used to handle ExtraArgs in clang-tidy configuration. 239 // We don't use clang's standard handling of this as we want slightly different 240 // behavior (e.g. we want to exclude these from -Wno-error). 241 void applyWarningOptions(llvm::ArrayRef<std::string> ExtraArgs, 242 DiagnosticsEngine &Diags) { 243 for (llvm::StringRef Group : ExtraArgs) { 244 // Only handle args that are of the form -W[no-]<group>. 245 // Other flags are possible but rare and deliberately out of scope. 246 llvm::SmallVector<diag::kind> Members; 247 if (!Group.consume_front("-W") || Group.empty()) 248 continue; 249 bool Enable = !Group.consume_front("no-"); 250 if (Diags.getDiagnosticIDs()->getDiagnosticsInGroup( 251 diag::Flavor::WarningOrError, Group, Members)) 252 continue; 253 254 // Upgrade (or downgrade) the severity of each diagnostic in the group. 255 // If -Werror is on, newly added warnings will be treated as errors. 256 // We don't want this, so keep track of them to fix afterwards. 257 bool NeedsWerrorExclusion = false; 258 for (diag::kind ID : Members) { 259 if (Enable) { 260 if (Diags.getDiagnosticLevel(ID, SourceLocation()) < 261 DiagnosticsEngine::Warning) { 262 Diags.setSeverity(ID, diag::Severity::Warning, SourceLocation()); 263 if (Diags.getWarningsAsErrors()) 264 NeedsWerrorExclusion = true; 265 } 266 } else { 267 Diags.setSeverity(ID, diag::Severity::Ignored, SourceLocation()); 268 } 269 } 270 if (NeedsWerrorExclusion) { 271 // FIXME: there's no API to suppress -Werror for single diagnostics. 272 // In some cases with sub-groups, we may end up erroneously 273 // downgrading diagnostics that were -Werror in the compile command. 274 Diags.setDiagnosticGroupWarningAsError(Group, false); 275 } 276 } 277 } 278 279 } // namespace 280 281 llvm::Optional<ParsedAST> 282 ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs, 283 std::unique_ptr<clang::CompilerInvocation> CI, 284 llvm::ArrayRef<Diag> CompilerInvocationDiags, 285 std::shared_ptr<const PreambleData> Preamble) { 286 trace::Span Tracer("BuildAST"); 287 SPAN_ATTACH(Tracer, "File", Filename); 288 289 auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory); 290 if (Preamble && Preamble->StatCache) 291 VFS = Preamble->StatCache->getConsumingFS(std::move(VFS)); 292 293 assert(CI); 294 // Command-line parsing sets DisableFree to true by default, but we don't want 295 // to leak memory in clangd. 296 CI->getFrontendOpts().DisableFree = false; 297 const PrecompiledPreamble *PreamblePCH = 298 Preamble ? &Preamble->Preamble : nullptr; 299 300 // This is on-by-default in windows to allow parsing SDK headers, but it 301 // breaks many features. Disable it for the main-file (not preamble). 302 CI->getLangOpts()->DelayedTemplateParsing = false; 303 304 std::vector<std::unique_ptr<FeatureModule::ASTListener>> ASTListeners; 305 if (Inputs.FeatureModules) { 306 for (auto &M : *Inputs.FeatureModules) { 307 if (auto Listener = M.astListeners()) 308 ASTListeners.emplace_back(std::move(Listener)); 309 } 310 } 311 StoreDiags ASTDiags; 312 ASTDiags.setDiagCallback( 313 [&ASTListeners](const clang::Diagnostic &D, clangd::Diag &Diag) { 314 llvm::for_each(ASTListeners, 315 [&](const auto &L) { L->sawDiagnostic(D, Diag); }); 316 }); 317 318 llvm::Optional<PreamblePatch> Patch; 319 bool PreserveDiags = true; 320 // We might use an ignoring diagnostic consumer if they are going to be 321 // dropped later on to not pay for extra latency by processing them. 322 DiagnosticConsumer *DiagConsumer = &ASTDiags; 323 IgnoreDiagnostics DropDiags; 324 if (Preamble) { 325 Patch = PreamblePatch::createFullPatch(Filename, Inputs, *Preamble); 326 Patch->apply(*CI); 327 PreserveDiags = Patch->preserveDiagnostics(); 328 if (!PreserveDiags) 329 DiagConsumer = &DropDiags; 330 } 331 auto Clang = prepareCompilerInstance( 332 std::move(CI), PreamblePCH, 333 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, Filename), VFS, 334 *DiagConsumer); 335 if (!Clang) { 336 // The last diagnostic contains information about the reason of this 337 // failure. 338 std::vector<Diag> Diags(ASTDiags.take()); 339 elog("Failed to prepare a compiler instance: {0}", 340 !Diags.empty() ? static_cast<DiagBase &>(Diags.back()).Message 341 : "unknown error"); 342 return None; 343 } 344 tidy::ClangTidyOptions ClangTidyOpts; 345 if (PreserveDiags) { 346 trace::Span Tracer("ClangTidyOpts"); 347 ClangTidyOpts = getTidyOptionsForFile(Inputs.ClangTidyProvider, Filename); 348 dlog("ClangTidy configuration for file {0}: {1}", Filename, 349 tidy::configurationAsText(ClangTidyOpts)); 350 351 // If clang-tidy is configured to emit clang warnings, we should too. 352 // 353 // Such clang-tidy configuration consists of two parts: 354 // - ExtraArgs: ["-Wfoo"] causes clang to produce the warnings 355 // - Checks: "clang-diagnostic-foo" prevents clang-tidy filtering them out 356 // 357 // We treat these as clang warnings, so the Checks part is not relevant. 358 // We must enable the warnings specified in ExtraArgs. 359 // 360 // We *don't* want to change the compile command directly. this can have 361 // too many unexpected effects: breaking the command, interactions with 362 // -- and -Werror, etc. Besides, we've already parsed the command. 363 // Instead we parse the -W<group> flags and handle them directly. 364 auto &Diags = Clang->getDiagnostics(); 365 if (ClangTidyOpts.ExtraArgsBefore) 366 applyWarningOptions(*ClangTidyOpts.ExtraArgsBefore, Diags); 367 if (ClangTidyOpts.ExtraArgs) 368 applyWarningOptions(*ClangTidyOpts.ExtraArgs, Diags); 369 } else { 370 // Skips some analysis. 371 Clang->getDiagnosticOpts().IgnoreWarnings = true; 372 } 373 374 auto Action = std::make_unique<ClangdFrontendAction>(); 375 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0]; 376 if (!Action->BeginSourceFile(*Clang, MainInput)) { 377 log("BeginSourceFile() failed when building AST for {0}", 378 MainInput.getFile()); 379 return None; 380 } 381 // If we saw an include guard in the preamble section of the main file, 382 // mark the main-file as include-guarded. 383 // This information is part of the HeaderFileInfo but is not loaded from the 384 // preamble as the file's size is part of its identity and may have changed. 385 // (The rest of HeaderFileInfo is not relevant for our purposes). 386 if (Preamble && Preamble->MainIsIncludeGuarded) { 387 const SourceManager &SM = Clang->getSourceManager(); 388 const FileEntry *MainFE = SM.getFileEntryForID(SM.getMainFileID()); 389 Clang->getPreprocessor().getHeaderSearchInfo().MarkFileIncludeOnce(MainFE); 390 } 391 392 // Set up ClangTidy. Must happen after BeginSourceFile() so ASTContext exists. 393 // Clang-tidy has some limitations to ensure reasonable performance: 394 // - checks don't see all preprocessor events in the preamble 395 // - matchers run only over the main-file top-level decls (and can't see 396 // ancestors outside this scope). 397 // In practice almost all checks work well without modifications. 398 std::vector<std::unique_ptr<tidy::ClangTidyCheck>> CTChecks; 399 ast_matchers::MatchFinder CTFinder; 400 llvm::Optional<tidy::ClangTidyContext> CTContext; 401 llvm::Optional<IncludeFixer> FixIncludes; 402 llvm::DenseMap<diag::kind, DiagnosticsEngine::Level> OverriddenSeverity; 403 // No need to run clang-tidy or IncludeFixerif we are not going to surface 404 // diagnostics. 405 if (PreserveDiags) { 406 trace::Span Tracer("ClangTidyInit"); 407 tidy::ClangTidyCheckFactories CTFactories; 408 for (const auto &E : tidy::ClangTidyModuleRegistry::entries()) 409 E.instantiate()->addCheckFactories(CTFactories); 410 CTContext.emplace(std::make_unique<tidy::DefaultOptionsProvider>( 411 tidy::ClangTidyGlobalOptions(), ClangTidyOpts)); 412 CTContext->setDiagnosticsEngine(&Clang->getDiagnostics()); 413 CTContext->setASTContext(&Clang->getASTContext()); 414 CTContext->setCurrentFile(Filename); 415 CTContext->setSelfContainedDiags(true); 416 CTChecks = CTFactories.createChecks(CTContext.getPointer()); 417 llvm::erase_if(CTChecks, [&](const auto &Check) { 418 return !Check->isLanguageVersionSupported(CTContext->getLangOpts()); 419 }); 420 Preprocessor *PP = &Clang->getPreprocessor(); 421 for (const auto &Check : CTChecks) { 422 Check->registerPPCallbacks(Clang->getSourceManager(), PP, PP); 423 Check->registerMatchers(&CTFinder); 424 } 425 426 // Clang only corrects typos for use of undeclared functions in C if that 427 // use is an error. Include fixer relies on typo correction, so pretend 428 // this is an error. (The actual typo correction is nice too). 429 // We restore the original severity in the level adjuster. 430 // FIXME: It would be better to have a real API for this, but what? 431 for (auto ID : {diag::ext_implicit_function_decl_c99, 432 diag::ext_implicit_lib_function_decl_c99, 433 diag::warn_implicit_function_decl}) { 434 OverriddenSeverity.try_emplace( 435 ID, Clang->getDiagnostics().getDiagnosticLevel(ID, SourceLocation())); 436 Clang->getDiagnostics().setSeverity(ID, diag::Severity::Error, 437 SourceLocation()); 438 } 439 440 const Config &Cfg = Config::current(); 441 ASTDiags.setLevelAdjuster([&](DiagnosticsEngine::Level DiagLevel, 442 const clang::Diagnostic &Info) { 443 if (Cfg.Diagnostics.SuppressAll || 444 isBuiltinDiagnosticSuppressed(Info.getID(), Cfg.Diagnostics.Suppress, 445 Clang->getLangOpts())) 446 return DiagnosticsEngine::Ignored; 447 448 auto It = OverriddenSeverity.find(Info.getID()); 449 if (It != OverriddenSeverity.end()) 450 DiagLevel = It->second; 451 452 if (!CTChecks.empty()) { 453 std::string CheckName = CTContext->getCheckName(Info.getID()); 454 bool IsClangTidyDiag = !CheckName.empty(); 455 if (IsClangTidyDiag) { 456 if (Cfg.Diagnostics.Suppress.contains(CheckName)) 457 return DiagnosticsEngine::Ignored; 458 // Check for suppression comment. Skip the check for diagnostics not 459 // in the main file, because we don't want that function to query the 460 // source buffer for preamble files. For the same reason, we ask 461 // shouldSuppressDiagnostic to avoid I/O. 462 // We let suppression comments take precedence over warning-as-error 463 // to match clang-tidy's behaviour. 464 bool IsInsideMainFile = 465 Info.hasSourceManager() && 466 isInsideMainFile(Info.getLocation(), Info.getSourceManager()); 467 SmallVector<tooling::Diagnostic, 1> TidySuppressedErrors; 468 if (IsInsideMainFile && CTContext->shouldSuppressDiagnostic( 469 DiagLevel, Info, TidySuppressedErrors, 470 /*AllowIO=*/false, 471 /*EnableNolintBlocks=*/true)) { 472 // FIXME: should we expose the suppression error (invalid use of 473 // NOLINT comments)? 474 return DiagnosticsEngine::Ignored; 475 } 476 477 // Check for warning-as-error. 478 if (DiagLevel == DiagnosticsEngine::Warning && 479 CTContext->treatAsError(CheckName)) { 480 return DiagnosticsEngine::Error; 481 } 482 } 483 } 484 return DiagLevel; 485 }); 486 487 // Add IncludeFixer which can recover diagnostics caused by missing includes 488 // (e.g. incomplete type) and attach include insertion fixes to diagnostics. 489 auto BuildDir = VFS->getCurrentWorkingDirectory(); 490 if (Inputs.Index && !BuildDir.getError()) { 491 auto Style = 492 getFormatStyleForFile(Filename, Inputs.Contents, *Inputs.TFS); 493 auto Inserter = std::make_shared<IncludeInserter>( 494 Filename, Inputs.Contents, Style, BuildDir.get(), 495 &Clang->getPreprocessor().getHeaderSearchInfo()); 496 if (Preamble) { 497 for (const auto &Inc : Preamble->Includes.MainFileIncludes) 498 Inserter->addExisting(Inc); 499 } 500 FixIncludes.emplace(Filename, Inserter, *Inputs.Index, 501 /*IndexRequestLimit=*/5); 502 ASTDiags.contributeFixes([&FixIncludes](DiagnosticsEngine::Level DiagLevl, 503 const clang::Diagnostic &Info) { 504 return FixIncludes->fix(DiagLevl, Info); 505 }); 506 Clang->setExternalSemaSource(FixIncludes->unresolvedNameRecorder()); 507 } 508 } 509 510 IncludeStructure Includes; 511 // If we are using a preamble, copy existing includes. 512 if (Preamble) { 513 Includes = Preamble->Includes; 514 Includes.MainFileIncludes = Patch->preambleIncludes(); 515 // Replay the preamble includes so that clang-tidy checks can see them. 516 ReplayPreamble::attach(Patch->preambleIncludes(), *Clang, 517 Patch->modifiedBounds()); 518 } 519 // Important: collectIncludeStructure is registered *after* ReplayPreamble! 520 // Otherwise we would collect the replayed includes again... 521 // (We can't *just* use the replayed includes, they don't have Resolved path). 522 Includes.collect(*Clang); 523 // Copy over the macros in the preamble region of the main file, and combine 524 // with non-preamble macros below. 525 MainFileMacros Macros; 526 if (Preamble) 527 Macros = Preamble->Macros; 528 Clang->getPreprocessor().addPPCallbacks( 529 std::make_unique<CollectMainFileMacros>(Clang->getSourceManager(), 530 Macros)); 531 532 std::vector<PragmaMark> Marks; 533 // FIXME: We need to patch the marks for stale preambles. 534 if (Preamble) 535 Marks = Preamble->Marks; 536 Clang->getPreprocessor().addPPCallbacks( 537 collectPragmaMarksCallback(Clang->getSourceManager(), Marks)); 538 539 // Copy over the includes from the preamble, then combine with the 540 // non-preamble includes below. 541 CanonicalIncludes CanonIncludes; 542 if (Preamble) 543 CanonIncludes = Preamble->CanonIncludes; 544 else 545 CanonIncludes.addSystemHeadersMapping(Clang->getLangOpts()); 546 std::unique_ptr<CommentHandler> IWYUHandler = 547 collectIWYUHeaderMaps(&CanonIncludes); 548 Clang->getPreprocessor().addCommentHandler(IWYUHandler.get()); 549 550 // Collect tokens of the main file. 551 syntax::TokenCollector CollectTokens(Clang->getPreprocessor()); 552 553 // To remain consistent with preamble builds, these callbacks must be called 554 // exactly here, after preprocessor is initialized and BeginSourceFile() was 555 // called already. 556 for (const auto &L : ASTListeners) 557 L->beforeExecute(*Clang); 558 559 if (llvm::Error Err = Action->Execute()) 560 log("Execute() failed when building AST for {0}: {1}", MainInput.getFile(), 561 toString(std::move(Err))); 562 563 // We have to consume the tokens before running clang-tidy to avoid collecting 564 // tokens from running the preprocessor inside the checks (only 565 // modernize-use-trailing-return-type does that today). 566 syntax::TokenBuffer Tokens = std::move(CollectTokens).consume(); 567 // Makes SelectionTree build much faster. 568 Tokens.indexExpandedTokens(); 569 std::vector<Decl *> ParsedDecls = Action->takeTopLevelDecls(); 570 // AST traversals should exclude the preamble, to avoid performance cliffs. 571 Clang->getASTContext().setTraversalScope(ParsedDecls); 572 if (!CTChecks.empty()) { 573 // Run the AST-dependent part of the clang-tidy checks. 574 // (The preprocessor part ran already, via PPCallbacks). 575 trace::Span Tracer("ClangTidyMatch"); 576 CTFinder.matchAST(Clang->getASTContext()); 577 } 578 579 // XXX: This is messy: clang-tidy checks flush some diagnostics at EOF. 580 // However Action->EndSourceFile() would destroy the ASTContext! 581 // So just inform the preprocessor of EOF, while keeping everything alive. 582 Clang->getPreprocessor().EndSourceFile(); 583 // UnitDiagsConsumer is local, we can not store it in CompilerInstance that 584 // has a longer lifetime. 585 Clang->getDiagnostics().setClient(new IgnoreDiagnostics); 586 // CompilerInstance won't run this callback, do it directly. 587 ASTDiags.EndSourceFile(); 588 589 llvm::Optional<std::vector<Diag>> Diags; 590 // FIXME: Also skip generation of diagnostics alltogether to speed up ast 591 // builds when we are patching a stale preamble. 592 if (PreserveDiags) { 593 Diags = CompilerInvocationDiags; 594 // Add diagnostics from the preamble, if any. 595 if (Preamble) 596 Diags->insert(Diags->end(), Preamble->Diags.begin(), 597 Preamble->Diags.end()); 598 // Finally, add diagnostics coming from the AST. 599 { 600 std::vector<Diag> D = ASTDiags.take(CTContext.getPointer()); 601 Diags->insert(Diags->end(), D.begin(), D.end()); 602 } 603 } 604 ParsedAST Result(Inputs.Version, std::move(Preamble), std::move(Clang), 605 std::move(Action), std::move(Tokens), std::move(Macros), 606 std::move(Marks), std::move(ParsedDecls), std::move(Diags), 607 std::move(Includes), std::move(CanonIncludes)); 608 if (Result.Diags) { 609 auto UnusedHeadersDiags = 610 issueUnusedIncludesDiagnostics(Result, Inputs.Contents); 611 Result.Diags->insert(Result.Diags->end(), 612 make_move_iterator(UnusedHeadersDiags.begin()), 613 make_move_iterator(UnusedHeadersDiags.end())); 614 } 615 return Result; 616 } 617 618 ParsedAST::ParsedAST(ParsedAST &&Other) = default; 619 620 ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default; 621 622 ParsedAST::~ParsedAST() { 623 if (Action) { 624 // We already notified the PP of end-of-file earlier, so detach it first. 625 // We must keep it alive until after EndSourceFile(), Sema relies on this. 626 auto PP = Clang->getPreprocessorPtr(); // Keep PP alive for now. 627 Clang->setPreprocessor(nullptr); // Detach so we don't send EOF again. 628 Action->EndSourceFile(); // Destroy ASTContext and Sema. 629 // Now Sema is gone, it's safe for PP to go out of scope. 630 } 631 } 632 633 ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); } 634 635 const ASTContext &ParsedAST::getASTContext() const { 636 return Clang->getASTContext(); 637 } 638 639 Sema &ParsedAST::getSema() { return Clang->getSema(); } 640 641 Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); } 642 643 std::shared_ptr<Preprocessor> ParsedAST::getPreprocessorPtr() { 644 return Clang->getPreprocessorPtr(); 645 } 646 647 const Preprocessor &ParsedAST::getPreprocessor() const { 648 return Clang->getPreprocessor(); 649 } 650 651 llvm::ArrayRef<Decl *> ParsedAST::getLocalTopLevelDecls() { 652 return LocalTopLevelDecls; 653 } 654 655 const MainFileMacros &ParsedAST::getMacros() const { return Macros; } 656 const std::vector<PragmaMark> &ParsedAST::getMarks() const { return Marks; } 657 658 std::size_t ParsedAST::getUsedBytes() const { 659 auto &AST = getASTContext(); 660 // FIXME(ibiryukov): we do not account for the dynamically allocated part of 661 // Message and Fixes inside each diagnostic. 662 std::size_t Total = clangd::getUsedBytes(LocalTopLevelDecls) + 663 (Diags ? clangd::getUsedBytes(*Diags) : 0); 664 665 // FIXME: the rest of the function is almost a direct copy-paste from 666 // libclang's clang_getCXTUResourceUsage. We could share the implementation. 667 668 // Sum up various allocators inside the ast context and the preprocessor. 669 Total += AST.getASTAllocatedMemory(); 670 Total += AST.getSideTableAllocatedMemory(); 671 Total += AST.Idents.getAllocator().getTotalMemory(); 672 Total += AST.Selectors.getTotalMemory(); 673 674 Total += AST.getSourceManager().getContentCacheSize(); 675 Total += AST.getSourceManager().getDataStructureSizes(); 676 Total += AST.getSourceManager().getMemoryBufferSizes().malloc_bytes; 677 678 if (ExternalASTSource *Ext = AST.getExternalSource()) 679 Total += Ext->getMemoryBufferSizes().malloc_bytes; 680 681 const Preprocessor &PP = getPreprocessor(); 682 Total += PP.getTotalMemory(); 683 if (PreprocessingRecord *PRec = PP.getPreprocessingRecord()) 684 Total += PRec->getTotalMemory(); 685 Total += PP.getHeaderSearchInfo().getTotalMemory(); 686 687 return Total; 688 } 689 690 const IncludeStructure &ParsedAST::getIncludeStructure() const { 691 return Includes; 692 } 693 694 const CanonicalIncludes &ParsedAST::getCanonicalIncludes() const { 695 return CanonIncludes; 696 } 697 698 ParsedAST::ParsedAST(llvm::StringRef Version, 699 std::shared_ptr<const PreambleData> Preamble, 700 std::unique_ptr<CompilerInstance> Clang, 701 std::unique_ptr<FrontendAction> Action, 702 syntax::TokenBuffer Tokens, MainFileMacros Macros, 703 std::vector<PragmaMark> Marks, 704 std::vector<Decl *> LocalTopLevelDecls, 705 llvm::Optional<std::vector<Diag>> Diags, 706 IncludeStructure Includes, CanonicalIncludes CanonIncludes) 707 : Version(Version), Preamble(std::move(Preamble)), Clang(std::move(Clang)), 708 Action(std::move(Action)), Tokens(std::move(Tokens)), 709 Macros(std::move(Macros)), Marks(std::move(Marks)), 710 Diags(std::move(Diags)), 711 LocalTopLevelDecls(std::move(LocalTopLevelDecls)), 712 Includes(std::move(Includes)), CanonIncludes(std::move(CanonIncludes)) { 713 Resolver = std::make_unique<HeuristicResolver>(getASTContext()); 714 assert(this->Clang); 715 assert(this->Action); 716 } 717 718 llvm::Optional<llvm::StringRef> ParsedAST::preambleVersion() const { 719 if (!Preamble) 720 return llvm::None; 721 return llvm::StringRef(Preamble->Version); 722 } 723 724 } // namespace clangd 725 } // namespace clang 726