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