blob: 4acfe72b42e0381e9a3288e6f1c02fbaee1439d5 [file] [log] [blame]
John Thompsond977c1e2013-03-27 18:34:38 +00001//===- extra/modularize/Modularize.cpp - Check modularized headers --------===//
John Thompson4f8ba652013-03-12 02:07:30 +00002//
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//
John Thompson8eb8d932015-02-19 16:47:27 +000010// Introduction
11//
John Thompson4f8ba652013-03-12 02:07:30 +000012// This file implements a tool that checks whether a set of headers provides
John Thompson9cb79642015-02-18 16:14:32 +000013// 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
John Thompson4f8ba652013-03-12 02:07:30 +000019// different circumstances. These conditions cause modules built from the
John Thompsonf5db45b2013-03-27 01:02:46 +000020// headers to behave poorly, and should be fixed before introducing a module
John Thompson4f8ba652013-03-12 02:07:30 +000021// map.
22//
John Thompson9cb79642015-02-18 16:14:32 +000023// 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.
John Thompsonf5db45b2013-03-27 01:02:46 +000037// Lines beginning with '#' and empty lines are ignored.
John Thompson7d0213c2013-09-04 20:46:24 +000038// 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//
John Thompson9cb79642015-02-18 16:14:32 +000043// Modularize also accepts regular clang front-end arguments.
John Thompson4f8ba652013-03-12 02:07:30 +000044//
John Thompson9cb79642015-02-18 16:14:32 +000045// Usage: modularize [(modularize options)]
46// [(include-files_list)|(module map)]+ [(front-end-options) ...]
John Thompsoneaa4c732015-02-18 15:11:12 +000047//
48// Options:
John Thompsoncf777e92015-06-04 01:10:19 +000049// -prefix=(optional header path prefix)
John Thompsoneaa4c732015-02-18 15:11:12 +000050// 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.
John Thompsoncf777e92015-06-04 01:10:19 +000054// -module-map-path=(module map)
John Thompsoneaa4c732015-02-18 15:11:12 +000055// 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.
John Thompsoncf777e92015-06-04 01:10:19 +000061// -root-module=(root module name)
John Thompsoneaa4c732015-02-18 15:11:12 +000062// 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.
John Thompson8eb8d932015-02-19 16:47:27 +000067// -no-coverage-check
68// Don't do the coverage check.
69// -coverage-check-only
70// Only do the coverage check.
John Thompsona2de1082013-03-26 01:17:48 +000071//
John Thompson8eb8d932015-02-19 16:47:27 +000072// 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.
John Thompson4f8ba652013-03-12 02:07:30 +000075//
John Thompsonf9f62b12015-05-06 18:43:01 +000076// Note that by default, the modularize assumes .h files contain C++ source.
77// If your .h files in the file list contain another language, you should
78// append an appropriate -x option to your command line, i.e.: -x c
John Thompsonfd8ca382013-03-27 19:31:22 +000079//
John Thompson8eb8d932015-02-19 16:47:27 +000080// 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,
John Thompson4f8ba652013-03-12 02:07:30 +000084// but will also report special error messages like the following:
85//
John Thompson7c6e79f32013-07-29 19:07:00 +000086// error: '(symbol)' defined at multiple locations:
87// (file):(row):(column)
88// (file):(row):(column)
John Thompson4f8ba652013-03-12 02:07:30 +000089//
John Thompsondc118272013-07-29 21:59:41 +000090// error: header '(file)' has different contents depending on how it was
John Thompson7c6e79f32013-07-29 19:07:00 +000091// included
John Thompson4f8ba652013-03-12 02:07:30 +000092//
93// The latter might be followed by messages like the following:
94//
John Thompson7c6e79f32013-07-29 19:07:00 +000095// note: '(symbol)' in (file) at (row):(column) not always provided
John Thompson4f8ba652013-03-12 02:07:30 +000096//
John Thompson7c6e79f32013-07-29 19:07:00 +000097// 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//
Nico Weber8e20be22013-08-12 11:43:36 +0000101// (...)/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//
John Thompson74083922013-09-18 18:19:43 +0000121// 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//
John Thompson4fa9c2c2013-08-09 00:19:03 +0000134// See PreprocessorTracker.cpp for additional details.
John Thompsoncc2e2912013-09-03 18:44:11 +0000135//
John Thompson8eb8d932015-02-19 16:47:27 +0000136// 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//
John Thompson5d9862f2015-02-10 14:45:30 +0000166// 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,
John Thompson5ab4f112013-10-15 13:52:33 +0000168// generating a module map file based on the header list. An optional
169// "-root-module=(rootName)" argument can specify a root module to be
John Thompson5d9862f2015-02-10 14:45:30 +0000170// created in the generated module.modulemap file. Note that you will likely
John Thompson5ab4f112013-10-15 13:52:33 +0000171// need to edit this file to suit the needs of your headers.
172//
John Thompson5d9862f2015-02-10 14:45:30 +0000173// An example command line for generating a module.modulemap file:
John Thompson5ab4f112013-10-15 13:52:33 +0000174//
John Thompson5d9862f2015-02-10 14:45:30 +0000175// modularize -module-map-path=module.modulemap -root-module=myroot \
176// headerlist.txt
John Thompson5ab4f112013-10-15 13:52:33 +0000177//
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//
John Thompson74751802013-09-03 18:48:43 +0000186// 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//
John Thompson74083922013-09-18 18:19:43 +0000193// 1. Omit duplicate "not always provided" messages
John Thompson53a9d2d2013-09-04 18:29:36 +0000194//
John Thompson74083922013-09-18 18:19:43 +0000195// 2. Add options to disable any of the checks, in case
John Thompson74751802013-09-03 18:48:43 +0000196// there is some problem with them, or the messages get too verbose.
197//
John Thompson74083922013-09-18 18:19:43 +0000198// 3. Try to figure out the preprocessor conditional directives that
John Thompson74751802013-09-03 18:48:43 +0000199// contribute to problems and tie them to the inconsistent definitions.
200//
John Thompson74083922013-09-18 18:19:43 +0000201// 4. There are some legitimate uses of preprocessor macros that
Bob Wilsonf5999bd2013-09-04 16:48:28 +0000202// 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//
John Thompson74083922013-09-18 18:19:43 +0000209// 5. What else?
John Thompsonce601e22013-03-14 01:41:29 +0000210//
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//
John Thompson4f8ba652013-03-12 02:07:30 +0000217//===----------------------------------------------------------------------===//
John Thompsonf5db45b2013-03-27 01:02:46 +0000218
Chandler Carruth85e6e872014-01-07 20:05:01 +0000219#include "Modularize.h"
John Thompsond845bae2015-02-13 14:29:22 +0000220#include "ModularizeUtilities.h"
Chandler Carruth85e6e872014-01-07 20:05:01 +0000221#include "PreprocessorTracker.h"
Chandler Carruthf7e45c02014-01-07 22:15:39 +0000222#include "clang/AST/ASTConsumer.h"
John Thompsond977c1e2013-03-27 18:34:38 +0000223#include "clang/AST/ASTContext.h"
224#include "clang/AST/RecursiveASTVisitor.h"
225#include "clang/Basic/SourceManager.h"
John Thompson7d0213c2013-09-04 20:46:24 +0000226#include "clang/Driver/Options.h"
John Thompsond977c1e2013-03-27 18:34:38 +0000227#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"
John Thompson7d0213c2013-09-04 20:46:24 +0000232#include "llvm/Option/Arg.h"
233#include "llvm/Option/ArgList.h"
234#include "llvm/Option/OptTable.h"
235#include "llvm/Option/Option.h"
John Thompsona2de1082013-03-26 01:17:48 +0000236#include "llvm/Support/CommandLine.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000237#include "llvm/Support/FileSystem.h"
John Thompsonf5db45b2013-03-27 01:02:46 +0000238#include "llvm/Support/MemoryBuffer.h"
John Thompsona2de1082013-03-26 01:17:48 +0000239#include "llvm/Support/Path.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000240#include <algorithm>
John Thompsond977c1e2013-03-27 18:34:38 +0000241#include <fstream>
John Thompson4f8ba652013-03-12 02:07:30 +0000242#include <iterator>
John Thompsond977c1e2013-03-27 18:34:38 +0000243#include <string>
244#include <vector>
John Thompson4f8ba652013-03-12 02:07:30 +0000245
Bob Wilsonf5999bd2013-09-04 16:48:28 +0000246using namespace clang;
John Thompson7d0213c2013-09-04 20:46:24 +0000247using namespace clang::driver;
248using namespace clang::driver::options;
249using namespace clang::tooling;
John Thompsona2de1082013-03-26 01:17:48 +0000250using namespace llvm;
John Thompson7d0213c2013-09-04 20:46:24 +0000251using namespace llvm::opt;
John Thompson94faa4d2013-07-26 23:56:42 +0000252using namespace Modularize;
John Thompson4f8ba652013-03-12 02:07:30 +0000253
John Thompsonea6c8db2013-03-27 21:23:21 +0000254// Option to specify a file name for a list of header files to check.
Benjamin Kramere7103712015-03-23 12:49:15 +0000255static 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);
John Thompsonea6c8db2013-03-27 21:23:21 +0000259
260// Collect all other arguments, which will be passed to the front end.
Benjamin Kramere7103712015-03-23 12:49:15 +0000261static cl::list<std::string>
262 CC1Arguments(cl::ConsumeAfter,
263 cl::desc("<arguments to be passed to front end>..."));
John Thompsonea6c8db2013-03-27 21:23:21 +0000264
265// Option to specify a prefix to be prepended to the header names.
Benjamin Kramere7103712015-03-23 12:49:15 +0000266static cl::opt<std::string> HeaderPrefix(
John Thompsonea6c8db2013-03-27 21:23:21 +0000267 "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
John Thompson5ab4f112013-10-15 13:52:33 +0000273// Option for assistant mode, telling modularize to output a module map
274// based on the headers list, and where to put it.
Benjamin Kramere7103712015-03-23 12:49:15 +0000275static cl::opt<std::string> ModuleMapPath(
John Thompson5ab4f112013-10-15 13:52:33 +0000276 "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.
Benjamin Kramere7103712015-03-23 12:49:15 +0000283static cl::opt<std::string>
John Thompson5ab4f112013-10-15 13:52:33 +0000284RootModule("root-module", cl::init(""),
285 cl::desc("Specify the name of the root module."));
286
John Thompsonecd3b042015-02-11 16:58:36 +0000287// 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.
291static cl::opt<bool>
292BlockCheckHeaderListOnly("block-check-header-list-only", cl::init(false),
293cl::desc("Only warn if #include directives are inside extern or namespace"
294 " blocks if the included header is in the header list."));
295
John Thompson8eb8d932015-02-19 16:47:27 +0000296// Option for include paths for coverage check.
297static cl::list<std::string>
298IncludePaths("I", cl::desc("Include path for coverage check."),
299cl::ZeroOrMore, cl::value_desc("path"));
300
301// Option for just doing the coverage check.
302static cl::opt<bool>
303NoCoverageCheck("no-coverage-check", cl::init(false),
304cl::desc("Don't do the coverage check."));
305
306// Option for just doing the coverage check.
307static cl::opt<bool>
308CoverageCheckOnly("coverage-check-only", cl::init(false),
309cl::desc("Only do the coverage check."));
310
John Thompson5ab4f112013-10-15 13:52:33 +0000311// Save the program name for error messages.
312const char *Argv0;
313// Save the command line for comments.
314std::string CommandLine;
Bob Wilsonf5999bd2013-09-04 16:48:28 +0000315
John Thompson7d0213c2013-09-04 20:46:24 +0000316// Helper function for finding the input file in an arguments list.
Benjamin Kramere7103712015-03-23 12:49:15 +0000317static std::string findInputFile(const CommandLineArguments &CLArgs) {
Ahmed Charles6a2dc5c2014-03-09 09:24:40 +0000318 std::unique_ptr<OptTable> Opts(createDriverOptTable());
John Thompson7d0213c2013-09-04 20:46:24 +0000319 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());
David Blaikie1f02f962015-06-22 22:06:58 +0000326 InputArgList Args = Opts->ParseArgs(Argv, MissingArgIndex, MissingArgCount,
327 IncludedFlagsBitmask);
328 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
John Thompson3dcb3932015-02-17 20:43:47 +0000329 return ModularizeUtilities::getCanonicalPath(Inputs.back());
John Thompson7d0213c2013-09-04 20:46:24 +0000330}
331
Alexander Kornienkod3657312014-12-03 17:53:03 +0000332// This arguments adjuster inserts "-include (file)" arguments for header
John Thompsonf9f62b12015-05-06 18:43:01 +0000333// dependencies. It also insertts a "-w" option and a "-x c++",
334// if no other "-x" option is present.
Benjamin Kramere7103712015-03-23 12:49:15 +0000335static ArgumentsAdjuster
John Thompsoncf777e92015-06-04 01:10:19 +0000336getModularizeArgumentsAdjuster(DependencyMap &Dependencies) {
Alexander Kornienkod3657312014-12-03 17:53:03 +0000337 return [&Dependencies](const CommandLineArguments &Args) {
John Thompson7d0213c2013-09-04 20:46:24 +0000338 std::string InputFile = findInputFile(Args);
339 DependentsVector &FileDependents = Dependencies[InputFile];
John Thompson7d0213c2013-09-04 20:46:24 +0000340 CommandLineArguments NewArgs(Args);
Alexander Kornienkod3657312014-12-03 17:53:03 +0000341 if (int Count = FileDependents.size()) {
342 for (int Index = 0; Index < Count; ++Index) {
343 NewArgs.push_back("-include");
344 std::string File(std::string("\"") + FileDependents[Index] +
345 std::string("\""));
346 NewArgs.push_back(FileDependents[Index]);
347 }
John Thompson7d0213c2013-09-04 20:46:24 +0000348 }
John Thompsonf9f62b12015-05-06 18:43:01 +0000349 // Ignore warnings. (Insert after "clang_tool" at beginning.)
350 NewArgs.insert(NewArgs.begin() + 1, "-w");
351 // Since we are compiling .h files, assume C++ unless given a -x option.
352 if (std::find(NewArgs.begin(), NewArgs.end(), "-x") == NewArgs.end()) {
353 NewArgs.insert(NewArgs.begin() + 2, "-x");
354 NewArgs.insert(NewArgs.begin() + 3, "c++");
355 }
John Thompson7d0213c2013-09-04 20:46:24 +0000356 return NewArgs;
Alexander Kornienkod3657312014-12-03 17:53:03 +0000357 };
358}
John Thompson7d0213c2013-09-04 20:46:24 +0000359
John Thompsonce601e22013-03-14 01:41:29 +0000360// FIXME: The Location class seems to be something that we might
361// want to design to be applicable to a wider range of tools, and stick it
362// somewhere into Tooling/ in mainline
John Thompson4f8ba652013-03-12 02:07:30 +0000363struct Location {
364 const FileEntry *File;
365 unsigned Line, Column;
John Thompsonf5db45b2013-03-27 01:02:46 +0000366
367 Location() : File(), Line(), Column() {}
368
John Thompson4f8ba652013-03-12 02:07:30 +0000369 Location(SourceManager &SM, SourceLocation Loc) : File(), Line(), Column() {
370 Loc = SM.getExpansionLoc(Loc);
371 if (Loc.isInvalid())
372 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000373
John Thompson4f8ba652013-03-12 02:07:30 +0000374 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(Loc);
375 File = SM.getFileEntryForID(Decomposed.first);
376 if (!File)
377 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000378
John Thompson4f8ba652013-03-12 02:07:30 +0000379 Line = SM.getLineNumber(Decomposed.first, Decomposed.second);
380 Column = SM.getColumnNumber(Decomposed.first, Decomposed.second);
381 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000382
Craig Topperf61be9c2014-06-09 02:03:06 +0000383 operator bool() const { return File != nullptr; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000384
John Thompson4f8ba652013-03-12 02:07:30 +0000385 friend bool operator==(const Location &X, const Location &Y) {
386 return X.File == Y.File && X.Line == Y.Line && X.Column == Y.Column;
387 }
388
389 friend bool operator!=(const Location &X, const Location &Y) {
390 return !(X == Y);
391 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000392
John Thompson4f8ba652013-03-12 02:07:30 +0000393 friend bool operator<(const Location &X, const Location &Y) {
394 if (X.File != Y.File)
395 return X.File < Y.File;
396 if (X.Line != Y.Line)
397 return X.Line < Y.Line;
398 return X.Column < Y.Column;
399 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000400 friend bool operator>(const Location &X, const Location &Y) { return Y < X; }
John Thompson4f8ba652013-03-12 02:07:30 +0000401 friend bool operator<=(const Location &X, const Location &Y) {
402 return !(Y < X);
403 }
404 friend bool operator>=(const Location &X, const Location &Y) {
405 return !(X < Y);
406 }
John Thompson4f8ba652013-03-12 02:07:30 +0000407};
408
John Thompson4f8ba652013-03-12 02:07:30 +0000409struct Entry {
John Thompson52d98862013-03-28 18:38:43 +0000410 enum EntryKind {
411 EK_Tag,
412 EK_Value,
413 EK_Macro,
414
415 EK_NumberOfKinds
John Thompson4f8ba652013-03-12 02:07:30 +0000416 } Kind;
John Thompsonf5db45b2013-03-27 01:02:46 +0000417
John Thompson4f8ba652013-03-12 02:07:30 +0000418 Location Loc;
John Thompson4e4d9b32013-03-28 01:20:19 +0000419
420 StringRef getKindName() { return getKindName(Kind); }
John Thompson52d98862013-03-28 18:38:43 +0000421 static StringRef getKindName(EntryKind kind);
John Thompson4f8ba652013-03-12 02:07:30 +0000422};
423
John Thompson4e4d9b32013-03-28 01:20:19 +0000424// Return a string representing the given kind.
John Thompson52d98862013-03-28 18:38:43 +0000425StringRef Entry::getKindName(Entry::EntryKind kind) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000426 switch (kind) {
John Thompson52d98862013-03-28 18:38:43 +0000427 case EK_Tag:
John Thompson4e4d9b32013-03-28 01:20:19 +0000428 return "tag";
John Thompson52d98862013-03-28 18:38:43 +0000429 case EK_Value:
John Thompson4e4d9b32013-03-28 01:20:19 +0000430 return "value";
John Thompson52d98862013-03-28 18:38:43 +0000431 case EK_Macro:
John Thompson4e4d9b32013-03-28 01:20:19 +0000432 return "macro";
John Thompson52d98862013-03-28 18:38:43 +0000433 case EK_NumberOfKinds:
John Thompson4e4d9b32013-03-28 01:20:19 +0000434 break;
John Thompson4e4d9b32013-03-28 01:20:19 +0000435 }
David Blaikiec66c07d2013-03-28 02:30:37 +0000436 llvm_unreachable("invalid Entry kind");
John Thompson4e4d9b32013-03-28 01:20:19 +0000437}
438
John Thompson4f8ba652013-03-12 02:07:30 +0000439struct HeaderEntry {
440 std::string Name;
441 Location Loc;
John Thompsonf5db45b2013-03-27 01:02:46 +0000442
John Thompson4f8ba652013-03-12 02:07:30 +0000443 friend bool operator==(const HeaderEntry &X, const HeaderEntry &Y) {
444 return X.Loc == Y.Loc && X.Name == Y.Name;
445 }
446 friend bool operator!=(const HeaderEntry &X, const HeaderEntry &Y) {
447 return !(X == Y);
448 }
449 friend bool operator<(const HeaderEntry &X, const HeaderEntry &Y) {
450 return X.Loc < Y.Loc || (X.Loc == Y.Loc && X.Name < Y.Name);
451 }
452 friend bool operator>(const HeaderEntry &X, const HeaderEntry &Y) {
453 return Y < X;
454 }
455 friend bool operator<=(const HeaderEntry &X, const HeaderEntry &Y) {
456 return !(Y < X);
457 }
458 friend bool operator>=(const HeaderEntry &X, const HeaderEntry &Y) {
459 return !(X < Y);
460 }
461};
462
463typedef std::vector<HeaderEntry> HeaderContents;
464
John Thompsonf5db45b2013-03-27 01:02:46 +0000465class EntityMap : public StringMap<SmallVector<Entry, 2> > {
John Thompson4f8ba652013-03-12 02:07:30 +0000466public:
John Thompsonf5db45b2013-03-27 01:02:46 +0000467 DenseMap<const FileEntry *, HeaderContents> HeaderContentMismatches;
468
Yaron Keren45267012015-07-03 09:16:20 +0000469 void add(StringRef Name, enum Entry::EntryKind Kind, Location Loc) {
John Thompson4f8ba652013-03-12 02:07:30 +0000470 // Record this entity in its header.
Yaron Keren45267012015-07-03 09:16:20 +0000471 HeaderEntry HE = {Name.str(), Loc};
John Thompson4f8ba652013-03-12 02:07:30 +0000472 CurHeaderContents[Loc.File].push_back(HE);
John Thompsonf5db45b2013-03-27 01:02:46 +0000473
John Thompson4f8ba652013-03-12 02:07:30 +0000474 // Check whether we've seen this entry before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000475 SmallVector<Entry, 2> &Entries = (*this)[Name];
John Thompson4f8ba652013-03-12 02:07:30 +0000476 for (unsigned I = 0, N = Entries.size(); I != N; ++I) {
477 if (Entries[I].Kind == Kind && Entries[I].Loc == Loc)
478 return;
479 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000480
John Thompson4f8ba652013-03-12 02:07:30 +0000481 // We have not seen this entry before; record it.
482 Entry E = { Kind, Loc };
483 Entries.push_back(E);
484 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000485
John Thompson4f8ba652013-03-12 02:07:30 +0000486 void mergeCurHeaderContents() {
John Thompsonf5db45b2013-03-27 01:02:46 +0000487 for (DenseMap<const FileEntry *, HeaderContents>::iterator
488 H = CurHeaderContents.begin(),
489 HEnd = CurHeaderContents.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000490 H != HEnd; ++H) {
491 // Sort contents.
492 std::sort(H->second.begin(), H->second.end());
493
494 // Check whether we've seen this header before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000495 DenseMap<const FileEntry *, HeaderContents>::iterator KnownH =
496 AllHeaderContents.find(H->first);
John Thompson4f8ba652013-03-12 02:07:30 +0000497 if (KnownH == AllHeaderContents.end()) {
498 // We haven't seen this header before; record its contents.
499 AllHeaderContents.insert(*H);
500 continue;
501 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000502
John Thompson4f8ba652013-03-12 02:07:30 +0000503 // If the header contents are the same, we're done.
504 if (H->second == KnownH->second)
505 continue;
John Thompsonf5db45b2013-03-27 01:02:46 +0000506
John Thompson4f8ba652013-03-12 02:07:30 +0000507 // Determine what changed.
John Thompsonf5db45b2013-03-27 01:02:46 +0000508 std::set_symmetric_difference(
509 H->second.begin(), H->second.end(), KnownH->second.begin(),
510 KnownH->second.end(),
511 std::back_inserter(HeaderContentMismatches[H->first]));
John Thompson4f8ba652013-03-12 02:07:30 +0000512 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000513
John Thompson4f8ba652013-03-12 02:07:30 +0000514 CurHeaderContents.clear();
515 }
John Thompson161381e2013-06-27 18:52:23 +0000516
John Thompson1f67ccb2013-03-12 18:51:47 +0000517private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000518 DenseMap<const FileEntry *, HeaderContents> CurHeaderContents;
519 DenseMap<const FileEntry *, HeaderContents> AllHeaderContents;
John Thompson4f8ba652013-03-12 02:07:30 +0000520};
521
John Thompson161381e2013-06-27 18:52:23 +0000522class CollectEntitiesVisitor
523 : public RecursiveASTVisitor<CollectEntitiesVisitor> {
John Thompson4f8ba652013-03-12 02:07:30 +0000524public:
John Thompson74083922013-09-18 18:19:43 +0000525 CollectEntitiesVisitor(SourceManager &SM, EntityMap &Entities,
526 Preprocessor &PP, PreprocessorTracker &PPTracker,
527 int &HadErrors)
528 : SM(SM), Entities(Entities), PP(PP), PPTracker(PPTracker),
529 HadErrors(HadErrors) {}
John Thompsonf5db45b2013-03-27 01:02:46 +0000530
John Thompson4f8ba652013-03-12 02:07:30 +0000531 bool TraverseStmt(Stmt *S) { return true; }
532 bool TraverseType(QualType T) { return true; }
533 bool TraverseTypeLoc(TypeLoc TL) { return true; }
534 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000535 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
536 return true;
537 }
538 bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo) {
539 return true;
540 }
John Thompson4f8ba652013-03-12 02:07:30 +0000541 bool TraverseTemplateName(TemplateName Template) { return true; }
542 bool TraverseTemplateArgument(const TemplateArgument &Arg) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000543 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
544 return true;
545 }
John Thompson4f8ba652013-03-12 02:07:30 +0000546 bool TraverseTemplateArguments(const TemplateArgument *Args,
John Thompsonf5db45b2013-03-27 01:02:46 +0000547 unsigned NumArgs) {
548 return true;
549 }
John Thompson4f8ba652013-03-12 02:07:30 +0000550 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; }
Benjamin Kramer281f9d02014-05-10 16:32:07 +0000551 bool TraverseLambdaCapture(LambdaCapture C) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000552
John Thompson74083922013-09-18 18:19:43 +0000553 // Check 'extern "*" {}' block for #include directives.
554 bool VisitLinkageSpecDecl(LinkageSpecDecl *D) {
555 // Bail if not a block.
556 if (!D->hasBraces())
557 return true;
558 SourceRange BlockRange = D->getSourceRange();
559 const char *LinkageLabel;
560 switch (D->getLanguage()) {
561 case LinkageSpecDecl::lang_c:
562 LinkageLabel = "extern \"C\" {}";
563 break;
564 case LinkageSpecDecl::lang_cxx:
565 LinkageLabel = "extern \"C++\" {}";
566 break;
John Thompson74083922013-09-18 18:19:43 +0000567 }
568 if (!PPTracker.checkForIncludesInBlock(PP, BlockRange, LinkageLabel,
569 errs()))
570 HadErrors = 1;
571 return true;
572 }
573
574 // Check 'namespace (name) {}' block for #include directives.
575 bool VisitNamespaceDecl(const NamespaceDecl *D) {
576 SourceRange BlockRange = D->getSourceRange();
577 std::string Label("namespace ");
578 Label += D->getName();
579 Label += " {}";
580 if (!PPTracker.checkForIncludesInBlock(PP, BlockRange, Label.c_str(),
581 errs()))
582 HadErrors = 1;
583 return true;
584 }
585
586 // Collect definition entities.
John Thompson4f8ba652013-03-12 02:07:30 +0000587 bool VisitNamedDecl(NamedDecl *ND) {
588 // We only care about file-context variables.
589 if (!ND->getDeclContext()->isFileContext())
590 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000591
John Thompson4f8ba652013-03-12 02:07:30 +0000592 // Skip declarations that tend to be properly multiply-declared.
593 if (isa<NamespaceDecl>(ND) || isa<UsingDirectiveDecl>(ND) ||
John Thompsonf5db45b2013-03-27 01:02:46 +0000594 isa<NamespaceAliasDecl>(ND) ||
595 isa<ClassTemplateSpecializationDecl>(ND) || isa<UsingDecl>(ND) ||
John Thompson8e01c062013-08-26 15:17:23 +0000596 isa<ClassTemplateDecl>(ND) || isa<TemplateTypeParmDecl>(ND) ||
John Thompsoncc2e2912013-09-03 18:44:11 +0000597 isa<TypeAliasTemplateDecl>(ND) || isa<UsingShadowDecl>(ND) ||
598 isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
John Thompson4f8ba652013-03-12 02:07:30 +0000599 (isa<TagDecl>(ND) &&
600 !cast<TagDecl>(ND)->isThisDeclarationADefinition()))
601 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000602
John Thompson8e01c062013-08-26 15:17:23 +0000603 // Skip anonymous declarations.
604 if (!ND->getDeclName())
605 return true;
606
607 // Get the qualified name.
John Thompsoncc2e2912013-09-03 18:44:11 +0000608 std::string Name;
609 llvm::raw_string_ostream OS(Name);
610 ND->printQualifiedName(OS);
611 OS.flush();
John Thompson4f8ba652013-03-12 02:07:30 +0000612 if (Name.empty())
613 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000614
John Thompson4f8ba652013-03-12 02:07:30 +0000615 Location Loc(SM, ND->getLocation());
616 if (!Loc)
617 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000618
John Thompson52d98862013-03-28 18:38:43 +0000619 Entities.add(Name, isa<TagDecl>(ND) ? Entry::EK_Tag : Entry::EK_Value, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000620 return true;
621 }
John Thompson161381e2013-06-27 18:52:23 +0000622
John Thompson1f67ccb2013-03-12 18:51:47 +0000623private:
624 SourceManager &SM;
625 EntityMap &Entities;
John Thompson74083922013-09-18 18:19:43 +0000626 Preprocessor &PP;
627 PreprocessorTracker &PPTracker;
628 int &HadErrors;
John Thompson4f8ba652013-03-12 02:07:30 +0000629};
630
631class CollectEntitiesConsumer : public ASTConsumer {
John Thompson4f8ba652013-03-12 02:07:30 +0000632public:
John Thompson94faa4d2013-07-26 23:56:42 +0000633 CollectEntitiesConsumer(EntityMap &Entities,
634 PreprocessorTracker &preprocessorTracker,
John Thompson74083922013-09-18 18:19:43 +0000635 Preprocessor &PP, StringRef InFile, int &HadErrors)
636 : Entities(Entities), PPTracker(preprocessorTracker), PP(PP),
637 HadErrors(HadErrors) {
John Thompson94faa4d2013-07-26 23:56:42 +0000638 PPTracker.handlePreprocessorEntry(PP, InFile);
639 }
640
Alexander Kornienko87638f62015-04-11 07:59:33 +0000641 ~CollectEntitiesConsumer() override { PPTracker.handlePreprocessorExit(); }
John Thompsonf5db45b2013-03-27 01:02:46 +0000642
Alexander Kornienko87638f62015-04-11 07:59:33 +0000643 void HandleTranslationUnit(ASTContext &Ctx) override {
John Thompson4f8ba652013-03-12 02:07:30 +0000644 SourceManager &SM = Ctx.getSourceManager();
John Thompsonf5db45b2013-03-27 01:02:46 +0000645
John Thompson4f8ba652013-03-12 02:07:30 +0000646 // Collect declared entities.
John Thompson74083922013-09-18 18:19:43 +0000647 CollectEntitiesVisitor(SM, Entities, PP, PPTracker, HadErrors)
John Thompsonf5db45b2013-03-27 01:02:46 +0000648 .TraverseDecl(Ctx.getTranslationUnitDecl());
649
John Thompson4f8ba652013-03-12 02:07:30 +0000650 // Collect macro definitions.
651 for (Preprocessor::macro_iterator M = PP.macro_begin(),
John Thompsonf5db45b2013-03-27 01:02:46 +0000652 MEnd = PP.macro_end();
John Thompson4f8ba652013-03-12 02:07:30 +0000653 M != MEnd; ++M) {
Richard Smith76e66602015-04-23 20:38:48 +0000654 Location Loc(SM, M->second.getLatest()->getLocation());
John Thompson4f8ba652013-03-12 02:07:30 +0000655 if (!Loc)
656 continue;
657
John Thompson52d98862013-03-28 18:38:43 +0000658 Entities.add(M->first->getName().str(), Entry::EK_Macro, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000659 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000660
John Thompson4f8ba652013-03-12 02:07:30 +0000661 // Merge header contents.
662 Entities.mergeCurHeaderContents();
663 }
John Thompson161381e2013-06-27 18:52:23 +0000664
John Thompson1f67ccb2013-03-12 18:51:47 +0000665private:
666 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000667 PreprocessorTracker &PPTracker;
John Thompson1f67ccb2013-03-12 18:51:47 +0000668 Preprocessor &PP;
John Thompson74083922013-09-18 18:19:43 +0000669 int &HadErrors;
John Thompson4f8ba652013-03-12 02:07:30 +0000670};
671
672class CollectEntitiesAction : public SyntaxOnlyAction {
John Thompson1f67ccb2013-03-12 18:51:47 +0000673public:
John Thompson94faa4d2013-07-26 23:56:42 +0000674 CollectEntitiesAction(EntityMap &Entities,
John Thompson74083922013-09-18 18:19:43 +0000675 PreprocessorTracker &preprocessorTracker,
676 int &HadErrors)
677 : Entities(Entities), PPTracker(preprocessorTracker),
678 HadErrors(HadErrors) {}
John Thompson161381e2013-06-27 18:52:23 +0000679
John Thompson4f8ba652013-03-12 02:07:30 +0000680protected:
David Blaikie680c4c82014-08-10 19:56:59 +0000681 std::unique_ptr<clang::ASTConsumer>
682 CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override {
683 return llvm::make_unique<CollectEntitiesConsumer>(
684 Entities, PPTracker, CI.getPreprocessor(), InFile, HadErrors);
John Thompson4f8ba652013-03-12 02:07:30 +0000685 }
John Thompson161381e2013-06-27 18:52:23 +0000686
John Thompson1f67ccb2013-03-12 18:51:47 +0000687private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000688 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000689 PreprocessorTracker &PPTracker;
John Thompson74083922013-09-18 18:19:43 +0000690 int &HadErrors;
John Thompson4f8ba652013-03-12 02:07:30 +0000691};
692
693class ModularizeFrontendActionFactory : public FrontendActionFactory {
John Thompson4f8ba652013-03-12 02:07:30 +0000694public:
John Thompson94faa4d2013-07-26 23:56:42 +0000695 ModularizeFrontendActionFactory(EntityMap &Entities,
John Thompson74083922013-09-18 18:19:43 +0000696 PreprocessorTracker &preprocessorTracker,
697 int &HadErrors)
698 : Entities(Entities), PPTracker(preprocessorTracker),
699 HadErrors(HadErrors) {}
John Thompson4f8ba652013-03-12 02:07:30 +0000700
Alexander Kornienko87638f62015-04-11 07:59:33 +0000701 CollectEntitiesAction *create() override {
John Thompson74083922013-09-18 18:19:43 +0000702 return new CollectEntitiesAction(Entities, PPTracker, HadErrors);
John Thompson4f8ba652013-03-12 02:07:30 +0000703 }
John Thompson161381e2013-06-27 18:52:23 +0000704
John Thompson1f67ccb2013-03-12 18:51:47 +0000705private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000706 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000707 PreprocessorTracker &PPTracker;
John Thompson74083922013-09-18 18:19:43 +0000708 int &HadErrors;
John Thompson4f8ba652013-03-12 02:07:30 +0000709};
710
John Thompsonbb0a3b02013-08-09 13:52:09 +0000711int main(int Argc, const char **Argv) {
John Thompsona2de1082013-03-26 01:17:48 +0000712
John Thompson5ab4f112013-10-15 13:52:33 +0000713 // Save program name for error messages.
714 Argv0 = Argv[0];
715
John Thompson5d9862f2015-02-10 14:45:30 +0000716 // Save program arguments for use in module.modulemap comment.
John Thompson5ab4f112013-10-15 13:52:33 +0000717 CommandLine = sys::path::stem(sys::path::filename(Argv0));
718 for (int ArgIndex = 1; ArgIndex < Argc; ArgIndex++) {
719 CommandLine.append(" ");
720 CommandLine.append(Argv[ArgIndex]);
721 }
722
John Thompsona2de1082013-03-26 01:17:48 +0000723 // This causes options to be parsed.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000724 cl::ParseCommandLineOptions(Argc, Argv, "modularize.\n");
John Thompsona2de1082013-03-26 01:17:48 +0000725
726 // No go if we have no header list file.
John Thompson469bbc02015-02-12 16:22:09 +0000727 if (ListFileNames.size() == 0) {
John Thompsona2de1082013-03-26 01:17:48 +0000728 cl::PrintHelpMessage();
John Thompsonea6c8db2013-03-27 21:23:21 +0000729 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000730 }
John Thompsona2de1082013-03-26 01:17:48 +0000731
John Thompsond845bae2015-02-13 14:29:22 +0000732 std::unique_ptr<ModularizeUtilities> ModUtil;
John Thompson8eb8d932015-02-19 16:47:27 +0000733 int HadErrors = 0;
734
John Thompsond845bae2015-02-13 14:29:22 +0000735 ModUtil.reset(
736 ModularizeUtilities::createModularizeUtilities(
737 ListFileNames, HeaderPrefix));
738
John Thompson7d0213c2013-09-04 20:46:24 +0000739 // Get header file names and dependencies.
John Thompson96f55512015-06-04 23:35:19 +0000740 if (ModUtil->loadAllHeaderListsAndDependencies())
741 HadErrors = 1;
John Thompsona2de1082013-03-26 01:17:48 +0000742
John Thompson5ab4f112013-10-15 13:52:33 +0000743 // If we are in assistant mode, output the module map and quit.
John Thompsone744d2b2013-12-10 02:26:44 +0000744 if (ModuleMapPath.length() != 0) {
John Thompsond845bae2015-02-13 14:29:22 +0000745 if (!createModuleMap(ModuleMapPath, ModUtil->HeaderFileNames,
746 ModUtil->Dependencies, HeaderPrefix, RootModule))
John Thompson5ab4f112013-10-15 13:52:33 +0000747 return 1; // Failed.
748 return 0; // Success - Skip checks in assistant mode.
749 }
750
John Thompson8eb8d932015-02-19 16:47:27 +0000751 // If we're doing module maps.
752 if (!NoCoverageCheck && ModUtil->HasModuleMap) {
753 // Do coverage check.
754 if (ModUtil->doCoverageCheck(IncludePaths, CommandLine))
755 HadErrors = 1;
756 }
757
758 // Bail early if only doing the coverage check.
759 if (CoverageCheckOnly)
760 return HadErrors;
761
John Thompson4f8ba652013-03-12 02:07:30 +0000762 // Create the compilation database.
John Thompsona2de1082013-03-26 01:17:48 +0000763 SmallString<256> PathBuf;
John Thompsonf5db45b2013-03-27 01:02:46 +0000764 sys::fs::current_path(PathBuf);
Ahmed Charles6a2dc5c2014-03-09 09:24:40 +0000765 std::unique_ptr<CompilationDatabase> Compilations;
John Thompsonf5db45b2013-03-27 01:02:46 +0000766 Compilations.reset(
767 new FixedCompilationDatabase(Twine(PathBuf), CC1Arguments));
John Thompsona2de1082013-03-26 01:17:48 +0000768
John Thompson94faa4d2013-07-26 23:56:42 +0000769 // Create preprocessor tracker, to watch for macro and conditional problems.
John Thompsonecd3b042015-02-11 16:58:36 +0000770 std::unique_ptr<PreprocessorTracker> PPTracker(
John Thompsond845bae2015-02-13 14:29:22 +0000771 PreprocessorTracker::create(ModUtil->HeaderFileNames,
772 BlockCheckHeaderListOnly));
John Thompson94faa4d2013-07-26 23:56:42 +0000773
John Thompson4f8ba652013-03-12 02:07:30 +0000774 // Parse all of the headers, detecting duplicates.
775 EntityMap Entities;
John Thompsond845bae2015-02-13 14:29:22 +0000776 ClangTool Tool(*Compilations, ModUtil->HeaderFileNames);
John Thompsoncf777e92015-06-04 01:10:19 +0000777 Tool.appendArgumentsAdjuster(
778 getModularizeArgumentsAdjuster(ModUtil->Dependencies));
Benjamin Kramer6e914242014-07-24 10:23:33 +0000779 ModularizeFrontendActionFactory Factory(Entities, *PPTracker, HadErrors);
780 HadErrors |= Tool.run(&Factory);
John Thompsonce601e22013-03-14 01:41:29 +0000781
John Thompson4e4d9b32013-03-28 01:20:19 +0000782 // Create a place to save duplicate entity locations, separate bins per kind.
783 typedef SmallVector<Location, 8> LocationArray;
John Thompson52d98862013-03-28 18:38:43 +0000784 typedef SmallVector<LocationArray, Entry::EK_NumberOfKinds> EntryBinArray;
John Thompson4e4d9b32013-03-28 01:20:19 +0000785 EntryBinArray EntryBins;
John Thompsonbb0a3b02013-08-09 13:52:09 +0000786 int KindIndex;
787 for (KindIndex = 0; KindIndex < Entry::EK_NumberOfKinds; ++KindIndex) {
788 LocationArray Array;
789 EntryBins.push_back(Array);
Michael Gottesman4b249212013-03-28 06:07:15 +0000790 }
John Thompson4e4d9b32013-03-28 01:20:19 +0000791
John Thompson4f8ba652013-03-12 02:07:30 +0000792 // Check for the same entity being defined in multiple places.
793 for (EntityMap::iterator E = Entities.begin(), EEnd = Entities.end();
794 E != EEnd; ++E) {
Alp Toker9a5134e2013-12-01 05:08:12 +0000795 // If only one occurrence, exit early.
John Thompson4e4d9b32013-03-28 01:20:19 +0000796 if (E->second.size() == 1)
797 continue;
798 // Clear entity locations.
799 for (EntryBinArray::iterator CI = EntryBins.begin(), CE = EntryBins.end();
800 CI != CE; ++CI) {
John Thompson52d98862013-03-28 18:38:43 +0000801 CI->clear();
John Thompson4e4d9b32013-03-28 01:20:19 +0000802 }
803 // Walk the entities of a single name, collecting the locations,
804 // separated into separate bins.
John Thompson4f8ba652013-03-12 02:07:30 +0000805 for (unsigned I = 0, N = E->second.size(); I != N; ++I) {
John Thompson52d98862013-03-28 18:38:43 +0000806 EntryBins[E->second[I].Kind].push_back(E->second[I].Loc);
John Thompson4e4d9b32013-03-28 01:20:19 +0000807 }
808 // Report any duplicate entity definition errors.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000809 int KindIndex = 0;
John Thompson4e4d9b32013-03-28 01:20:19 +0000810 for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end();
John Thompsonbb0a3b02013-08-09 13:52:09 +0000811 DI != DE; ++DI, ++KindIndex) {
812 int ECount = DI->size();
John Thompson8eb8d932015-02-19 16:47:27 +0000813 // If only 1 occurrence of this entity, skip it, we only report duplicates.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000814 if (ECount <= 1)
John Thompson4f8ba652013-03-12 02:07:30 +0000815 continue;
John Thompson52d98862013-03-28 18:38:43 +0000816 LocationArray::iterator FI = DI->begin();
John Thompsonbb0a3b02013-08-09 13:52:09 +0000817 StringRef kindName = Entry::getKindName((Entry::EntryKind)KindIndex);
John Thompson4e4d9b32013-03-28 01:20:19 +0000818 errs() << "error: " << kindName << " '" << E->first()
819 << "' defined at multiple locations:\n";
John Thompson52d98862013-03-28 18:38:43 +0000820 for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000821 errs() << " " << FI->File->getName() << ":" << FI->Line << ":"
822 << FI->Column << "\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000823 }
John Thompson4f8ba652013-03-12 02:07:30 +0000824 HadErrors = 1;
825 }
826 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000827
John Thompson94faa4d2013-07-26 23:56:42 +0000828 // Complain about macro instance in header files that differ based on how
829 // they are included.
830 if (PPTracker->reportInconsistentMacros(errs()))
831 HadErrors = 1;
832
833 // Complain about preprocessor conditional directives in header files that
834 // differ based on how they are included.
835 if (PPTracker->reportInconsistentConditionals(errs()))
836 HadErrors = 1;
837
John Thompson4f8ba652013-03-12 02:07:30 +0000838 // Complain about any headers that have contents that differ based on how
839 // they are included.
John Thompsonce601e22013-03-14 01:41:29 +0000840 // FIXME: Could we provide information about which preprocessor conditionals
841 // are involved?
John Thompsonf5db45b2013-03-27 01:02:46 +0000842 for (DenseMap<const FileEntry *, HeaderContents>::iterator
843 H = Entities.HeaderContentMismatches.begin(),
844 HEnd = Entities.HeaderContentMismatches.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000845 H != HEnd; ++H) {
846 if (H->second.empty()) {
John Thompsonf5db45b2013-03-27 01:02:46 +0000847 errs() << "internal error: phantom header content mismatch\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000848 continue;
849 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000850
John Thompson4f8ba652013-03-12 02:07:30 +0000851 HadErrors = 1;
John Thompsonf5db45b2013-03-27 01:02:46 +0000852 errs() << "error: header '" << H->first->getName()
John Thompson94faa4d2013-07-26 23:56:42 +0000853 << "' has different contents depending on how it was included.\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000854 for (unsigned I = 0, N = H->second.size(); I != N; ++I) {
John Thompson161381e2013-06-27 18:52:23 +0000855 errs() << "note: '" << H->second[I].Name << "' in "
856 << H->second[I].Loc.File->getName() << " at "
857 << H->second[I].Loc.Line << ":" << H->second[I].Loc.Column
858 << " not always provided\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000859 }
860 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000861
John Thompson4f8ba652013-03-12 02:07:30 +0000862 return HadErrors;
863}