blob: af78c5ae5543c30419d908b8f4ae8c1e54f7796b [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 Thompson4fa9c2c2013-08-09 00:19:03 +000078// See PreprocessorTracker.cpp for additional details.
John Thompsoncc2e2912013-09-03 18:44:11 +000079//
John Thompson74751802013-09-03 18:48:43 +000080// Future directions:
81//
82// Basically, we want to add new checks for whatever we can check with respect
83// to checking headers for module'ability.
84//
85// Some ideas:
86//
John Thompson53a9d2d2013-09-04 18:29:36 +000087// 1. Check for and warn about "#include" directives inside 'extern "C/C++" {}'
88// and "namespace (name) {}" blocks.
89//
90// 2. Omit duplicate "not always provided" messages
91//
92// 3. Add options to disable any of the checks, in case
John Thompson74751802013-09-03 18:48:43 +000093// there is some problem with them, or the messages get too verbose.
94//
John Thompson53a9d2d2013-09-04 18:29:36 +000095// 4. Try to figure out the preprocessor conditional directives that
John Thompson74751802013-09-03 18:48:43 +000096// contribute to problems and tie them to the inconsistent definitions.
97//
Bob Wilsonf5999bd2013-09-04 16:48:28 +000098// 5. There are some legitimate uses of preprocessor macros that
99// modularize will flag as errors, such as repeatedly #include'ing
100// a file and using interleaving defined/undefined macros
101// to change declarations in the included file. Is there a way
102// to address this? Maybe have modularize accept a list of macros
103// to ignore. Otherwise you can just exclude the file, after checking
104// for legitimate errors.
105//
106// 6. What else?
John Thompsonce601e22013-03-14 01:41:29 +0000107//
108// General clean-up and refactoring:
109//
110// 1. The Location class seems to be something that we might
111// want to design to be applicable to a wider range of tools, and stick it
112// somewhere into Tooling/ in mainline
113//
John Thompson4f8ba652013-03-12 02:07:30 +0000114//===----------------------------------------------------------------------===//
John Thompsonf5db45b2013-03-27 01:02:46 +0000115
John Thompsond977c1e2013-03-27 18:34:38 +0000116#include "clang/AST/ASTConsumer.h"
117#include "clang/AST/ASTContext.h"
118#include "clang/AST/RecursiveASTVisitor.h"
119#include "clang/Basic/SourceManager.h"
John Thompson7d0213c2013-09-04 20:46:24 +0000120#include "clang/Driver/Options.h"
John Thompsond977c1e2013-03-27 18:34:38 +0000121#include "clang/Frontend/CompilerInstance.h"
122#include "clang/Frontend/FrontendActions.h"
123#include "clang/Lex/Preprocessor.h"
124#include "clang/Tooling/CompilationDatabase.h"
125#include "clang/Tooling/Tooling.h"
126#include "llvm/ADT/OwningPtr.h"
127#include "llvm/ADT/StringRef.h"
John Thompson7d0213c2013-09-04 20:46:24 +0000128#include "llvm/ADT/StringMap.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000129#include "llvm/Config/config.h"
John Thompson7d0213c2013-09-04 20:46:24 +0000130#include "llvm/Option/Arg.h"
131#include "llvm/Option/ArgList.h"
132#include "llvm/Option/OptTable.h"
133#include "llvm/Option/Option.h"
John Thompsona2de1082013-03-26 01:17:48 +0000134#include "llvm/Support/CommandLine.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000135#include "llvm/Support/FileSystem.h"
John Thompsonf5db45b2013-03-27 01:02:46 +0000136#include "llvm/Support/MemoryBuffer.h"
John Thompsona2de1082013-03-26 01:17:48 +0000137#include "llvm/Support/Path.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000138#include <algorithm>
John Thompsond977c1e2013-03-27 18:34:38 +0000139#include <fstream>
John Thompson4f8ba652013-03-12 02:07:30 +0000140#include <iterator>
John Thompsond977c1e2013-03-27 18:34:38 +0000141#include <string>
142#include <vector>
John Thompson94faa4d2013-07-26 23:56:42 +0000143#include "PreprocessorTracker.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000144
Bob Wilsonf5999bd2013-09-04 16:48:28 +0000145using namespace clang;
John Thompson7d0213c2013-09-04 20:46:24 +0000146using namespace clang::driver;
147using namespace clang::driver::options;
148using namespace clang::tooling;
John Thompsona2de1082013-03-26 01:17:48 +0000149using namespace llvm;
John Thompson7d0213c2013-09-04 20:46:24 +0000150using namespace llvm::opt;
John Thompson94faa4d2013-07-26 23:56:42 +0000151using namespace Modularize;
John Thompson4f8ba652013-03-12 02:07:30 +0000152
John Thompsonea6c8db2013-03-27 21:23:21 +0000153// Option to specify a file name for a list of header files to check.
John Thompsonb809dfc2013-07-19 14:19:31 +0000154cl::opt<std::string>
155ListFileName(cl::Positional,
156 cl::desc("<name of file containing list of headers to check>"));
John Thompsonea6c8db2013-03-27 21:23:21 +0000157
158// Collect all other arguments, which will be passed to the front end.
John Thompson161381e2013-06-27 18:52:23 +0000159cl::list<std::string>
John Thompsonb809dfc2013-07-19 14:19:31 +0000160CC1Arguments(cl::ConsumeAfter,
161 cl::desc("<arguments to be passed to front end>..."));
John Thompsonea6c8db2013-03-27 21:23:21 +0000162
163// Option to specify a prefix to be prepended to the header names.
164cl::opt<std::string> HeaderPrefix(
165 "prefix", cl::init(""),
166 cl::desc(
167 "Prepend header file paths with this prefix."
168 " If not specified,"
169 " the files are considered to be relative to the header list file."));
170
John Thompson7d0213c2013-09-04 20:46:24 +0000171typedef SmallVector<std::string, 4> DependentsVector;
172typedef StringMap<DependentsVector> DependencyMap;
Bob Wilsonf5999bd2013-09-04 16:48:28 +0000173
John Thompson7d0213c2013-09-04 20:46:24 +0000174// Read the header list file and collect the header file names and
175// optional dependencies.
176error_code getHeaderFileNames(SmallVectorImpl<std::string> &HeaderFileNames,
177 DependencyMap &Dependencies,
178 StringRef ListFileName, StringRef HeaderPrefix) {
John Thompsonea6c8db2013-03-27 21:23:21 +0000179 // By default, use the path component of the list file name.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000180 SmallString<256> HeaderDirectory(ListFileName);
181 sys::path::remove_filename(HeaderDirectory);
John Thompson7d0213c2013-09-04 20:46:24 +0000182 SmallString<256> CurrentDirectory;
183 sys::fs::current_path(CurrentDirectory);
John Thompsonea6c8db2013-03-27 21:23:21 +0000184
185 // Get the prefix if we have one.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000186 if (HeaderPrefix.size() != 0)
187 HeaderDirectory = HeaderPrefix;
John Thompsonea6c8db2013-03-27 21:23:21 +0000188
189 // Read the header list file into a buffer.
190 OwningPtr<MemoryBuffer> listBuffer;
John Thompsonbb0a3b02013-08-09 13:52:09 +0000191 if (error_code ec = MemoryBuffer::getFile(ListFileName, listBuffer)) {
John Thompsonea6c8db2013-03-27 21:23:21 +0000192 return ec;
193 }
194
195 // Parse the header list into strings.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000196 SmallVector<StringRef, 32> Strings;
197 listBuffer->getBuffer().split(Strings, "\n", -1, false);
John Thompsonea6c8db2013-03-27 21:23:21 +0000198
199 // Collect the header file names from the string list.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000200 for (SmallVectorImpl<StringRef>::iterator I = Strings.begin(),
201 E = Strings.end();
John Thompsonea6c8db2013-03-27 21:23:21 +0000202 I != E; ++I) {
John Thompson7d0213c2013-09-04 20:46:24 +0000203 StringRef Line = I->trim();
John Thompsonea6c8db2013-03-27 21:23:21 +0000204 // Ignore comments and empty lines.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000205 if (Line.empty() || (Line[0] == '#'))
John Thompsonea6c8db2013-03-27 21:23:21 +0000206 continue;
John Thompson7d0213c2013-09-04 20:46:24 +0000207 std::pair<StringRef, StringRef> TargetAndDependents = Line.split(':');
John Thompsonbb0a3b02013-08-09 13:52:09 +0000208 SmallString<256> HeaderFileName;
John Thompsonea6c8db2013-03-27 21:23:21 +0000209 // Prepend header file name prefix if it's not absolute.
John Thompson7d0213c2013-09-04 20:46:24 +0000210 if (sys::path::is_absolute(TargetAndDependents.first))
211 llvm::sys::path::native(TargetAndDependents.first, HeaderFileName);
John Thompsonea6c8db2013-03-27 21:23:21 +0000212 else {
John Thompson7d0213c2013-09-04 20:46:24 +0000213 if (HeaderDirectory.size() != 0)
214 HeaderFileName = HeaderDirectory;
215 else
216 HeaderFileName = CurrentDirectory;
217 sys::path::append(HeaderFileName, TargetAndDependents.first);
218 llvm::sys::path::native(HeaderFileName.str(), HeaderFileName);
John Thompsonea6c8db2013-03-27 21:23:21 +0000219 }
John Thompson7d0213c2013-09-04 20:46:24 +0000220 // Handle optional dependencies.
221 DependentsVector Dependents;
222 SmallVector<StringRef, 4> DependentsList;
223 TargetAndDependents.second.split(DependentsList, " ", -1, false);
224 int Count = DependentsList.size();
225 for (int Index = 0; Index < Count; ++Index) {
226 SmallString<256> Dependent;
227 if (sys::path::is_absolute(DependentsList[Index]))
228 Dependent = DependentsList[Index];
229 else {
230 if (HeaderDirectory.size() != 0)
231 Dependent = HeaderDirectory;
232 else
233 Dependent = CurrentDirectory;
234 sys::path::append(Dependent, DependentsList[Index]);
235 }
236 llvm::sys::path::native(Dependent.str(), Dependent);
237 Dependents.push_back(Dependent.str());
238 }
239 // Save the resulting header file path and dependencies.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000240 HeaderFileNames.push_back(HeaderFileName.str());
John Thompson7d0213c2013-09-04 20:46:24 +0000241 Dependencies[HeaderFileName.str()] = Dependents;
John Thompsonea6c8db2013-03-27 21:23:21 +0000242 }
243
244 return error_code::success();
245}
246
John Thompson7d0213c2013-09-04 20:46:24 +0000247// Helper function for finding the input file in an arguments list.
248std::string findInputFile(const CommandLineArguments &CLArgs) {
249 OwningPtr<OptTable> Opts(createDriverOptTable());
250 const unsigned IncludedFlagsBitmask = options::CC1Option;
251 unsigned MissingArgIndex, MissingArgCount;
252 SmallVector<const char *, 256> Argv;
253 for (CommandLineArguments::const_iterator I = CLArgs.begin(),
254 E = CLArgs.end();
255 I != E; ++I)
256 Argv.push_back(I->c_str());
257 OwningPtr<InputArgList> Args(
258 Opts->ParseArgs(Argv.data(), Argv.data() + Argv.size(), MissingArgIndex,
259 MissingArgCount, IncludedFlagsBitmask));
260 std::vector<std::string> Inputs = Args->getAllArgValues(OPT_INPUT);
261 return Inputs.back();
262}
263
264// We provide this derivation to add in "-include (file)" arguments for header
265// dependencies.
266class AddDependenciesAdjuster : public ArgumentsAdjuster {
267public:
268 AddDependenciesAdjuster(DependencyMap &Dependencies)
269 : Dependencies(Dependencies) {}
270
271private:
272 // Callback for adjusting commandline arguments.
273 CommandLineArguments Adjust(const CommandLineArguments &Args) {
274 std::string InputFile = findInputFile(Args);
275 DependentsVector &FileDependents = Dependencies[InputFile];
276 int Count = FileDependents.size();
277 if (Count == 0)
278 return Args;
279 CommandLineArguments NewArgs(Args);
280 for (int Index = 0; Index < Count; ++Index) {
281 NewArgs.push_back("-include");
282 std::string File(std::string("\"") + FileDependents[Index] +
283 std::string("\""));
284 NewArgs.push_back(FileDependents[Index]);
285 }
286 return NewArgs;
287 }
288 DependencyMap &Dependencies;
289};
290
John Thompsonce601e22013-03-14 01:41:29 +0000291// FIXME: The Location class seems to be something that we might
292// want to design to be applicable to a wider range of tools, and stick it
293// somewhere into Tooling/ in mainline
John Thompson4f8ba652013-03-12 02:07:30 +0000294struct Location {
295 const FileEntry *File;
296 unsigned Line, Column;
John Thompsonf5db45b2013-03-27 01:02:46 +0000297
298 Location() : File(), Line(), Column() {}
299
John Thompson4f8ba652013-03-12 02:07:30 +0000300 Location(SourceManager &SM, SourceLocation Loc) : File(), Line(), Column() {
301 Loc = SM.getExpansionLoc(Loc);
302 if (Loc.isInvalid())
303 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000304
John Thompson4f8ba652013-03-12 02:07:30 +0000305 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(Loc);
306 File = SM.getFileEntryForID(Decomposed.first);
307 if (!File)
308 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000309
John Thompson4f8ba652013-03-12 02:07:30 +0000310 Line = SM.getLineNumber(Decomposed.first, Decomposed.second);
311 Column = SM.getColumnNumber(Decomposed.first, Decomposed.second);
312 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000313
John Thompson4f8ba652013-03-12 02:07:30 +0000314 operator bool() const { return File != 0; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000315
John Thompson4f8ba652013-03-12 02:07:30 +0000316 friend bool operator==(const Location &X, const Location &Y) {
317 return X.File == Y.File && X.Line == Y.Line && X.Column == Y.Column;
318 }
319
320 friend bool operator!=(const Location &X, const Location &Y) {
321 return !(X == Y);
322 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000323
John Thompson4f8ba652013-03-12 02:07:30 +0000324 friend bool operator<(const Location &X, const Location &Y) {
325 if (X.File != Y.File)
326 return X.File < Y.File;
327 if (X.Line != Y.Line)
328 return X.Line < Y.Line;
329 return X.Column < Y.Column;
330 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000331 friend bool operator>(const Location &X, const Location &Y) { return Y < X; }
John Thompson4f8ba652013-03-12 02:07:30 +0000332 friend bool operator<=(const Location &X, const Location &Y) {
333 return !(Y < X);
334 }
335 friend bool operator>=(const Location &X, const Location &Y) {
336 return !(X < Y);
337 }
John Thompson4f8ba652013-03-12 02:07:30 +0000338};
339
John Thompson4f8ba652013-03-12 02:07:30 +0000340struct Entry {
John Thompson52d98862013-03-28 18:38:43 +0000341 enum EntryKind {
342 EK_Tag,
343 EK_Value,
344 EK_Macro,
345
346 EK_NumberOfKinds
John Thompson4f8ba652013-03-12 02:07:30 +0000347 } Kind;
John Thompsonf5db45b2013-03-27 01:02:46 +0000348
John Thompson4f8ba652013-03-12 02:07:30 +0000349 Location Loc;
John Thompson4e4d9b32013-03-28 01:20:19 +0000350
351 StringRef getKindName() { return getKindName(Kind); }
John Thompson52d98862013-03-28 18:38:43 +0000352 static StringRef getKindName(EntryKind kind);
John Thompson4f8ba652013-03-12 02:07:30 +0000353};
354
John Thompson4e4d9b32013-03-28 01:20:19 +0000355// Return a string representing the given kind.
John Thompson52d98862013-03-28 18:38:43 +0000356StringRef Entry::getKindName(Entry::EntryKind kind) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000357 switch (kind) {
John Thompson52d98862013-03-28 18:38:43 +0000358 case EK_Tag:
John Thompson4e4d9b32013-03-28 01:20:19 +0000359 return "tag";
John Thompson52d98862013-03-28 18:38:43 +0000360 case EK_Value:
John Thompson4e4d9b32013-03-28 01:20:19 +0000361 return "value";
John Thompson52d98862013-03-28 18:38:43 +0000362 case EK_Macro:
John Thompson4e4d9b32013-03-28 01:20:19 +0000363 return "macro";
John Thompson52d98862013-03-28 18:38:43 +0000364 case EK_NumberOfKinds:
John Thompson4e4d9b32013-03-28 01:20:19 +0000365 break;
John Thompson4e4d9b32013-03-28 01:20:19 +0000366 }
David Blaikiec66c07d2013-03-28 02:30:37 +0000367 llvm_unreachable("invalid Entry kind");
John Thompson4e4d9b32013-03-28 01:20:19 +0000368}
369
John Thompson4f8ba652013-03-12 02:07:30 +0000370struct HeaderEntry {
371 std::string Name;
372 Location Loc;
John Thompsonf5db45b2013-03-27 01:02:46 +0000373
John Thompson4f8ba652013-03-12 02:07:30 +0000374 friend bool operator==(const HeaderEntry &X, const HeaderEntry &Y) {
375 return X.Loc == Y.Loc && X.Name == Y.Name;
376 }
377 friend bool operator!=(const HeaderEntry &X, const HeaderEntry &Y) {
378 return !(X == Y);
379 }
380 friend bool operator<(const HeaderEntry &X, const HeaderEntry &Y) {
381 return X.Loc < Y.Loc || (X.Loc == Y.Loc && X.Name < Y.Name);
382 }
383 friend bool operator>(const HeaderEntry &X, const HeaderEntry &Y) {
384 return Y < X;
385 }
386 friend bool operator<=(const HeaderEntry &X, const HeaderEntry &Y) {
387 return !(Y < X);
388 }
389 friend bool operator>=(const HeaderEntry &X, const HeaderEntry &Y) {
390 return !(X < Y);
391 }
392};
393
394typedef std::vector<HeaderEntry> HeaderContents;
395
John Thompsonf5db45b2013-03-27 01:02:46 +0000396class EntityMap : public StringMap<SmallVector<Entry, 2> > {
John Thompson4f8ba652013-03-12 02:07:30 +0000397public:
John Thompsonf5db45b2013-03-27 01:02:46 +0000398 DenseMap<const FileEntry *, HeaderContents> HeaderContentMismatches;
399
John Thompson52d98862013-03-28 18:38:43 +0000400 void add(const std::string &Name, enum Entry::EntryKind Kind, Location Loc) {
John Thompson4f8ba652013-03-12 02:07:30 +0000401 // Record this entity in its header.
402 HeaderEntry HE = { Name, Loc };
403 CurHeaderContents[Loc.File].push_back(HE);
John Thompsonf5db45b2013-03-27 01:02:46 +0000404
John Thompson4f8ba652013-03-12 02:07:30 +0000405 // Check whether we've seen this entry before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000406 SmallVector<Entry, 2> &Entries = (*this)[Name];
John Thompson4f8ba652013-03-12 02:07:30 +0000407 for (unsigned I = 0, N = Entries.size(); I != N; ++I) {
408 if (Entries[I].Kind == Kind && Entries[I].Loc == Loc)
409 return;
410 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000411
John Thompson4f8ba652013-03-12 02:07:30 +0000412 // We have not seen this entry before; record it.
413 Entry E = { Kind, Loc };
414 Entries.push_back(E);
415 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000416
John Thompson4f8ba652013-03-12 02:07:30 +0000417 void mergeCurHeaderContents() {
John Thompsonf5db45b2013-03-27 01:02:46 +0000418 for (DenseMap<const FileEntry *, HeaderContents>::iterator
419 H = CurHeaderContents.begin(),
420 HEnd = CurHeaderContents.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000421 H != HEnd; ++H) {
422 // Sort contents.
423 std::sort(H->second.begin(), H->second.end());
424
425 // Check whether we've seen this header before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000426 DenseMap<const FileEntry *, HeaderContents>::iterator KnownH =
427 AllHeaderContents.find(H->first);
John Thompson4f8ba652013-03-12 02:07:30 +0000428 if (KnownH == AllHeaderContents.end()) {
429 // We haven't seen this header before; record its contents.
430 AllHeaderContents.insert(*H);
431 continue;
432 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000433
John Thompson4f8ba652013-03-12 02:07:30 +0000434 // If the header contents are the same, we're done.
435 if (H->second == KnownH->second)
436 continue;
John Thompsonf5db45b2013-03-27 01:02:46 +0000437
John Thompson4f8ba652013-03-12 02:07:30 +0000438 // Determine what changed.
John Thompsonf5db45b2013-03-27 01:02:46 +0000439 std::set_symmetric_difference(
440 H->second.begin(), H->second.end(), KnownH->second.begin(),
441 KnownH->second.end(),
442 std::back_inserter(HeaderContentMismatches[H->first]));
John Thompson4f8ba652013-03-12 02:07:30 +0000443 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000444
John Thompson4f8ba652013-03-12 02:07:30 +0000445 CurHeaderContents.clear();
446 }
John Thompson161381e2013-06-27 18:52:23 +0000447
John Thompson1f67ccb2013-03-12 18:51:47 +0000448private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000449 DenseMap<const FileEntry *, HeaderContents> CurHeaderContents;
450 DenseMap<const FileEntry *, HeaderContents> AllHeaderContents;
John Thompson4f8ba652013-03-12 02:07:30 +0000451};
452
John Thompson161381e2013-06-27 18:52:23 +0000453class CollectEntitiesVisitor
454 : public RecursiveASTVisitor<CollectEntitiesVisitor> {
John Thompson4f8ba652013-03-12 02:07:30 +0000455public:
456 CollectEntitiesVisitor(SourceManager &SM, EntityMap &Entities)
John Thompsonf5db45b2013-03-27 01:02:46 +0000457 : SM(SM), Entities(Entities) {}
458
John Thompson4f8ba652013-03-12 02:07:30 +0000459 bool TraverseStmt(Stmt *S) { return true; }
460 bool TraverseType(QualType T) { return true; }
461 bool TraverseTypeLoc(TypeLoc TL) { return true; }
462 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000463 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
464 return true;
465 }
466 bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo) {
467 return true;
468 }
John Thompson4f8ba652013-03-12 02:07:30 +0000469 bool TraverseTemplateName(TemplateName Template) { return true; }
470 bool TraverseTemplateArgument(const TemplateArgument &Arg) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000471 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
472 return true;
473 }
John Thompson4f8ba652013-03-12 02:07:30 +0000474 bool TraverseTemplateArguments(const TemplateArgument *Args,
John Thompsonf5db45b2013-03-27 01:02:46 +0000475 unsigned NumArgs) {
476 return true;
477 }
John Thompson4f8ba652013-03-12 02:07:30 +0000478 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; }
479 bool TraverseLambdaCapture(LambdaExpr::Capture C) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000480
John Thompson4f8ba652013-03-12 02:07:30 +0000481 bool VisitNamedDecl(NamedDecl *ND) {
482 // We only care about file-context variables.
483 if (!ND->getDeclContext()->isFileContext())
484 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000485
John Thompson4f8ba652013-03-12 02:07:30 +0000486 // Skip declarations that tend to be properly multiply-declared.
487 if (isa<NamespaceDecl>(ND) || isa<UsingDirectiveDecl>(ND) ||
John Thompsonf5db45b2013-03-27 01:02:46 +0000488 isa<NamespaceAliasDecl>(ND) ||
489 isa<ClassTemplateSpecializationDecl>(ND) || isa<UsingDecl>(ND) ||
John Thompson8e01c062013-08-26 15:17:23 +0000490 isa<ClassTemplateDecl>(ND) || isa<TemplateTypeParmDecl>(ND) ||
John Thompsoncc2e2912013-09-03 18:44:11 +0000491 isa<TypeAliasTemplateDecl>(ND) || isa<UsingShadowDecl>(ND) ||
492 isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
John Thompson4f8ba652013-03-12 02:07:30 +0000493 (isa<TagDecl>(ND) &&
494 !cast<TagDecl>(ND)->isThisDeclarationADefinition()))
495 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000496
John Thompson8e01c062013-08-26 15:17:23 +0000497 // Skip anonymous declarations.
498 if (!ND->getDeclName())
499 return true;
500
501 // Get the qualified name.
John Thompsoncc2e2912013-09-03 18:44:11 +0000502 std::string Name;
503 llvm::raw_string_ostream OS(Name);
504 ND->printQualifiedName(OS);
505 OS.flush();
John Thompson4f8ba652013-03-12 02:07:30 +0000506 if (Name.empty())
507 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000508
John Thompson4f8ba652013-03-12 02:07:30 +0000509 Location Loc(SM, ND->getLocation());
510 if (!Loc)
511 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000512
John Thompson52d98862013-03-28 18:38:43 +0000513 Entities.add(Name, isa<TagDecl>(ND) ? Entry::EK_Tag : Entry::EK_Value, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000514 return true;
515 }
John Thompson161381e2013-06-27 18:52:23 +0000516
John Thompson1f67ccb2013-03-12 18:51:47 +0000517private:
518 SourceManager &SM;
519 EntityMap &Entities;
John Thompson4f8ba652013-03-12 02:07:30 +0000520};
521
522class CollectEntitiesConsumer : public ASTConsumer {
John Thompson4f8ba652013-03-12 02:07:30 +0000523public:
John Thompson94faa4d2013-07-26 23:56:42 +0000524 CollectEntitiesConsumer(EntityMap &Entities,
525 PreprocessorTracker &preprocessorTracker,
526 Preprocessor &PP, StringRef InFile)
527 : Entities(Entities), PPTracker(preprocessorTracker), PP(PP) {
528 PPTracker.handlePreprocessorEntry(PP, InFile);
529 }
530
531 ~CollectEntitiesConsumer() { PPTracker.handlePreprocessorExit(); }
John Thompsonf5db45b2013-03-27 01:02:46 +0000532
John Thompson4f8ba652013-03-12 02:07:30 +0000533 virtual void HandleTranslationUnit(ASTContext &Ctx) {
534 SourceManager &SM = Ctx.getSourceManager();
John Thompsonf5db45b2013-03-27 01:02:46 +0000535
John Thompson4f8ba652013-03-12 02:07:30 +0000536 // Collect declared entities.
537 CollectEntitiesVisitor(SM, Entities)
John Thompsonf5db45b2013-03-27 01:02:46 +0000538 .TraverseDecl(Ctx.getTranslationUnitDecl());
539
John Thompson4f8ba652013-03-12 02:07:30 +0000540 // Collect macro definitions.
541 for (Preprocessor::macro_iterator M = PP.macro_begin(),
John Thompsonf5db45b2013-03-27 01:02:46 +0000542 MEnd = PP.macro_end();
John Thompson4f8ba652013-03-12 02:07:30 +0000543 M != MEnd; ++M) {
544 Location Loc(SM, M->second->getLocation());
545 if (!Loc)
546 continue;
547
John Thompson52d98862013-03-28 18:38:43 +0000548 Entities.add(M->first->getName().str(), Entry::EK_Macro, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000549 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000550
John Thompson4f8ba652013-03-12 02:07:30 +0000551 // Merge header contents.
552 Entities.mergeCurHeaderContents();
553 }
John Thompson161381e2013-06-27 18:52:23 +0000554
John Thompson1f67ccb2013-03-12 18:51:47 +0000555private:
556 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000557 PreprocessorTracker &PPTracker;
John Thompson1f67ccb2013-03-12 18:51:47 +0000558 Preprocessor &PP;
John Thompson4f8ba652013-03-12 02:07:30 +0000559};
560
561class CollectEntitiesAction : public SyntaxOnlyAction {
John Thompson1f67ccb2013-03-12 18:51:47 +0000562public:
John Thompson94faa4d2013-07-26 23:56:42 +0000563 CollectEntitiesAction(EntityMap &Entities,
564 PreprocessorTracker &preprocessorTracker)
565 : Entities(Entities), PPTracker(preprocessorTracker) {}
John Thompson161381e2013-06-27 18:52:23 +0000566
John Thompson4f8ba652013-03-12 02:07:30 +0000567protected:
John Thompson161381e2013-06-27 18:52:23 +0000568 virtual clang::ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
569 StringRef InFile) {
John Thompson94faa4d2013-07-26 23:56:42 +0000570 return new CollectEntitiesConsumer(Entities, PPTracker,
571 CI.getPreprocessor(), InFile);
John Thompson4f8ba652013-03-12 02:07:30 +0000572 }
John Thompson161381e2013-06-27 18:52:23 +0000573
John Thompson1f67ccb2013-03-12 18:51:47 +0000574private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000575 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000576 PreprocessorTracker &PPTracker;
John Thompson4f8ba652013-03-12 02:07:30 +0000577};
578
579class ModularizeFrontendActionFactory : public FrontendActionFactory {
John Thompson4f8ba652013-03-12 02:07:30 +0000580public:
John Thompson94faa4d2013-07-26 23:56:42 +0000581 ModularizeFrontendActionFactory(EntityMap &Entities,
582 PreprocessorTracker &preprocessorTracker)
583 : Entities(Entities), PPTracker(preprocessorTracker) {}
John Thompson4f8ba652013-03-12 02:07:30 +0000584
585 virtual CollectEntitiesAction *create() {
John Thompson94faa4d2013-07-26 23:56:42 +0000586 return new CollectEntitiesAction(Entities, PPTracker);
John Thompson4f8ba652013-03-12 02:07:30 +0000587 }
John Thompson161381e2013-06-27 18:52:23 +0000588
John Thompson1f67ccb2013-03-12 18:51:47 +0000589private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000590 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000591 PreprocessorTracker &PPTracker;
John Thompson4f8ba652013-03-12 02:07:30 +0000592};
593
John Thompsonbb0a3b02013-08-09 13:52:09 +0000594int main(int Argc, const char **Argv) {
John Thompsona2de1082013-03-26 01:17:48 +0000595
596 // This causes options to be parsed.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000597 cl::ParseCommandLineOptions(Argc, Argv, "modularize.\n");
John Thompsona2de1082013-03-26 01:17:48 +0000598
599 // No go if we have no header list file.
600 if (ListFileName.size() == 0) {
601 cl::PrintHelpMessage();
John Thompsonea6c8db2013-03-27 21:23:21 +0000602 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000603 }
John Thompsona2de1082013-03-26 01:17:48 +0000604
John Thompson7d0213c2013-09-04 20:46:24 +0000605 // Get header file names and dependencies.
John Thompsonf5db45b2013-03-27 01:02:46 +0000606 SmallVector<std::string, 32> Headers;
John Thompson7d0213c2013-09-04 20:46:24 +0000607 DependencyMap Dependencies;
608 if (error_code EC = getHeaderFileNames(Headers, Dependencies, ListFileName,
609 HeaderPrefix)) {
John Thompsonbb0a3b02013-08-09 13:52:09 +0000610 errs() << Argv[0] << ": error: Unable to get header list '" << ListFileName
611 << "': " << EC.message() << '\n';
John Thompsonea6c8db2013-03-27 21:23:21 +0000612 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000613 }
John Thompsona2de1082013-03-26 01:17:48 +0000614
John Thompson4f8ba652013-03-12 02:07:30 +0000615 // Create the compilation database.
John Thompsona2de1082013-03-26 01:17:48 +0000616 SmallString<256> PathBuf;
John Thompsonf5db45b2013-03-27 01:02:46 +0000617 sys::fs::current_path(PathBuf);
618 OwningPtr<CompilationDatabase> Compilations;
619 Compilations.reset(
620 new FixedCompilationDatabase(Twine(PathBuf), CC1Arguments));
John Thompsona2de1082013-03-26 01:17:48 +0000621
John Thompson94faa4d2013-07-26 23:56:42 +0000622 // Create preprocessor tracker, to watch for macro and conditional problems.
623 OwningPtr<PreprocessorTracker> PPTracker(PreprocessorTracker::create());
624
John Thompson4f8ba652013-03-12 02:07:30 +0000625 // Parse all of the headers, detecting duplicates.
626 EntityMap Entities;
627 ClangTool Tool(*Compilations, Headers);
John Thompson7d0213c2013-09-04 20:46:24 +0000628 Tool.appendArgumentsAdjuster(new AddDependenciesAdjuster(Dependencies));
John Thompson94faa4d2013-07-26 23:56:42 +0000629 int HadErrors =
630 Tool.run(new ModularizeFrontendActionFactory(Entities, *PPTracker));
John Thompsonce601e22013-03-14 01:41:29 +0000631
John Thompson4e4d9b32013-03-28 01:20:19 +0000632 // Create a place to save duplicate entity locations, separate bins per kind.
633 typedef SmallVector<Location, 8> LocationArray;
John Thompson52d98862013-03-28 18:38:43 +0000634 typedef SmallVector<LocationArray, Entry::EK_NumberOfKinds> EntryBinArray;
John Thompson4e4d9b32013-03-28 01:20:19 +0000635 EntryBinArray EntryBins;
John Thompsonbb0a3b02013-08-09 13:52:09 +0000636 int KindIndex;
637 for (KindIndex = 0; KindIndex < Entry::EK_NumberOfKinds; ++KindIndex) {
638 LocationArray Array;
639 EntryBins.push_back(Array);
Michael Gottesman4b249212013-03-28 06:07:15 +0000640 }
John Thompson4e4d9b32013-03-28 01:20:19 +0000641
John Thompson4f8ba652013-03-12 02:07:30 +0000642 // Check for the same entity being defined in multiple places.
643 for (EntityMap::iterator E = Entities.begin(), EEnd = Entities.end();
644 E != EEnd; ++E) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000645 // If only one occurance, exit early.
646 if (E->second.size() == 1)
647 continue;
648 // Clear entity locations.
649 for (EntryBinArray::iterator CI = EntryBins.begin(), CE = EntryBins.end();
650 CI != CE; ++CI) {
John Thompson52d98862013-03-28 18:38:43 +0000651 CI->clear();
John Thompson4e4d9b32013-03-28 01:20:19 +0000652 }
653 // Walk the entities of a single name, collecting the locations,
654 // separated into separate bins.
John Thompson4f8ba652013-03-12 02:07:30 +0000655 for (unsigned I = 0, N = E->second.size(); I != N; ++I) {
John Thompson52d98862013-03-28 18:38:43 +0000656 EntryBins[E->second[I].Kind].push_back(E->second[I].Loc);
John Thompson4e4d9b32013-03-28 01:20:19 +0000657 }
658 // Report any duplicate entity definition errors.
John Thompsonbb0a3b02013-08-09 13:52:09 +0000659 int KindIndex = 0;
John Thompson4e4d9b32013-03-28 01:20:19 +0000660 for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end();
John Thompsonbb0a3b02013-08-09 13:52:09 +0000661 DI != DE; ++DI, ++KindIndex) {
662 int ECount = DI->size();
John Thompson4e4d9b32013-03-28 01:20:19 +0000663 // If only 1 occurance, skip;
John Thompsonbb0a3b02013-08-09 13:52:09 +0000664 if (ECount <= 1)
John Thompson4f8ba652013-03-12 02:07:30 +0000665 continue;
John Thompson52d98862013-03-28 18:38:43 +0000666 LocationArray::iterator FI = DI->begin();
John Thompsonbb0a3b02013-08-09 13:52:09 +0000667 StringRef kindName = Entry::getKindName((Entry::EntryKind)KindIndex);
John Thompson4e4d9b32013-03-28 01:20:19 +0000668 errs() << "error: " << kindName << " '" << E->first()
669 << "' defined at multiple locations:\n";
John Thompson52d98862013-03-28 18:38:43 +0000670 for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000671 errs() << " " << FI->File->getName() << ":" << FI->Line << ":"
672 << FI->Column << "\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000673 }
John Thompson4f8ba652013-03-12 02:07:30 +0000674 HadErrors = 1;
675 }
676 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000677
John Thompson94faa4d2013-07-26 23:56:42 +0000678 // Complain about macro instance in header files that differ based on how
679 // they are included.
680 if (PPTracker->reportInconsistentMacros(errs()))
681 HadErrors = 1;
682
683 // Complain about preprocessor conditional directives in header files that
684 // differ based on how they are included.
685 if (PPTracker->reportInconsistentConditionals(errs()))
686 HadErrors = 1;
687
John Thompson4f8ba652013-03-12 02:07:30 +0000688 // Complain about any headers that have contents that differ based on how
689 // they are included.
John Thompsonce601e22013-03-14 01:41:29 +0000690 // FIXME: Could we provide information about which preprocessor conditionals
691 // are involved?
John Thompsonf5db45b2013-03-27 01:02:46 +0000692 for (DenseMap<const FileEntry *, HeaderContents>::iterator
693 H = Entities.HeaderContentMismatches.begin(),
694 HEnd = Entities.HeaderContentMismatches.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000695 H != HEnd; ++H) {
696 if (H->second.empty()) {
John Thompsonf5db45b2013-03-27 01:02:46 +0000697 errs() << "internal error: phantom header content mismatch\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000698 continue;
699 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000700
John Thompson4f8ba652013-03-12 02:07:30 +0000701 HadErrors = 1;
John Thompsonf5db45b2013-03-27 01:02:46 +0000702 errs() << "error: header '" << H->first->getName()
John Thompson94faa4d2013-07-26 23:56:42 +0000703 << "' has different contents depending on how it was included.\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000704 for (unsigned I = 0, N = H->second.size(); I != N; ++I) {
John Thompson161381e2013-06-27 18:52:23 +0000705 errs() << "note: '" << H->second[I].Name << "' in "
706 << H->second[I].Loc.File->getName() << " at "
707 << H->second[I].Loc.Line << ":" << H->second[I].Loc.Column
708 << " not always provided\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000709 }
710 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000711
John Thompson4f8ba652013-03-12 02:07:30 +0000712 return HadErrors;
713}