blob: 49b2de045b1ad3cee1439a71012c19aeece3f458 [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//
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
John Thompsonf5db45b2013-03-27 01:02:46 +000015// headers to behave poorly, and should be fixed before introducing a module
John Thompson4f8ba652013-03-12 02:07:30 +000016// 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.
John Thompsonf5db45b2013-03-27 01:02:46 +000020// Lines beginning with '#' and empty lines are ignored.
John Thompson7d0213c2013-09-04 20:46:24 +000021// 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//
John Thompson4f8ba652013-03-12 02:07:30 +000026// Modularize also accepts regular front-end arguments.
27//
John Thompsonf5db45b2013-03-27 01:02:46 +000028// Usage: modularize [-prefix (optional header path prefix)]
John Thompsona2de1082013-03-26 01:17:48 +000029// (include-files_list) [(front-end-options) ...]
30//
John Thompsona44f85a2013-04-15 22:32:28 +000031// Note that unless a "-prefix (header path)" option is specified,
John Thompsona2de1082013-03-26 01:17:48 +000032// 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.
John Thompson4f8ba652013-03-12 02:07:30 +000035//
John Thompsonfd8ca382013-03-27 19:31:22 +000036// 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,
John Thompsonea6c8db2013-03-27 21:23:21 +000038// you should append the following to your command lines: -x c++
John Thompsonfd8ca382013-03-27 19:31:22 +000039//
John Thompson4f8ba652013-03-12 02:07:30 +000040// Modularize will do normal parsing, reporting normal errors and warnings,
41// but will also report special error messages like the following:
42//
John Thompson7c6e79f32013-07-29 19:07:00 +000043// error: '(symbol)' defined at multiple locations:
44// (file):(row):(column)
45// (file):(row):(column)
John Thompson4f8ba652013-03-12 02:07:30 +000046//
John Thompsondc118272013-07-29 21:59:41 +000047// error: header '(file)' has different contents depending on how it was
John Thompson7c6e79f32013-07-29 19:07:00 +000048// included
John Thompson4f8ba652013-03-12 02:07:30 +000049//
50// The latter might be followed by messages like the following:
51//
John Thompson7c6e79f32013-07-29 19:07:00 +000052// note: '(symbol)' in (file) at (row):(column) not always provided
John Thompson4f8ba652013-03-12 02:07:30 +000053//
John Thompson7c6e79f32013-07-29 19:07:00 +000054// 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//
Nico Weber8e20be22013-08-12 11:43:36 +000058// (...)/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//
John Thompson74083922013-09-18 18:19:43 +000078// 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//
John Thompson4fa9c2c2013-08-09 00:19:03 +000091// See PreprocessorTracker.cpp for additional details.
John Thompsoncc2e2912013-09-03 18:44:11 +000092//
John Thompson5d9862f2015-02-10 14:45:30 +000093// 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,
John Thompson5ab4f112013-10-15 13:52:33 +000095// generating a module map file based on the header list. An optional
96// "-root-module=(rootName)" argument can specify a root module to be
John Thompson5d9862f2015-02-10 14:45:30 +000097// created in the generated module.modulemap file. Note that you will likely
John Thompson5ab4f112013-10-15 13:52:33 +000098// need to edit this file to suit the needs of your headers.
99//
John Thompson5d9862f2015-02-10 14:45:30 +0000100// An example command line for generating a module.modulemap file:
John Thompson5ab4f112013-10-15 13:52:33 +0000101//
John Thompson5d9862f2015-02-10 14:45:30 +0000102// modularize -module-map-path=module.modulemap -root-module=myroot \
103// headerlist.txt
John Thompson5ab4f112013-10-15 13:52:33 +0000104//
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//
John Thompson74751802013-09-03 18:48:43 +0000113// 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//
John Thompson74083922013-09-18 18:19:43 +0000120// 1. Omit duplicate "not always provided" messages
John Thompson53a9d2d2013-09-04 18:29:36 +0000121//
John Thompson74083922013-09-18 18:19:43 +0000122// 2. Add options to disable any of the checks, in case
John Thompson74751802013-09-03 18:48:43 +0000123// there is some problem with them, or the messages get too verbose.
124//
John Thompson74083922013-09-18 18:19:43 +0000125// 3. Try to figure out the preprocessor conditional directives that
John Thompson74751802013-09-03 18:48:43 +0000126// contribute to problems and tie them to the inconsistent definitions.
127//
John Thompson74083922013-09-18 18:19:43 +0000128// 4. There are some legitimate uses of preprocessor macros that
Bob Wilsonf5999bd2013-09-04 16:48:28 +0000129// 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//
John Thompson74083922013-09-18 18:19:43 +0000136// 5. What else?
John Thompsonce601e22013-03-14 01:41:29 +0000137//
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//
John Thompson4f8ba652013-03-12 02:07:30 +0000144//===----------------------------------------------------------------------===//
John Thompsonf5db45b2013-03-27 01:02:46 +0000145
Chandler Carruth85e6e872014-01-07 20:05:01 +0000146#include "Modularize.h"
147#include "PreprocessorTracker.h"
Chandler Carruthf7e45c02014-01-07 22:15:39 +0000148#include "clang/AST/ASTConsumer.h"
John Thompsond977c1e2013-03-27 18:34:38 +0000149#include "clang/AST/ASTContext.h"
150#include "clang/AST/RecursiveASTVisitor.h"
151#include "clang/Basic/SourceManager.h"
John Thompson7d0213c2013-09-04 20:46:24 +0000152#include "clang/Driver/Options.h"
John Thompsond977c1e2013-03-27 18:34:38 +0000153#include "clang/Frontend/CompilerInstance.h"
154#include "clang/Frontend/FrontendActions.h"
155#include "clang/Lex/Preprocessor.h"
156#include "clang/Tooling/CompilationDatabase.h"
157#include "clang/Tooling/Tooling.h"
John Thompson7d0213c2013-09-04 20:46:24 +0000158#include "llvm/Option/Arg.h"
159#include "llvm/Option/ArgList.h"
160#include "llvm/Option/OptTable.h"
161#include "llvm/Option/Option.h"
John Thompsona2de1082013-03-26 01:17:48 +0000162#include "llvm/Support/CommandLine.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000163#include "llvm/Support/FileSystem.h"
John Thompsonf5db45b2013-03-27 01:02:46 +0000164#include "llvm/Support/MemoryBuffer.h"
John Thompsona2de1082013-03-26 01:17:48 +0000165#include "llvm/Support/Path.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000166#include <algorithm>
John Thompsond977c1e2013-03-27 18:34:38 +0000167#include <fstream>
John Thompson4f8ba652013-03-12 02:07:30 +0000168#include <iterator>
John Thompsond977c1e2013-03-27 18:34:38 +0000169#include <string>
170#include <vector>
John Thompson4f8ba652013-03-12 02:07:30 +0000171
Bob Wilsonf5999bd2013-09-04 16:48:28 +0000172using namespace clang;
John Thompson7d0213c2013-09-04 20:46:24 +0000173using namespace clang::driver;
174using namespace clang::driver::options;
175using namespace clang::tooling;
John Thompsona2de1082013-03-26 01:17:48 +0000176using namespace llvm;
John Thompson7d0213c2013-09-04 20:46:24 +0000177using namespace llvm::opt;
John Thompson94faa4d2013-07-26 23:56:42 +0000178using namespace Modularize;
John Thompson4f8ba652013-03-12 02:07:30 +0000179
John Thompsonea6c8db2013-03-27 21:23:21 +0000180// Option to specify a file name for a list of header files to check.
John Thompsonb809dfc2013-07-19 14:19:31 +0000181cl::opt<std::string>
182ListFileName(cl::Positional,
183 cl::desc("<name of file containing list of headers to check>"));
John Thompsonea6c8db2013-03-27 21:23:21 +0000184
185// Collect all other arguments, which will be passed to the front end.
John Thompson161381e2013-06-27 18:52:23 +0000186cl::list<std::string>
John Thompsonb809dfc2013-07-19 14:19:31 +0000187CC1Arguments(cl::ConsumeAfter,
188 cl::desc("<arguments to be passed to front end>..."));
John Thompsonea6c8db2013-03-27 21:23:21 +0000189
190// Option to specify a prefix to be prepended to the header names.
191cl::opt<std::string> HeaderPrefix(
192 "prefix", cl::init(""),
193 cl::desc(
194 "Prepend header file paths with this prefix."
195 " If not specified,"
196 " the files are considered to be relative to the header list file."));
197
John Thompson5ab4f112013-10-15 13:52:33 +0000198// Option for assistant mode, telling modularize to output a module map
199// based on the headers list, and where to put it.
200cl::opt<std::string> ModuleMapPath(
201 "module-map-path", cl::init(""),
202 cl::desc("Turn on module map output and specify output path or file name."
203 " If no path is specified and if prefix option is specified,"
204 " use prefix for file path."));
205
206// Option for assistant mode, telling modularize to output a module map
207// based on the headers list, and where to put it.
208cl::opt<std::string>
209RootModule("root-module", cl::init(""),
210 cl::desc("Specify the name of the root module."));
211
212// Save the program name for error messages.
213const char *Argv0;
214// Save the command line for comments.
215std::string CommandLine;
Bob Wilsonf5999bd2013-09-04 16:48:28 +0000216
John Thompson7d0213c2013-09-04 20:46:24 +0000217// Read the header list file and collect the header file names and
218// optional dependencies.
Rafael Espindolac7f0d232014-06-12 22:08:48 +0000219std::error_code
220getHeaderFileNames(SmallVectorImpl<std::string> &HeaderFileNames,
221 DependencyMap &Dependencies, StringRef ListFileName,
222 StringRef HeaderPrefix) {
John Thompsonea6c8db2013-03-27 21:23:21 +0000223 // By default, use the path component of the list file name.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000224 SmallString<256> HeaderDirectory(ListFileName);
225 sys::path::remove_filename(HeaderDirectory);
John Thompson7d0213c2013-09-04 20:46:24 +0000226 SmallString<256> CurrentDirectory;
227 sys::fs::current_path(CurrentDirectory);
John Thompsonea6c8db2013-03-27 21:23:21 +0000228
229 // Get the prefix if we have one.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000230 if (HeaderPrefix.size() != 0)
231 HeaderDirectory = HeaderPrefix;
John Thompsonea6c8db2013-03-27 21:23:21 +0000232
233 // Read the header list file into a buffer.
Rafael Espindola43f0aa62014-07-06 17:43:19 +0000234 ErrorOr<std::unique_ptr<MemoryBuffer>> listBuffer =
235 MemoryBuffer::getFile(ListFileName);
236 if (std::error_code EC = listBuffer.getError())
237 return EC;
John Thompsonea6c8db2013-03-27 21:23:21 +0000238
239 // Parse the header list into strings.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000240 SmallVector<StringRef, 32> Strings;
Rafael Espindola43f0aa62014-07-06 17:43:19 +0000241 listBuffer.get()->getBuffer().split(Strings, "\n", -1, false);
John Thompsonea6c8db2013-03-27 21:23:21 +0000242
243 // Collect the header file names from the string list.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000244 for (SmallVectorImpl<StringRef>::iterator I = Strings.begin(),
245 E = Strings.end();
John Thompsonea6c8db2013-03-27 21:23:21 +0000246 I != E; ++I) {
John Thompson7d0213c2013-09-04 20:46:24 +0000247 StringRef Line = I->trim();
John Thompsonea6c8db2013-03-27 21:23:21 +0000248 // Ignore comments and empty lines.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000249 if (Line.empty() || (Line[0] == '#'))
John Thompsonea6c8db2013-03-27 21:23:21 +0000250 continue;
John Thompson7d0213c2013-09-04 20:46:24 +0000251 std::pair<StringRef, StringRef> TargetAndDependents = Line.split(':');
John Thompsonbb0a3b02013-08-09 13:52:09 +0000252 SmallString<256> HeaderFileName;
John Thompsonea6c8db2013-03-27 21:23:21 +0000253 // Prepend header file name prefix if it's not absolute.
John Thompson7d0213c2013-09-04 20:46:24 +0000254 if (sys::path::is_absolute(TargetAndDependents.first))
255 llvm::sys::path::native(TargetAndDependents.first, HeaderFileName);
John Thompsonea6c8db2013-03-27 21:23:21 +0000256 else {
John Thompson7d0213c2013-09-04 20:46:24 +0000257 if (HeaderDirectory.size() != 0)
258 HeaderFileName = HeaderDirectory;
259 else
260 HeaderFileName = CurrentDirectory;
261 sys::path::append(HeaderFileName, TargetAndDependents.first);
Benjamin Kramer3353a102013-09-11 10:45:25 +0000262 sys::path::native(HeaderFileName);
John Thompsonea6c8db2013-03-27 21:23:21 +0000263 }
John Thompson7d0213c2013-09-04 20:46:24 +0000264 // Handle optional dependencies.
265 DependentsVector Dependents;
266 SmallVector<StringRef, 4> DependentsList;
267 TargetAndDependents.second.split(DependentsList, " ", -1, false);
268 int Count = DependentsList.size();
269 for (int Index = 0; Index < Count; ++Index) {
270 SmallString<256> Dependent;
271 if (sys::path::is_absolute(DependentsList[Index]))
272 Dependent = DependentsList[Index];
273 else {
274 if (HeaderDirectory.size() != 0)
275 Dependent = HeaderDirectory;
276 else
277 Dependent = CurrentDirectory;
278 sys::path::append(Dependent, DependentsList[Index]);
279 }
Benjamin Kramer3353a102013-09-11 10:45:25 +0000280 sys::path::native(Dependent);
John Thompson7d0213c2013-09-04 20:46:24 +0000281 Dependents.push_back(Dependent.str());
282 }
283 // Save the resulting header file path and dependencies.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000284 HeaderFileNames.push_back(HeaderFileName.str());
John Thompson7d0213c2013-09-04 20:46:24 +0000285 Dependencies[HeaderFileName.str()] = Dependents;
John Thompsonea6c8db2013-03-27 21:23:21 +0000286 }
287
Rafael Espindolac7f0d232014-06-12 22:08:48 +0000288 return std::error_code();
John Thompsonea6c8db2013-03-27 21:23:21 +0000289}
290
John Thompson7d0213c2013-09-04 20:46:24 +0000291// Helper function for finding the input file in an arguments list.
292std::string findInputFile(const CommandLineArguments &CLArgs) {
Ahmed Charles6a2dc5c2014-03-09 09:24:40 +0000293 std::unique_ptr<OptTable> Opts(createDriverOptTable());
John Thompson7d0213c2013-09-04 20:46:24 +0000294 const unsigned IncludedFlagsBitmask = options::CC1Option;
295 unsigned MissingArgIndex, MissingArgCount;
296 SmallVector<const char *, 256> Argv;
297 for (CommandLineArguments::const_iterator I = CLArgs.begin(),
298 E = CLArgs.end();
299 I != E; ++I)
300 Argv.push_back(I->c_str());
Ahmed Charles6a2dc5c2014-03-09 09:24:40 +0000301 std::unique_ptr<InputArgList> Args(
John Thompson7d0213c2013-09-04 20:46:24 +0000302 Opts->ParseArgs(Argv.data(), Argv.data() + Argv.size(), MissingArgIndex,
303 MissingArgCount, IncludedFlagsBitmask));
304 std::vector<std::string> Inputs = Args->getAllArgValues(OPT_INPUT);
305 return Inputs.back();
306}
307
Alexander Kornienkod3657312014-12-03 17:53:03 +0000308// This arguments adjuster inserts "-include (file)" arguments for header
John Thompson7d0213c2013-09-04 20:46:24 +0000309// dependencies.
Alexander Kornienkod3657312014-12-03 17:53:03 +0000310ArgumentsAdjuster getAddDependenciesAdjuster(DependencyMap &Dependencies) {
311 return [&Dependencies](const CommandLineArguments &Args) {
John Thompson7d0213c2013-09-04 20:46:24 +0000312 std::string InputFile = findInputFile(Args);
313 DependentsVector &FileDependents = Dependencies[InputFile];
John Thompson7d0213c2013-09-04 20:46:24 +0000314 CommandLineArguments NewArgs(Args);
Alexander Kornienkod3657312014-12-03 17:53:03 +0000315 if (int Count = FileDependents.size()) {
316 for (int Index = 0; Index < Count; ++Index) {
317 NewArgs.push_back("-include");
318 std::string File(std::string("\"") + FileDependents[Index] +
319 std::string("\""));
320 NewArgs.push_back(FileDependents[Index]);
321 }
John Thompson7d0213c2013-09-04 20:46:24 +0000322 }
323 return NewArgs;
Alexander Kornienkod3657312014-12-03 17:53:03 +0000324 };
325}
John Thompson7d0213c2013-09-04 20:46:24 +0000326
John Thompsonce601e22013-03-14 01:41:29 +0000327// FIXME: The Location class seems to be something that we might
328// want to design to be applicable to a wider range of tools, and stick it
329// somewhere into Tooling/ in mainline
John Thompson4f8ba652013-03-12 02:07:30 +0000330struct Location {
331 const FileEntry *File;
332 unsigned Line, Column;
John Thompsonf5db45b2013-03-27 01:02:46 +0000333
334 Location() : File(), Line(), Column() {}
335
John Thompson4f8ba652013-03-12 02:07:30 +0000336 Location(SourceManager &SM, SourceLocation Loc) : File(), Line(), Column() {
337 Loc = SM.getExpansionLoc(Loc);
338 if (Loc.isInvalid())
339 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000340
John Thompson4f8ba652013-03-12 02:07:30 +0000341 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(Loc);
342 File = SM.getFileEntryForID(Decomposed.first);
343 if (!File)
344 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000345
John Thompson4f8ba652013-03-12 02:07:30 +0000346 Line = SM.getLineNumber(Decomposed.first, Decomposed.second);
347 Column = SM.getColumnNumber(Decomposed.first, Decomposed.second);
348 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000349
Craig Topperf61be9c2014-06-09 02:03:06 +0000350 operator bool() const { return File != nullptr; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000351
John Thompson4f8ba652013-03-12 02:07:30 +0000352 friend bool operator==(const Location &X, const Location &Y) {
353 return X.File == Y.File && X.Line == Y.Line && X.Column == Y.Column;
354 }
355
356 friend bool operator!=(const Location &X, const Location &Y) {
357 return !(X == Y);
358 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000359
John Thompson4f8ba652013-03-12 02:07:30 +0000360 friend bool operator<(const Location &X, const Location &Y) {
361 if (X.File != Y.File)
362 return X.File < Y.File;
363 if (X.Line != Y.Line)
364 return X.Line < Y.Line;
365 return X.Column < Y.Column;
366 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000367 friend bool operator>(const Location &X, const Location &Y) { return Y < X; }
John Thompson4f8ba652013-03-12 02:07:30 +0000368 friend bool operator<=(const Location &X, const Location &Y) {
369 return !(Y < X);
370 }
371 friend bool operator>=(const Location &X, const Location &Y) {
372 return !(X < Y);
373 }
John Thompson4f8ba652013-03-12 02:07:30 +0000374};
375
John Thompson4f8ba652013-03-12 02:07:30 +0000376struct Entry {
John Thompson52d98862013-03-28 18:38:43 +0000377 enum EntryKind {
378 EK_Tag,
379 EK_Value,
380 EK_Macro,
381
382 EK_NumberOfKinds
John Thompson4f8ba652013-03-12 02:07:30 +0000383 } Kind;
John Thompsonf5db45b2013-03-27 01:02:46 +0000384
John Thompson4f8ba652013-03-12 02:07:30 +0000385 Location Loc;
John Thompson4e4d9b32013-03-28 01:20:19 +0000386
387 StringRef getKindName() { return getKindName(Kind); }
John Thompson52d98862013-03-28 18:38:43 +0000388 static StringRef getKindName(EntryKind kind);
John Thompson4f8ba652013-03-12 02:07:30 +0000389};
390
John Thompson4e4d9b32013-03-28 01:20:19 +0000391// Return a string representing the given kind.
John Thompson52d98862013-03-28 18:38:43 +0000392StringRef Entry::getKindName(Entry::EntryKind kind) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000393 switch (kind) {
John Thompson52d98862013-03-28 18:38:43 +0000394 case EK_Tag:
John Thompson4e4d9b32013-03-28 01:20:19 +0000395 return "tag";
John Thompson52d98862013-03-28 18:38:43 +0000396 case EK_Value:
John Thompson4e4d9b32013-03-28 01:20:19 +0000397 return "value";
John Thompson52d98862013-03-28 18:38:43 +0000398 case EK_Macro:
John Thompson4e4d9b32013-03-28 01:20:19 +0000399 return "macro";
John Thompson52d98862013-03-28 18:38:43 +0000400 case EK_NumberOfKinds:
John Thompson4e4d9b32013-03-28 01:20:19 +0000401 break;
John Thompson4e4d9b32013-03-28 01:20:19 +0000402 }
David Blaikiec66c07d2013-03-28 02:30:37 +0000403 llvm_unreachable("invalid Entry kind");
John Thompson4e4d9b32013-03-28 01:20:19 +0000404}
405
John Thompson4f8ba652013-03-12 02:07:30 +0000406struct HeaderEntry {
407 std::string Name;
408 Location Loc;
John Thompsonf5db45b2013-03-27 01:02:46 +0000409
John Thompson4f8ba652013-03-12 02:07:30 +0000410 friend bool operator==(const HeaderEntry &X, const HeaderEntry &Y) {
411 return X.Loc == Y.Loc && X.Name == Y.Name;
412 }
413 friend bool operator!=(const HeaderEntry &X, const HeaderEntry &Y) {
414 return !(X == Y);
415 }
416 friend bool operator<(const HeaderEntry &X, const HeaderEntry &Y) {
417 return X.Loc < Y.Loc || (X.Loc == Y.Loc && X.Name < Y.Name);
418 }
419 friend bool operator>(const HeaderEntry &X, const HeaderEntry &Y) {
420 return Y < X;
421 }
422 friend bool operator<=(const HeaderEntry &X, const HeaderEntry &Y) {
423 return !(Y < X);
424 }
425 friend bool operator>=(const HeaderEntry &X, const HeaderEntry &Y) {
426 return !(X < Y);
427 }
428};
429
430typedef std::vector<HeaderEntry> HeaderContents;
431
John Thompsonf5db45b2013-03-27 01:02:46 +0000432class EntityMap : public StringMap<SmallVector<Entry, 2> > {
John Thompson4f8ba652013-03-12 02:07:30 +0000433public:
John Thompsonf5db45b2013-03-27 01:02:46 +0000434 DenseMap<const FileEntry *, HeaderContents> HeaderContentMismatches;
435
John Thompson52d98862013-03-28 18:38:43 +0000436 void add(const std::string &Name, enum Entry::EntryKind Kind, Location Loc) {
John Thompson4f8ba652013-03-12 02:07:30 +0000437 // Record this entity in its header.
438 HeaderEntry HE = { Name, Loc };
439 CurHeaderContents[Loc.File].push_back(HE);
John Thompsonf5db45b2013-03-27 01:02:46 +0000440
John Thompson4f8ba652013-03-12 02:07:30 +0000441 // Check whether we've seen this entry before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000442 SmallVector<Entry, 2> &Entries = (*this)[Name];
John Thompson4f8ba652013-03-12 02:07:30 +0000443 for (unsigned I = 0, N = Entries.size(); I != N; ++I) {
444 if (Entries[I].Kind == Kind && Entries[I].Loc == Loc)
445 return;
446 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000447
John Thompson4f8ba652013-03-12 02:07:30 +0000448 // We have not seen this entry before; record it.
449 Entry E = { Kind, Loc };
450 Entries.push_back(E);
451 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000452
John Thompson4f8ba652013-03-12 02:07:30 +0000453 void mergeCurHeaderContents() {
John Thompsonf5db45b2013-03-27 01:02:46 +0000454 for (DenseMap<const FileEntry *, HeaderContents>::iterator
455 H = CurHeaderContents.begin(),
456 HEnd = CurHeaderContents.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000457 H != HEnd; ++H) {
458 // Sort contents.
459 std::sort(H->second.begin(), H->second.end());
460
461 // Check whether we've seen this header before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000462 DenseMap<const FileEntry *, HeaderContents>::iterator KnownH =
463 AllHeaderContents.find(H->first);
John Thompson4f8ba652013-03-12 02:07:30 +0000464 if (KnownH == AllHeaderContents.end()) {
465 // We haven't seen this header before; record its contents.
466 AllHeaderContents.insert(*H);
467 continue;
468 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000469
John Thompson4f8ba652013-03-12 02:07:30 +0000470 // If the header contents are the same, we're done.
471 if (H->second == KnownH->second)
472 continue;
John Thompsonf5db45b2013-03-27 01:02:46 +0000473
John Thompson4f8ba652013-03-12 02:07:30 +0000474 // Determine what changed.
John Thompsonf5db45b2013-03-27 01:02:46 +0000475 std::set_symmetric_difference(
476 H->second.begin(), H->second.end(), KnownH->second.begin(),
477 KnownH->second.end(),
478 std::back_inserter(HeaderContentMismatches[H->first]));
John Thompson4f8ba652013-03-12 02:07:30 +0000479 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000480
John Thompson4f8ba652013-03-12 02:07:30 +0000481 CurHeaderContents.clear();
482 }
John Thompson161381e2013-06-27 18:52:23 +0000483
John Thompson1f67ccb2013-03-12 18:51:47 +0000484private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000485 DenseMap<const FileEntry *, HeaderContents> CurHeaderContents;
486 DenseMap<const FileEntry *, HeaderContents> AllHeaderContents;
John Thompson4f8ba652013-03-12 02:07:30 +0000487};
488
John Thompson161381e2013-06-27 18:52:23 +0000489class CollectEntitiesVisitor
490 : public RecursiveASTVisitor<CollectEntitiesVisitor> {
John Thompson4f8ba652013-03-12 02:07:30 +0000491public:
John Thompson74083922013-09-18 18:19:43 +0000492 CollectEntitiesVisitor(SourceManager &SM, EntityMap &Entities,
493 Preprocessor &PP, PreprocessorTracker &PPTracker,
494 int &HadErrors)
495 : SM(SM), Entities(Entities), PP(PP), PPTracker(PPTracker),
496 HadErrors(HadErrors) {}
John Thompsonf5db45b2013-03-27 01:02:46 +0000497
John Thompson4f8ba652013-03-12 02:07:30 +0000498 bool TraverseStmt(Stmt *S) { return true; }
499 bool TraverseType(QualType T) { return true; }
500 bool TraverseTypeLoc(TypeLoc TL) { return true; }
501 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000502 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
503 return true;
504 }
505 bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo) {
506 return true;
507 }
John Thompson4f8ba652013-03-12 02:07:30 +0000508 bool TraverseTemplateName(TemplateName Template) { return true; }
509 bool TraverseTemplateArgument(const TemplateArgument &Arg) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000510 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
511 return true;
512 }
John Thompson4f8ba652013-03-12 02:07:30 +0000513 bool TraverseTemplateArguments(const TemplateArgument *Args,
John Thompsonf5db45b2013-03-27 01:02:46 +0000514 unsigned NumArgs) {
515 return true;
516 }
John Thompson4f8ba652013-03-12 02:07:30 +0000517 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; }
Benjamin Kramer281f9d02014-05-10 16:32:07 +0000518 bool TraverseLambdaCapture(LambdaCapture C) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000519
John Thompson74083922013-09-18 18:19:43 +0000520 // Check 'extern "*" {}' block for #include directives.
521 bool VisitLinkageSpecDecl(LinkageSpecDecl *D) {
522 // Bail if not a block.
523 if (!D->hasBraces())
524 return true;
525 SourceRange BlockRange = D->getSourceRange();
526 const char *LinkageLabel;
527 switch (D->getLanguage()) {
528 case LinkageSpecDecl::lang_c:
529 LinkageLabel = "extern \"C\" {}";
530 break;
531 case LinkageSpecDecl::lang_cxx:
532 LinkageLabel = "extern \"C++\" {}";
533 break;
John Thompson74083922013-09-18 18:19:43 +0000534 }
535 if (!PPTracker.checkForIncludesInBlock(PP, BlockRange, LinkageLabel,
536 errs()))
537 HadErrors = 1;
538 return true;
539 }
540
541 // Check 'namespace (name) {}' block for #include directives.
542 bool VisitNamespaceDecl(const NamespaceDecl *D) {
543 SourceRange BlockRange = D->getSourceRange();
544 std::string Label("namespace ");
545 Label += D->getName();
546 Label += " {}";
547 if (!PPTracker.checkForIncludesInBlock(PP, BlockRange, Label.c_str(),
548 errs()))
549 HadErrors = 1;
550 return true;
551 }
552
553 // Collect definition entities.
John Thompson4f8ba652013-03-12 02:07:30 +0000554 bool VisitNamedDecl(NamedDecl *ND) {
555 // We only care about file-context variables.
556 if (!ND->getDeclContext()->isFileContext())
557 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000558
John Thompson4f8ba652013-03-12 02:07:30 +0000559 // Skip declarations that tend to be properly multiply-declared.
560 if (isa<NamespaceDecl>(ND) || isa<UsingDirectiveDecl>(ND) ||
John Thompsonf5db45b2013-03-27 01:02:46 +0000561 isa<NamespaceAliasDecl>(ND) ||
562 isa<ClassTemplateSpecializationDecl>(ND) || isa<UsingDecl>(ND) ||
John Thompson8e01c062013-08-26 15:17:23 +0000563 isa<ClassTemplateDecl>(ND) || isa<TemplateTypeParmDecl>(ND) ||
John Thompsoncc2e2912013-09-03 18:44:11 +0000564 isa<TypeAliasTemplateDecl>(ND) || isa<UsingShadowDecl>(ND) ||
565 isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
John Thompson4f8ba652013-03-12 02:07:30 +0000566 (isa<TagDecl>(ND) &&
567 !cast<TagDecl>(ND)->isThisDeclarationADefinition()))
568 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000569
John Thompson8e01c062013-08-26 15:17:23 +0000570 // Skip anonymous declarations.
571 if (!ND->getDeclName())
572 return true;
573
574 // Get the qualified name.
John Thompsoncc2e2912013-09-03 18:44:11 +0000575 std::string Name;
576 llvm::raw_string_ostream OS(Name);
577 ND->printQualifiedName(OS);
578 OS.flush();
John Thompson4f8ba652013-03-12 02:07:30 +0000579 if (Name.empty())
580 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000581
John Thompson4f8ba652013-03-12 02:07:30 +0000582 Location Loc(SM, ND->getLocation());
583 if (!Loc)
584 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000585
John Thompson52d98862013-03-28 18:38:43 +0000586 Entities.add(Name, isa<TagDecl>(ND) ? Entry::EK_Tag : Entry::EK_Value, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000587 return true;
588 }
John Thompson161381e2013-06-27 18:52:23 +0000589
John Thompson1f67ccb2013-03-12 18:51:47 +0000590private:
591 SourceManager &SM;
592 EntityMap &Entities;
John Thompson74083922013-09-18 18:19:43 +0000593 Preprocessor &PP;
594 PreprocessorTracker &PPTracker;
595 int &HadErrors;
John Thompson4f8ba652013-03-12 02:07:30 +0000596};
597
598class CollectEntitiesConsumer : public ASTConsumer {
John Thompson4f8ba652013-03-12 02:07:30 +0000599public:
John Thompson94faa4d2013-07-26 23:56:42 +0000600 CollectEntitiesConsumer(EntityMap &Entities,
601 PreprocessorTracker &preprocessorTracker,
John Thompson74083922013-09-18 18:19:43 +0000602 Preprocessor &PP, StringRef InFile, int &HadErrors)
603 : Entities(Entities), PPTracker(preprocessorTracker), PP(PP),
604 HadErrors(HadErrors) {
John Thompson94faa4d2013-07-26 23:56:42 +0000605 PPTracker.handlePreprocessorEntry(PP, InFile);
606 }
607
608 ~CollectEntitiesConsumer() { PPTracker.handlePreprocessorExit(); }
John Thompsonf5db45b2013-03-27 01:02:46 +0000609
John Thompson4f8ba652013-03-12 02:07:30 +0000610 virtual void HandleTranslationUnit(ASTContext &Ctx) {
611 SourceManager &SM = Ctx.getSourceManager();
John Thompsonf5db45b2013-03-27 01:02:46 +0000612
John Thompson4f8ba652013-03-12 02:07:30 +0000613 // Collect declared entities.
John Thompson74083922013-09-18 18:19:43 +0000614 CollectEntitiesVisitor(SM, Entities, PP, PPTracker, HadErrors)
John Thompsonf5db45b2013-03-27 01:02:46 +0000615 .TraverseDecl(Ctx.getTranslationUnitDecl());
616
John Thompson4f8ba652013-03-12 02:07:30 +0000617 // Collect macro definitions.
618 for (Preprocessor::macro_iterator M = PP.macro_begin(),
John Thompsonf5db45b2013-03-27 01:02:46 +0000619 MEnd = PP.macro_end();
John Thompson4f8ba652013-03-12 02:07:30 +0000620 M != MEnd; ++M) {
621 Location Loc(SM, M->second->getLocation());
622 if (!Loc)
623 continue;
624
John Thompson52d98862013-03-28 18:38:43 +0000625 Entities.add(M->first->getName().str(), Entry::EK_Macro, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000626 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000627
John Thompson4f8ba652013-03-12 02:07:30 +0000628 // Merge header contents.
629 Entities.mergeCurHeaderContents();
630 }
John Thompson161381e2013-06-27 18:52:23 +0000631
John Thompson1f67ccb2013-03-12 18:51:47 +0000632private:
633 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000634 PreprocessorTracker &PPTracker;
John Thompson1f67ccb2013-03-12 18:51:47 +0000635 Preprocessor &PP;
John Thompson74083922013-09-18 18:19:43 +0000636 int &HadErrors;
John Thompson4f8ba652013-03-12 02:07:30 +0000637};
638
639class CollectEntitiesAction : public SyntaxOnlyAction {
John Thompson1f67ccb2013-03-12 18:51:47 +0000640public:
John Thompson94faa4d2013-07-26 23:56:42 +0000641 CollectEntitiesAction(EntityMap &Entities,
John Thompson74083922013-09-18 18:19:43 +0000642 PreprocessorTracker &preprocessorTracker,
643 int &HadErrors)
644 : Entities(Entities), PPTracker(preprocessorTracker),
645 HadErrors(HadErrors) {}
John Thompson161381e2013-06-27 18:52:23 +0000646
John Thompson4f8ba652013-03-12 02:07:30 +0000647protected:
David Blaikie680c4c82014-08-10 19:56:59 +0000648 std::unique_ptr<clang::ASTConsumer>
649 CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override {
650 return llvm::make_unique<CollectEntitiesConsumer>(
651 Entities, PPTracker, CI.getPreprocessor(), InFile, HadErrors);
John Thompson4f8ba652013-03-12 02:07:30 +0000652 }
John Thompson161381e2013-06-27 18:52:23 +0000653
John Thompson1f67ccb2013-03-12 18:51:47 +0000654private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000655 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000656 PreprocessorTracker &PPTracker;
John Thompson74083922013-09-18 18:19:43 +0000657 int &HadErrors;
John Thompson4f8ba652013-03-12 02:07:30 +0000658};
659
660class ModularizeFrontendActionFactory : public FrontendActionFactory {
John Thompson4f8ba652013-03-12 02:07:30 +0000661public:
John Thompson94faa4d2013-07-26 23:56:42 +0000662 ModularizeFrontendActionFactory(EntityMap &Entities,
John Thompson74083922013-09-18 18:19:43 +0000663 PreprocessorTracker &preprocessorTracker,
664 int &HadErrors)
665 : Entities(Entities), PPTracker(preprocessorTracker),
666 HadErrors(HadErrors) {}
John Thompson4f8ba652013-03-12 02:07:30 +0000667
668 virtual CollectEntitiesAction *create() {
John Thompson74083922013-09-18 18:19:43 +0000669 return new CollectEntitiesAction(Entities, PPTracker, HadErrors);
John Thompson4f8ba652013-03-12 02:07:30 +0000670 }
John Thompson161381e2013-06-27 18:52:23 +0000671
John Thompson1f67ccb2013-03-12 18:51:47 +0000672private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000673 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000674 PreprocessorTracker &PPTracker;
John Thompson74083922013-09-18 18:19:43 +0000675 int &HadErrors;
John Thompson4f8ba652013-03-12 02:07:30 +0000676};
677
John Thompsonbb0a3b02013-08-09 13:52:09 +0000678int main(int Argc, const char **Argv) {
John Thompsona2de1082013-03-26 01:17:48 +0000679
John Thompson5ab4f112013-10-15 13:52:33 +0000680 // Save program name for error messages.
681 Argv0 = Argv[0];
682
John Thompson5d9862f2015-02-10 14:45:30 +0000683 // Save program arguments for use in module.modulemap comment.
John Thompson5ab4f112013-10-15 13:52:33 +0000684 CommandLine = sys::path::stem(sys::path::filename(Argv0));
685 for (int ArgIndex = 1; ArgIndex < Argc; ArgIndex++) {
686 CommandLine.append(" ");
687 CommandLine.append(Argv[ArgIndex]);
688 }
689
John Thompsona2de1082013-03-26 01:17:48 +0000690 // This causes options to be parsed.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000691 cl::ParseCommandLineOptions(Argc, Argv, "modularize.\n");
John Thompsona2de1082013-03-26 01:17:48 +0000692
693 // No go if we have no header list file.
694 if (ListFileName.size() == 0) {
695 cl::PrintHelpMessage();
John Thompsonea6c8db2013-03-27 21:23:21 +0000696 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000697 }
John Thompsona2de1082013-03-26 01:17:48 +0000698
John Thompson7d0213c2013-09-04 20:46:24 +0000699 // Get header file names and dependencies.
John Thompsonf5db45b2013-03-27 01:02:46 +0000700 SmallVector<std::string, 32> Headers;
John Thompson7d0213c2013-09-04 20:46:24 +0000701 DependencyMap Dependencies;
Rafael Espindolac7f0d232014-06-12 22:08:48 +0000702 if (std::error_code EC = getHeaderFileNames(Headers, Dependencies,
703 ListFileName, HeaderPrefix)) {
John Thompsonbb0a3b02013-08-09 13:52:09 +0000704 errs() << Argv[0] << ": error: Unable to get header list '" << ListFileName
705 << "': " << EC.message() << '\n';
John Thompsonea6c8db2013-03-27 21:23:21 +0000706 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000707 }
John Thompsona2de1082013-03-26 01:17:48 +0000708
John Thompson5ab4f112013-10-15 13:52:33 +0000709 // If we are in assistant mode, output the module map and quit.
John Thompsone744d2b2013-12-10 02:26:44 +0000710 if (ModuleMapPath.length() != 0) {
John Thompson5ab4f112013-10-15 13:52:33 +0000711 if (!createModuleMap(ModuleMapPath, Headers, Dependencies, HeaderPrefix,
712 RootModule))
713 return 1; // Failed.
714 return 0; // Success - Skip checks in assistant mode.
715 }
716
John Thompson4f8ba652013-03-12 02:07:30 +0000717 // Create the compilation database.
John Thompsona2de1082013-03-26 01:17:48 +0000718 SmallString<256> PathBuf;
John Thompsonf5db45b2013-03-27 01:02:46 +0000719 sys::fs::current_path(PathBuf);
Ahmed Charles6a2dc5c2014-03-09 09:24:40 +0000720 std::unique_ptr<CompilationDatabase> Compilations;
John Thompsonf5db45b2013-03-27 01:02:46 +0000721 Compilations.reset(
722 new FixedCompilationDatabase(Twine(PathBuf), CC1Arguments));
John Thompsona2de1082013-03-26 01:17:48 +0000723
John Thompson94faa4d2013-07-26 23:56:42 +0000724 // Create preprocessor tracker, to watch for macro and conditional problems.
Ahmed Charles6a2dc5c2014-03-09 09:24:40 +0000725 std::unique_ptr<PreprocessorTracker> PPTracker(PreprocessorTracker::create());
John Thompson94faa4d2013-07-26 23:56:42 +0000726
John Thompson4f8ba652013-03-12 02:07:30 +0000727 // Parse all of the headers, detecting duplicates.
728 EntityMap Entities;
729 ClangTool Tool(*Compilations, Headers);
Alexander Kornienkod3657312014-12-03 17:53:03 +0000730 Tool.appendArgumentsAdjuster(getAddDependenciesAdjuster(Dependencies));
John Thompson74083922013-09-18 18:19:43 +0000731 int HadErrors = 0;
Benjamin Kramer6e914242014-07-24 10:23:33 +0000732 ModularizeFrontendActionFactory Factory(Entities, *PPTracker, HadErrors);
733 HadErrors |= Tool.run(&Factory);
John Thompsonce601e22013-03-14 01:41:29 +0000734
John Thompson4e4d9b32013-03-28 01:20:19 +0000735 // Create a place to save duplicate entity locations, separate bins per kind.
736 typedef SmallVector<Location, 8> LocationArray;
John Thompson52d98862013-03-28 18:38:43 +0000737 typedef SmallVector<LocationArray, Entry::EK_NumberOfKinds> EntryBinArray;
John Thompson4e4d9b32013-03-28 01:20:19 +0000738 EntryBinArray EntryBins;
John Thompsonbb0a3b02013-08-09 13:52:09 +0000739 int KindIndex;
740 for (KindIndex = 0; KindIndex < Entry::EK_NumberOfKinds; ++KindIndex) {
741 LocationArray Array;
742 EntryBins.push_back(Array);
Michael Gottesman4b249212013-03-28 06:07:15 +0000743 }
John Thompson4e4d9b32013-03-28 01:20:19 +0000744
John Thompson4f8ba652013-03-12 02:07:30 +0000745 // Check for the same entity being defined in multiple places.
746 for (EntityMap::iterator E = Entities.begin(), EEnd = Entities.end();
747 E != EEnd; ++E) {
Alp Toker9a5134e2013-12-01 05:08:12 +0000748 // If only one occurrence, exit early.
John Thompson4e4d9b32013-03-28 01:20:19 +0000749 if (E->second.size() == 1)
750 continue;
751 // Clear entity locations.
752 for (EntryBinArray::iterator CI = EntryBins.begin(), CE = EntryBins.end();
753 CI != CE; ++CI) {
John Thompson52d98862013-03-28 18:38:43 +0000754 CI->clear();
John Thompson4e4d9b32013-03-28 01:20:19 +0000755 }
756 // Walk the entities of a single name, collecting the locations,
757 // separated into separate bins.
John Thompson4f8ba652013-03-12 02:07:30 +0000758 for (unsigned I = 0, N = E->second.size(); I != N; ++I) {
John Thompson52d98862013-03-28 18:38:43 +0000759 EntryBins[E->second[I].Kind].push_back(E->second[I].Loc);
John Thompson4e4d9b32013-03-28 01:20:19 +0000760 }
761 // Report any duplicate entity definition errors.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000762 int KindIndex = 0;
John Thompson4e4d9b32013-03-28 01:20:19 +0000763 for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end();
John Thompsonbb0a3b02013-08-09 13:52:09 +0000764 DI != DE; ++DI, ++KindIndex) {
765 int ECount = DI->size();
John Thompsonabe79d92013-12-04 20:41:30 +0000766 // If only 1 occurrence of this entity, skip it, as we only report duplicates.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000767 if (ECount <= 1)
John Thompson4f8ba652013-03-12 02:07:30 +0000768 continue;
John Thompson52d98862013-03-28 18:38:43 +0000769 LocationArray::iterator FI = DI->begin();
John Thompsonbb0a3b02013-08-09 13:52:09 +0000770 StringRef kindName = Entry::getKindName((Entry::EntryKind)KindIndex);
John Thompson4e4d9b32013-03-28 01:20:19 +0000771 errs() << "error: " << kindName << " '" << E->first()
772 << "' defined at multiple locations:\n";
John Thompson52d98862013-03-28 18:38:43 +0000773 for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000774 errs() << " " << FI->File->getName() << ":" << FI->Line << ":"
775 << FI->Column << "\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000776 }
John Thompson4f8ba652013-03-12 02:07:30 +0000777 HadErrors = 1;
778 }
779 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000780
John Thompson94faa4d2013-07-26 23:56:42 +0000781 // Complain about macro instance in header files that differ based on how
782 // they are included.
783 if (PPTracker->reportInconsistentMacros(errs()))
784 HadErrors = 1;
785
786 // Complain about preprocessor conditional directives in header files that
787 // differ based on how they are included.
788 if (PPTracker->reportInconsistentConditionals(errs()))
789 HadErrors = 1;
790
John Thompson4f8ba652013-03-12 02:07:30 +0000791 // Complain about any headers that have contents that differ based on how
792 // they are included.
John Thompsonce601e22013-03-14 01:41:29 +0000793 // FIXME: Could we provide information about which preprocessor conditionals
794 // are involved?
John Thompsonf5db45b2013-03-27 01:02:46 +0000795 for (DenseMap<const FileEntry *, HeaderContents>::iterator
796 H = Entities.HeaderContentMismatches.begin(),
797 HEnd = Entities.HeaderContentMismatches.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000798 H != HEnd; ++H) {
799 if (H->second.empty()) {
John Thompsonf5db45b2013-03-27 01:02:46 +0000800 errs() << "internal error: phantom header content mismatch\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000801 continue;
802 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000803
John Thompson4f8ba652013-03-12 02:07:30 +0000804 HadErrors = 1;
John Thompsonf5db45b2013-03-27 01:02:46 +0000805 errs() << "error: header '" << H->first->getName()
John Thompson94faa4d2013-07-26 23:56:42 +0000806 << "' has different contents depending on how it was included.\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000807 for (unsigned I = 0, N = H->second.size(); I != N; ++I) {
John Thompson161381e2013-06-27 18:52:23 +0000808 errs() << "note: '" << H->second[I].Name << "' in "
809 << H->second[I].Loc.File->getName() << " at "
810 << H->second[I].Loc.Line << ":" << H->second[I].Loc.Column
811 << " not always provided\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000812 }
813 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000814
John Thompson4f8ba652013-03-12 02:07:30 +0000815 return HadErrors;
816}