1 //===- extra/modularize/Modularize.cpp - Check modularized headers --------===// 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 // This file implements a tool that checks whether a set of headers provides 11 // the consistent definitions required to use modules. For example, it detects 12 // whether the same entity (say, a NULL macro or size_t typedef) is defined in 13 // multiple headers or whether a header produces different definitions under 14 // different circumstances. These conditions cause modules built from the 15 // headers to behave poorly, and should be fixed before introducing a module 16 // map. 17 // 18 // Modularize takes as argument a file name for a file containing the 19 // newline-separated list of headers to check with respect to each other. 20 // Lines beginning with '#' and empty lines are ignored. 21 // Header file names followed by a colon and other space-separated 22 // file names will include those extra files as dependencies. 23 // The file names can be relative or full paths, but must be on the 24 // same line. 25 // 26 // Modularize also accepts regular front-end arguments. 27 // 28 // Usage: modularize [-prefix (optional header path prefix)] 29 // (include-files_list) [(front-end-options) ...] 30 // 31 // Note that unless a "-prefix (header path)" option is specified, 32 // non-absolute file paths in the header list file will be relative 33 // to the header list file directory. Use -prefix to specify a different 34 // directory. 35 // 36 // Note that by default, the underlying Clang front end assumes .h files 37 // contain C source. If your .h files in the file list contain C++ source, 38 // you should append the following to your command lines: -x c++ 39 // 40 // Modularize will do normal parsing, reporting normal errors and warnings, 41 // but will also report special error messages like the following: 42 // 43 // error: '(symbol)' defined at multiple locations: 44 // (file):(row):(column) 45 // (file):(row):(column) 46 // 47 // error: header '(file)' has different contents depending on how it was 48 // included 49 // 50 // The latter might be followed by messages like the following: 51 // 52 // note: '(symbol)' in (file) at (row):(column) not always provided 53 // 54 // Checks will also be performed for macro expansions, defined(macro) 55 // expressions, and preprocessor conditional directives that evaluate 56 // inconsistently, and can produce error messages like the following: 57 // 58 // (...)/SubHeader.h:11:5: 59 // #if SYMBOL == 1 60 // ^ 61 // error: Macro instance 'SYMBOL' has different values in this header, 62 // depending on how it was included. 63 // 'SYMBOL' expanded to: '1' with respect to these inclusion paths: 64 // (...)/Header1.h 65 // (...)/SubHeader.h 66 // (...)/SubHeader.h:3:9: 67 // #define SYMBOL 1 68 // ^ 69 // Macro defined here. 70 // 'SYMBOL' expanded to: '2' with respect to these inclusion paths: 71 // (...)/Header2.h 72 // (...)/SubHeader.h 73 // (...)/SubHeader.h:7:9: 74 // #define SYMBOL 2 75 // ^ 76 // Macro defined here. 77 // 78 // Checks will also be performed for '#include' directives that are 79 // nested inside 'extern "C/C++" {}' or 'namespace (name) {}' blocks, 80 // and can produce error message like the following: 81 // 82 // IncludeInExtern.h:2:3 83 // #include "Empty.h" 84 // ^ 85 // error: Include directive within extern "C" {}. 86 // IncludeInExtern.h:1:1 87 // extern "C" { 88 // ^ 89 // The "extern "C" {}" block is here. 90 // 91 // See PreprocessorTracker.cpp for additional details. 92 // 93 // Modularize also has an option ("-module-map-path=module.modulemap") that will 94 // skip the checks, and instead act as a module.modulemap generation assistant, 95 // generating a module map file based on the header list. An optional 96 // "-root-module=(rootName)" argument can specify a root module to be 97 // created in the generated module.modulemap file. Note that you will likely 98 // need to edit this file to suit the needs of your headers. 99 // 100 // An example command line for generating a module.modulemap file: 101 // 102 // modularize -module-map-path=module.modulemap -root-module=myroot \ 103 // headerlist.txt 104 // 105 // Note that if the headers in the header list have partial paths, sub-modules 106 // will be created for the subdirectires involved, assuming that the 107 // subdirectories contain headers to be grouped into a module, but still with 108 // individual modules for the headers in the subdirectory. 109 // 110 // See the ModuleAssistant.cpp file comments for additional details about the 111 // implementation of the assistant mode. 112 // 113 // Future directions: 114 // 115 // Basically, we want to add new checks for whatever we can check with respect 116 // to checking headers for module'ability. 117 // 118 // Some ideas: 119 // 120 // 1. Omit duplicate "not always provided" messages 121 // 122 // 2. Add options to disable any of the checks, in case 123 // there is some problem with them, or the messages get too verbose. 124 // 125 // 3. Try to figure out the preprocessor conditional directives that 126 // contribute to problems and tie them to the inconsistent definitions. 127 // 128 // 4. There are some legitimate uses of preprocessor macros that 129 // modularize will flag as errors, such as repeatedly #include'ing 130 // a file and using interleaving defined/undefined macros 131 // to change declarations in the included file. Is there a way 132 // to address this? Maybe have modularize accept a list of macros 133 // to ignore. Otherwise you can just exclude the file, after checking 134 // for legitimate errors. 135 // 136 // 5. What else? 137 // 138 // General clean-up and refactoring: 139 // 140 // 1. The Location class seems to be something that we might 141 // want to design to be applicable to a wider range of tools, and stick it 142 // somewhere into Tooling/ in mainline 143 // 144 //===----------------------------------------------------------------------===// 145 146 #include "Modularize.h" 147 #include "ModularizeUtilities.h" 148 #include "PreprocessorTracker.h" 149 #include "clang/AST/ASTConsumer.h" 150 #include "clang/AST/ASTContext.h" 151 #include "clang/AST/RecursiveASTVisitor.h" 152 #include "clang/Basic/SourceManager.h" 153 #include "clang/Driver/Options.h" 154 #include "clang/Frontend/CompilerInstance.h" 155 #include "clang/Frontend/FrontendActions.h" 156 #include "clang/Lex/Preprocessor.h" 157 #include "clang/Tooling/CompilationDatabase.h" 158 #include "clang/Tooling/Tooling.h" 159 #include "llvm/Option/Arg.h" 160 #include "llvm/Option/ArgList.h" 161 #include "llvm/Option/OptTable.h" 162 #include "llvm/Option/Option.h" 163 #include "llvm/Support/CommandLine.h" 164 #include "llvm/Support/FileSystem.h" 165 #include "llvm/Support/MemoryBuffer.h" 166 #include "llvm/Support/Path.h" 167 #include <algorithm> 168 #include <fstream> 169 #include <iterator> 170 #include <string> 171 #include <vector> 172 173 using namespace clang; 174 using namespace clang::driver; 175 using namespace clang::driver::options; 176 using namespace clang::tooling; 177 using namespace llvm; 178 using namespace llvm::opt; 179 using namespace Modularize; 180 181 // Option to specify a file name for a list of header files to check. 182 cl::list<std::string> 183 ListFileNames(cl::Positional, cl::value_desc("list"), 184 cl::desc("<list of one or more header list files>"), 185 cl::CommaSeparated); 186 187 // Collect all other arguments, which will be passed to the front end. 188 cl::list<std::string> 189 CC1Arguments(cl::ConsumeAfter, 190 cl::desc("<arguments to be passed to front end>...")); 191 192 // Option to specify a prefix to be prepended to the header names. 193 cl::opt<std::string> HeaderPrefix( 194 "prefix", cl::init(""), 195 cl::desc( 196 "Prepend header file paths with this prefix." 197 " If not specified," 198 " the files are considered to be relative to the header list file.")); 199 200 // Option for assistant mode, telling modularize to output a module map 201 // based on the headers list, and where to put it. 202 cl::opt<std::string> ModuleMapPath( 203 "module-map-path", cl::init(""), 204 cl::desc("Turn on module map output and specify output path or file name." 205 " If no path is specified and if prefix option is specified," 206 " use prefix for file path.")); 207 208 // Option for assistant mode, telling modularize to output a module map 209 // based on the headers list, and where to put it. 210 cl::opt<std::string> 211 RootModule("root-module", cl::init(""), 212 cl::desc("Specify the name of the root module.")); 213 214 // Option for limiting the #include-inside-extern-or-namespace-block 215 // check to only those headers explicitly listed in the header list. 216 // This is a work-around for private includes that purposefully get 217 // included inside blocks. 218 static cl::opt<bool> 219 BlockCheckHeaderListOnly("block-check-header-list-only", cl::init(false), 220 cl::desc("Only warn if #include directives are inside extern or namespace" 221 " blocks if the included header is in the header list.")); 222 223 // Save the program name for error messages. 224 const char *Argv0; 225 // Save the command line for comments. 226 std::string CommandLine; 227 228 // Helper function for finding the input file in an arguments list. 229 std::string findInputFile(const CommandLineArguments &CLArgs) { 230 std::unique_ptr<OptTable> Opts(createDriverOptTable()); 231 const unsigned IncludedFlagsBitmask = options::CC1Option; 232 unsigned MissingArgIndex, MissingArgCount; 233 SmallVector<const char *, 256> Argv; 234 for (CommandLineArguments::const_iterator I = CLArgs.begin(), 235 E = CLArgs.end(); 236 I != E; ++I) 237 Argv.push_back(I->c_str()); 238 std::unique_ptr<InputArgList> Args( 239 Opts->ParseArgs(Argv.data(), Argv.data() + Argv.size(), MissingArgIndex, 240 MissingArgCount, IncludedFlagsBitmask)); 241 std::vector<std::string> Inputs = Args->getAllArgValues(OPT_INPUT); 242 return Inputs.back(); 243 } 244 245 // This arguments adjuster inserts "-include (file)" arguments for header 246 // dependencies. 247 ArgumentsAdjuster getAddDependenciesAdjuster(DependencyMap &Dependencies) { 248 return [&Dependencies](const CommandLineArguments &Args) { 249 std::string InputFile = findInputFile(Args); 250 DependentsVector &FileDependents = Dependencies[InputFile]; 251 CommandLineArguments NewArgs(Args); 252 if (int Count = FileDependents.size()) { 253 for (int Index = 0; Index < Count; ++Index) { 254 NewArgs.push_back("-include"); 255 std::string File(std::string("\"") + FileDependents[Index] + 256 std::string("\"")); 257 NewArgs.push_back(FileDependents[Index]); 258 } 259 } 260 return NewArgs; 261 }; 262 } 263 264 // FIXME: The Location class seems to be something that we might 265 // want to design to be applicable to a wider range of tools, and stick it 266 // somewhere into Tooling/ in mainline 267 struct Location { 268 const FileEntry *File; 269 unsigned Line, Column; 270 271 Location() : File(), Line(), Column() {} 272 273 Location(SourceManager &SM, SourceLocation Loc) : File(), Line(), Column() { 274 Loc = SM.getExpansionLoc(Loc); 275 if (Loc.isInvalid()) 276 return; 277 278 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(Loc); 279 File = SM.getFileEntryForID(Decomposed.first); 280 if (!File) 281 return; 282 283 Line = SM.getLineNumber(Decomposed.first, Decomposed.second); 284 Column = SM.getColumnNumber(Decomposed.first, Decomposed.second); 285 } 286 287 operator bool() const { return File != nullptr; } 288 289 friend bool operator==(const Location &X, const Location &Y) { 290 return X.File == Y.File && X.Line == Y.Line && X.Column == Y.Column; 291 } 292 293 friend bool operator!=(const Location &X, const Location &Y) { 294 return !(X == Y); 295 } 296 297 friend bool operator<(const Location &X, const Location &Y) { 298 if (X.File != Y.File) 299 return X.File < Y.File; 300 if (X.Line != Y.Line) 301 return X.Line < Y.Line; 302 return X.Column < Y.Column; 303 } 304 friend bool operator>(const Location &X, const Location &Y) { return Y < X; } 305 friend bool operator<=(const Location &X, const Location &Y) { 306 return !(Y < X); 307 } 308 friend bool operator>=(const Location &X, const Location &Y) { 309 return !(X < Y); 310 } 311 }; 312 313 struct Entry { 314 enum EntryKind { 315 EK_Tag, 316 EK_Value, 317 EK_Macro, 318 319 EK_NumberOfKinds 320 } Kind; 321 322 Location Loc; 323 324 StringRef getKindName() { return getKindName(Kind); } 325 static StringRef getKindName(EntryKind kind); 326 }; 327 328 // Return a string representing the given kind. 329 StringRef Entry::getKindName(Entry::EntryKind kind) { 330 switch (kind) { 331 case EK_Tag: 332 return "tag"; 333 case EK_Value: 334 return "value"; 335 case EK_Macro: 336 return "macro"; 337 case EK_NumberOfKinds: 338 break; 339 } 340 llvm_unreachable("invalid Entry kind"); 341 } 342 343 struct HeaderEntry { 344 std::string Name; 345 Location Loc; 346 347 friend bool operator==(const HeaderEntry &X, const HeaderEntry &Y) { 348 return X.Loc == Y.Loc && X.Name == Y.Name; 349 } 350 friend bool operator!=(const HeaderEntry &X, const HeaderEntry &Y) { 351 return !(X == Y); 352 } 353 friend bool operator<(const HeaderEntry &X, const HeaderEntry &Y) { 354 return X.Loc < Y.Loc || (X.Loc == Y.Loc && X.Name < Y.Name); 355 } 356 friend bool operator>(const HeaderEntry &X, const HeaderEntry &Y) { 357 return Y < X; 358 } 359 friend bool operator<=(const HeaderEntry &X, const HeaderEntry &Y) { 360 return !(Y < X); 361 } 362 friend bool operator>=(const HeaderEntry &X, const HeaderEntry &Y) { 363 return !(X < Y); 364 } 365 }; 366 367 typedef std::vector<HeaderEntry> HeaderContents; 368 369 class EntityMap : public StringMap<SmallVector<Entry, 2> > { 370 public: 371 DenseMap<const FileEntry *, HeaderContents> HeaderContentMismatches; 372 373 void add(const std::string &Name, enum Entry::EntryKind Kind, Location Loc) { 374 // Record this entity in its header. 375 HeaderEntry HE = { Name, Loc }; 376 CurHeaderContents[Loc.File].push_back(HE); 377 378 // Check whether we've seen this entry before. 379 SmallVector<Entry, 2> &Entries = (*this)[Name]; 380 for (unsigned I = 0, N = Entries.size(); I != N; ++I) { 381 if (Entries[I].Kind == Kind && Entries[I].Loc == Loc) 382 return; 383 } 384 385 // We have not seen this entry before; record it. 386 Entry E = { Kind, Loc }; 387 Entries.push_back(E); 388 } 389 390 void mergeCurHeaderContents() { 391 for (DenseMap<const FileEntry *, HeaderContents>::iterator 392 H = CurHeaderContents.begin(), 393 HEnd = CurHeaderContents.end(); 394 H != HEnd; ++H) { 395 // Sort contents. 396 std::sort(H->second.begin(), H->second.end()); 397 398 // Check whether we've seen this header before. 399 DenseMap<const FileEntry *, HeaderContents>::iterator KnownH = 400 AllHeaderContents.find(H->first); 401 if (KnownH == AllHeaderContents.end()) { 402 // We haven't seen this header before; record its contents. 403 AllHeaderContents.insert(*H); 404 continue; 405 } 406 407 // If the header contents are the same, we're done. 408 if (H->second == KnownH->second) 409 continue; 410 411 // Determine what changed. 412 std::set_symmetric_difference( 413 H->second.begin(), H->second.end(), KnownH->second.begin(), 414 KnownH->second.end(), 415 std::back_inserter(HeaderContentMismatches[H->first])); 416 } 417 418 CurHeaderContents.clear(); 419 } 420 421 private: 422 DenseMap<const FileEntry *, HeaderContents> CurHeaderContents; 423 DenseMap<const FileEntry *, HeaderContents> AllHeaderContents; 424 }; 425 426 class CollectEntitiesVisitor 427 : public RecursiveASTVisitor<CollectEntitiesVisitor> { 428 public: 429 CollectEntitiesVisitor(SourceManager &SM, EntityMap &Entities, 430 Preprocessor &PP, PreprocessorTracker &PPTracker, 431 int &HadErrors) 432 : SM(SM), Entities(Entities), PP(PP), PPTracker(PPTracker), 433 HadErrors(HadErrors) {} 434 435 bool TraverseStmt(Stmt *S) { return true; } 436 bool TraverseType(QualType T) { return true; } 437 bool TraverseTypeLoc(TypeLoc TL) { return true; } 438 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { return true; } 439 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { 440 return true; 441 } 442 bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo) { 443 return true; 444 } 445 bool TraverseTemplateName(TemplateName Template) { return true; } 446 bool TraverseTemplateArgument(const TemplateArgument &Arg) { return true; } 447 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) { 448 return true; 449 } 450 bool TraverseTemplateArguments(const TemplateArgument *Args, 451 unsigned NumArgs) { 452 return true; 453 } 454 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; } 455 bool TraverseLambdaCapture(LambdaCapture C) { return true; } 456 457 // Check 'extern "*" {}' block for #include directives. 458 bool VisitLinkageSpecDecl(LinkageSpecDecl *D) { 459 // Bail if not a block. 460 if (!D->hasBraces()) 461 return true; 462 SourceRange BlockRange = D->getSourceRange(); 463 const char *LinkageLabel; 464 switch (D->getLanguage()) { 465 case LinkageSpecDecl::lang_c: 466 LinkageLabel = "extern \"C\" {}"; 467 break; 468 case LinkageSpecDecl::lang_cxx: 469 LinkageLabel = "extern \"C++\" {}"; 470 break; 471 } 472 if (!PPTracker.checkForIncludesInBlock(PP, BlockRange, LinkageLabel, 473 errs())) 474 HadErrors = 1; 475 return true; 476 } 477 478 // Check 'namespace (name) {}' block for #include directives. 479 bool VisitNamespaceDecl(const NamespaceDecl *D) { 480 SourceRange BlockRange = D->getSourceRange(); 481 std::string Label("namespace "); 482 Label += D->getName(); 483 Label += " {}"; 484 if (!PPTracker.checkForIncludesInBlock(PP, BlockRange, Label.c_str(), 485 errs())) 486 HadErrors = 1; 487 return true; 488 } 489 490 // Collect definition entities. 491 bool VisitNamedDecl(NamedDecl *ND) { 492 // We only care about file-context variables. 493 if (!ND->getDeclContext()->isFileContext()) 494 return true; 495 496 // Skip declarations that tend to be properly multiply-declared. 497 if (isa<NamespaceDecl>(ND) || isa<UsingDirectiveDecl>(ND) || 498 isa<NamespaceAliasDecl>(ND) || 499 isa<ClassTemplateSpecializationDecl>(ND) || isa<UsingDecl>(ND) || 500 isa<ClassTemplateDecl>(ND) || isa<TemplateTypeParmDecl>(ND) || 501 isa<TypeAliasTemplateDecl>(ND) || isa<UsingShadowDecl>(ND) || 502 isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) || 503 (isa<TagDecl>(ND) && 504 !cast<TagDecl>(ND)->isThisDeclarationADefinition())) 505 return true; 506 507 // Skip anonymous declarations. 508 if (!ND->getDeclName()) 509 return true; 510 511 // Get the qualified name. 512 std::string Name; 513 llvm::raw_string_ostream OS(Name); 514 ND->printQualifiedName(OS); 515 OS.flush(); 516 if (Name.empty()) 517 return true; 518 519 Location Loc(SM, ND->getLocation()); 520 if (!Loc) 521 return true; 522 523 Entities.add(Name, isa<TagDecl>(ND) ? Entry::EK_Tag : Entry::EK_Value, Loc); 524 return true; 525 } 526 527 private: 528 SourceManager &SM; 529 EntityMap &Entities; 530 Preprocessor &PP; 531 PreprocessorTracker &PPTracker; 532 int &HadErrors; 533 }; 534 535 class CollectEntitiesConsumer : public ASTConsumer { 536 public: 537 CollectEntitiesConsumer(EntityMap &Entities, 538 PreprocessorTracker &preprocessorTracker, 539 Preprocessor &PP, StringRef InFile, int &HadErrors) 540 : Entities(Entities), PPTracker(preprocessorTracker), PP(PP), 541 HadErrors(HadErrors) { 542 PPTracker.handlePreprocessorEntry(PP, InFile); 543 } 544 545 ~CollectEntitiesConsumer() { PPTracker.handlePreprocessorExit(); } 546 547 virtual void HandleTranslationUnit(ASTContext &Ctx) { 548 SourceManager &SM = Ctx.getSourceManager(); 549 550 // Collect declared entities. 551 CollectEntitiesVisitor(SM, Entities, PP, PPTracker, HadErrors) 552 .TraverseDecl(Ctx.getTranslationUnitDecl()); 553 554 // Collect macro definitions. 555 for (Preprocessor::macro_iterator M = PP.macro_begin(), 556 MEnd = PP.macro_end(); 557 M != MEnd; ++M) { 558 Location Loc(SM, M->second->getLocation()); 559 if (!Loc) 560 continue; 561 562 Entities.add(M->first->getName().str(), Entry::EK_Macro, Loc); 563 } 564 565 // Merge header contents. 566 Entities.mergeCurHeaderContents(); 567 } 568 569 private: 570 EntityMap &Entities; 571 PreprocessorTracker &PPTracker; 572 Preprocessor &PP; 573 int &HadErrors; 574 }; 575 576 class CollectEntitiesAction : public SyntaxOnlyAction { 577 public: 578 CollectEntitiesAction(EntityMap &Entities, 579 PreprocessorTracker &preprocessorTracker, 580 int &HadErrors) 581 : Entities(Entities), PPTracker(preprocessorTracker), 582 HadErrors(HadErrors) {} 583 584 protected: 585 std::unique_ptr<clang::ASTConsumer> 586 CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override { 587 return llvm::make_unique<CollectEntitiesConsumer>( 588 Entities, PPTracker, CI.getPreprocessor(), InFile, HadErrors); 589 } 590 591 private: 592 EntityMap &Entities; 593 PreprocessorTracker &PPTracker; 594 int &HadErrors; 595 }; 596 597 class ModularizeFrontendActionFactory : public FrontendActionFactory { 598 public: 599 ModularizeFrontendActionFactory(EntityMap &Entities, 600 PreprocessorTracker &preprocessorTracker, 601 int &HadErrors) 602 : Entities(Entities), PPTracker(preprocessorTracker), 603 HadErrors(HadErrors) {} 604 605 virtual CollectEntitiesAction *create() { 606 return new CollectEntitiesAction(Entities, PPTracker, HadErrors); 607 } 608 609 private: 610 EntityMap &Entities; 611 PreprocessorTracker &PPTracker; 612 int &HadErrors; 613 }; 614 615 int main(int Argc, const char **Argv) { 616 617 // Save program name for error messages. 618 Argv0 = Argv[0]; 619 620 // Save program arguments for use in module.modulemap comment. 621 CommandLine = sys::path::stem(sys::path::filename(Argv0)); 622 for (int ArgIndex = 1; ArgIndex < Argc; ArgIndex++) { 623 CommandLine.append(" "); 624 CommandLine.append(Argv[ArgIndex]); 625 } 626 627 // This causes options to be parsed. 628 cl::ParseCommandLineOptions(Argc, Argv, "modularize.\n"); 629 630 // No go if we have no header list file. 631 if (ListFileNames.size() == 0) { 632 cl::PrintHelpMessage(); 633 return 1; 634 } 635 636 std::unique_ptr<ModularizeUtilities> ModUtil; 637 638 ModUtil.reset( 639 ModularizeUtilities::createModularizeUtilities( 640 ListFileNames, HeaderPrefix)); 641 642 // Get header file names and dependencies. 643 ModUtil->loadAllHeaderListsAndDependencies(); 644 645 646 // If we are in assistant mode, output the module map and quit. 647 if (ModuleMapPath.length() != 0) { 648 if (!createModuleMap(ModuleMapPath, ModUtil->HeaderFileNames, 649 ModUtil->Dependencies, HeaderPrefix, RootModule)) 650 return 1; // Failed. 651 return 0; // Success - Skip checks in assistant mode. 652 } 653 654 // Create the compilation database. 655 SmallString<256> PathBuf; 656 sys::fs::current_path(PathBuf); 657 std::unique_ptr<CompilationDatabase> Compilations; 658 Compilations.reset( 659 new FixedCompilationDatabase(Twine(PathBuf), CC1Arguments)); 660 661 // Create preprocessor tracker, to watch for macro and conditional problems. 662 std::unique_ptr<PreprocessorTracker> PPTracker( 663 PreprocessorTracker::create(ModUtil->HeaderFileNames, 664 BlockCheckHeaderListOnly)); 665 666 // Parse all of the headers, detecting duplicates. 667 EntityMap Entities; 668 ClangTool Tool(*Compilations, ModUtil->HeaderFileNames); 669 Tool.appendArgumentsAdjuster(getAddDependenciesAdjuster(ModUtil->Dependencies)); 670 int HadErrors = 0; 671 ModularizeFrontendActionFactory Factory(Entities, *PPTracker, HadErrors); 672 HadErrors |= Tool.run(&Factory); 673 674 // Create a place to save duplicate entity locations, separate bins per kind. 675 typedef SmallVector<Location, 8> LocationArray; 676 typedef SmallVector<LocationArray, Entry::EK_NumberOfKinds> EntryBinArray; 677 EntryBinArray EntryBins; 678 int KindIndex; 679 for (KindIndex = 0; KindIndex < Entry::EK_NumberOfKinds; ++KindIndex) { 680 LocationArray Array; 681 EntryBins.push_back(Array); 682 } 683 684 // Check for the same entity being defined in multiple places. 685 for (EntityMap::iterator E = Entities.begin(), EEnd = Entities.end(); 686 E != EEnd; ++E) { 687 // If only one occurrence, exit early. 688 if (E->second.size() == 1) 689 continue; 690 // Clear entity locations. 691 for (EntryBinArray::iterator CI = EntryBins.begin(), CE = EntryBins.end(); 692 CI != CE; ++CI) { 693 CI->clear(); 694 } 695 // Walk the entities of a single name, collecting the locations, 696 // separated into separate bins. 697 for (unsigned I = 0, N = E->second.size(); I != N; ++I) { 698 EntryBins[E->second[I].Kind].push_back(E->second[I].Loc); 699 } 700 // Report any duplicate entity definition errors. 701 int KindIndex = 0; 702 for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end(); 703 DI != DE; ++DI, ++KindIndex) { 704 int ECount = DI->size(); 705 // If only 1 occurrence of this entity, skip it, as we only report duplicates. 706 if (ECount <= 1) 707 continue; 708 LocationArray::iterator FI = DI->begin(); 709 StringRef kindName = Entry::getKindName((Entry::EntryKind)KindIndex); 710 errs() << "error: " << kindName << " '" << E->first() 711 << "' defined at multiple locations:\n"; 712 for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) { 713 errs() << " " << FI->File->getName() << ":" << FI->Line << ":" 714 << FI->Column << "\n"; 715 } 716 HadErrors = 1; 717 } 718 } 719 720 // Complain about macro instance in header files that differ based on how 721 // they are included. 722 if (PPTracker->reportInconsistentMacros(errs())) 723 HadErrors = 1; 724 725 // Complain about preprocessor conditional directives in header files that 726 // differ based on how they are included. 727 if (PPTracker->reportInconsistentConditionals(errs())) 728 HadErrors = 1; 729 730 // Complain about any headers that have contents that differ based on how 731 // they are included. 732 // FIXME: Could we provide information about which preprocessor conditionals 733 // are involved? 734 for (DenseMap<const FileEntry *, HeaderContents>::iterator 735 H = Entities.HeaderContentMismatches.begin(), 736 HEnd = Entities.HeaderContentMismatches.end(); 737 H != HEnd; ++H) { 738 if (H->second.empty()) { 739 errs() << "internal error: phantom header content mismatch\n"; 740 continue; 741 } 742 743 HadErrors = 1; 744 errs() << "error: header '" << H->first->getName() 745 << "' has different contents depending on how it was included.\n"; 746 for (unsigned I = 0, N = H->second.size(); I != N; ++I) { 747 errs() << "note: '" << H->second[I].Name << "' in " 748 << H->second[I].Loc.File->getName() << " at " 749 << H->second[I].Loc.Line << ":" << H->second[I].Loc.Column 750 << " not always provided\n"; 751 } 752 } 753 754 return HadErrors; 755 } 756