blob: ea7d2d598df0e9af0bad9eea254ee5f54a841025 [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 Thompson4f8ba652013-03-12 02:07:30 +000021// Modularize also accepts regular front-end arguments.
22//
John Thompsonf5db45b2013-03-27 01:02:46 +000023// Usage: modularize [-prefix (optional header path prefix)]
John Thompsona2de1082013-03-26 01:17:48 +000024// (include-files_list) [(front-end-options) ...]
25//
John Thompsona44f85a2013-04-15 22:32:28 +000026// Note that unless a "-prefix (header path)" option is specified,
John Thompsona2de1082013-03-26 01:17:48 +000027// non-absolute file paths in the header list file will be relative
28// to the header list file directory. Use -prefix to specify a different
29// directory.
John Thompson4f8ba652013-03-12 02:07:30 +000030//
John Thompsonfd8ca382013-03-27 19:31:22 +000031// Note that by default, the underlying Clang front end assumes .h files
32// contain C source. If your .h files in the file list contain C++ source,
John Thompsonea6c8db2013-03-27 21:23:21 +000033// you should append the following to your command lines: -x c++
John Thompsonfd8ca382013-03-27 19:31:22 +000034//
John Thompson4f8ba652013-03-12 02:07:30 +000035// Modularize will do normal parsing, reporting normal errors and warnings,
36// but will also report special error messages like the following:
37//
John Thompson7c6e79f32013-07-29 19:07:00 +000038// error: '(symbol)' defined at multiple locations:
39// (file):(row):(column)
40// (file):(row):(column)
John Thompson4f8ba652013-03-12 02:07:30 +000041//
John Thompsondc118272013-07-29 21:59:41 +000042// error: header '(file)' has different contents depending on how it was
John Thompson7c6e79f32013-07-29 19:07:00 +000043// included
John Thompson4f8ba652013-03-12 02:07:30 +000044//
45// The latter might be followed by messages like the following:
46//
John Thompson7c6e79f32013-07-29 19:07:00 +000047// note: '(symbol)' in (file) at (row):(column) not always provided
John Thompson4f8ba652013-03-12 02:07:30 +000048//
John Thompson7c6e79f32013-07-29 19:07:00 +000049// Checks will also be performed for macro expansions, defined(macro)
50// expressions, and preprocessor conditional directives that evaluate
51// inconsistently, and can produce error messages like the following:
52//
53// (...)/SubHeader.h:11:5:
54// #if SYMBOL == 1
55// ^
56// error: Macro instance 'SYMBOL' has different values in this header,
57// depending on how it was included.
58// 'SYMBOL' expanded to: '1' with respect to these inclusion paths:
59// (...)/Header1.h
60// (...)/SubHeader.h
61// (...)/SubHeader.h:3:9:
62// #define SYMBOL 1
63// ^
64// Macro defined here.
65// 'SYMBOL' expanded to: '2' with respect to these inclusion paths:
66// (...)/Header2.h
67// (...)/SubHeader.h
68// (...)/SubHeader.h:7:9:
69// #define SYMBOL 2
70// ^
71// Macro defined here.
72//
73// See PreprocessorTracker.cpp for additional details.
John Thompson181ea2e2013-08-08 00:00:10 +000074//
75// Current problems:
76//
77// Modularize has problems with C++:
78//
79// 1. Modularize doesn't distinguish class of the same name in
80// different namespaces. The result is erroneous duplicate definition errors.
81//
82// 2. Modularize doesn't distinguish between a regular class and a template
83// class of the same name.
84//
85// Other problems:
86//
87// 3. There seem to be a lot of spurious "not always provided" messages,
88// and many duplicates of these.
John Thompson7c6e79f32013-07-29 19:07:00 +000089//
John Thompsonce601e22013-03-14 01:41:29 +000090// Future directions:
91//
92// Basically, we want to add new checks for whatever we can check with respect
93// to checking headers for module'ability.
94//
95// Some ideas:
96//
John Thompson181ea2e2013-08-08 00:00:10 +000097// 1. Fix the C++ and other problems.
98//
99// 2. Add options to disable any of the checks, in case
100// there is some problem with them, or the messages get too verbose.
101//
102// 3. Try to figure out the preprocessor conditional directives that
John Thompson7c6e79f32013-07-29 19:07:00 +0000103// contribute to problems and tie them to the inconsistent definitions.
John Thompsonce601e22013-03-14 01:41:29 +0000104//
John Thompson181ea2e2013-08-08 00:00:10 +0000105// 4. Check for correct and consistent usage of extern "C" {} and other
John Thompsonce601e22013-03-14 01:41:29 +0000106// directives. Warn about #include inside extern "C" {}.
107//
John Thompson181ea2e2013-08-08 00:00:10 +0000108// 5. What else?
John Thompsonce601e22013-03-14 01:41:29 +0000109//
110// General clean-up and refactoring:
111//
112// 1. The Location class seems to be something that we might
113// want to design to be applicable to a wider range of tools, and stick it
114// somewhere into Tooling/ in mainline
115//
John Thompson4f8ba652013-03-12 02:07:30 +0000116//===----------------------------------------------------------------------===//
John Thompsonf5db45b2013-03-27 01:02:46 +0000117
John Thompsond977c1e2013-03-27 18:34:38 +0000118#include "clang/AST/ASTConsumer.h"
119#include "clang/AST/ASTContext.h"
120#include "clang/AST/RecursiveASTVisitor.h"
121#include "clang/Basic/SourceManager.h"
122#include "clang/Frontend/CompilerInstance.h"
123#include "clang/Frontend/FrontendActions.h"
124#include "clang/Lex/Preprocessor.h"
125#include "clang/Tooling/CompilationDatabase.h"
126#include "clang/Tooling/Tooling.h"
127#include "llvm/ADT/OwningPtr.h"
128#include "llvm/ADT/StringRef.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000129#include "llvm/Config/config.h"
John Thompsona2de1082013-03-26 01:17:48 +0000130#include "llvm/Support/CommandLine.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000131#include "llvm/Support/FileSystem.h"
John Thompsonf5db45b2013-03-27 01:02:46 +0000132#include "llvm/Support/MemoryBuffer.h"
John Thompsona2de1082013-03-26 01:17:48 +0000133#include "llvm/Support/Path.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000134#include <algorithm>
John Thompsond977c1e2013-03-27 18:34:38 +0000135#include <fstream>
John Thompson4f8ba652013-03-12 02:07:30 +0000136#include <iterator>
John Thompsond977c1e2013-03-27 18:34:38 +0000137#include <string>
138#include <vector>
John Thompson94faa4d2013-07-26 23:56:42 +0000139#include "PreprocessorTracker.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000140
141using namespace clang::tooling;
142using namespace clang;
John Thompsona2de1082013-03-26 01:17:48 +0000143using namespace llvm;
John Thompson94faa4d2013-07-26 23:56:42 +0000144using namespace Modularize;
John Thompson4f8ba652013-03-12 02:07:30 +0000145
John Thompsonea6c8db2013-03-27 21:23:21 +0000146// Option to specify a file name for a list of header files to check.
John Thompsonb809dfc2013-07-19 14:19:31 +0000147cl::opt<std::string>
148ListFileName(cl::Positional,
149 cl::desc("<name of file containing list of headers to check>"));
John Thompsonea6c8db2013-03-27 21:23:21 +0000150
151// Collect all other arguments, which will be passed to the front end.
John Thompson161381e2013-06-27 18:52:23 +0000152cl::list<std::string>
John Thompsonb809dfc2013-07-19 14:19:31 +0000153CC1Arguments(cl::ConsumeAfter,
154 cl::desc("<arguments to be passed to front end>..."));
John Thompsonea6c8db2013-03-27 21:23:21 +0000155
156// Option to specify a prefix to be prepended to the header names.
157cl::opt<std::string> HeaderPrefix(
158 "prefix", cl::init(""),
159 cl::desc(
160 "Prepend header file paths with this prefix."
161 " If not specified,"
162 " the files are considered to be relative to the header list file."));
163
164// Read the header list file and collect the header file names.
John Thompson54c83692013-06-18 19:56:05 +0000165error_code getHeaderFileNames(SmallVectorImpl<std::string> &headerFileNames,
John Thompsonea6c8db2013-03-27 21:23:21 +0000166 StringRef listFileName, StringRef headerPrefix) {
167
168 // By default, use the path component of the list file name.
169 SmallString<256> headerDirectory(listFileName);
170 sys::path::remove_filename(headerDirectory);
171
172 // Get the prefix if we have one.
173 if (headerPrefix.size() != 0)
174 headerDirectory = headerPrefix;
175
176 // Read the header list file into a buffer.
177 OwningPtr<MemoryBuffer> listBuffer;
John Thompson26b567a2013-06-19 20:35:50 +0000178 if (error_code ec = MemoryBuffer::getFile(listFileName, listBuffer)) {
John Thompsonea6c8db2013-03-27 21:23:21 +0000179 return ec;
180 }
181
182 // Parse the header list into strings.
183 SmallVector<StringRef, 32> strings;
184 listBuffer->getBuffer().split(strings, "\n", -1, false);
185
186 // Collect the header file names from the string list.
187 for (SmallVectorImpl<StringRef>::iterator I = strings.begin(),
188 E = strings.end();
189 I != E; ++I) {
190 StringRef line = (*I).trim();
191 // Ignore comments and empty lines.
192 if (line.empty() || (line[0] == '#'))
193 continue;
194 SmallString<256> headerFileName;
195 // Prepend header file name prefix if it's not absolute.
196 if (sys::path::is_absolute(line))
197 headerFileName = line;
198 else {
199 headerFileName = headerDirectory;
200 sys::path::append(headerFileName, line);
201 }
202 // Save the resulting header file path.
203 headerFileNames.push_back(headerFileName.str());
204 }
205
206 return error_code::success();
207}
208
John Thompsonce601e22013-03-14 01:41:29 +0000209// FIXME: The Location class seems to be something that we might
210// want to design to be applicable to a wider range of tools, and stick it
211// somewhere into Tooling/ in mainline
John Thompson4f8ba652013-03-12 02:07:30 +0000212struct Location {
213 const FileEntry *File;
214 unsigned Line, Column;
John Thompsonf5db45b2013-03-27 01:02:46 +0000215
216 Location() : File(), Line(), Column() {}
217
John Thompson4f8ba652013-03-12 02:07:30 +0000218 Location(SourceManager &SM, SourceLocation Loc) : File(), Line(), Column() {
219 Loc = SM.getExpansionLoc(Loc);
220 if (Loc.isInvalid())
221 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000222
John Thompson4f8ba652013-03-12 02:07:30 +0000223 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(Loc);
224 File = SM.getFileEntryForID(Decomposed.first);
225 if (!File)
226 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000227
John Thompson4f8ba652013-03-12 02:07:30 +0000228 Line = SM.getLineNumber(Decomposed.first, Decomposed.second);
229 Column = SM.getColumnNumber(Decomposed.first, Decomposed.second);
230 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000231
John Thompson4f8ba652013-03-12 02:07:30 +0000232 operator bool() const { return File != 0; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000233
John Thompson4f8ba652013-03-12 02:07:30 +0000234 friend bool operator==(const Location &X, const Location &Y) {
235 return X.File == Y.File && X.Line == Y.Line && X.Column == Y.Column;
236 }
237
238 friend bool operator!=(const Location &X, const Location &Y) {
239 return !(X == Y);
240 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000241
John Thompson4f8ba652013-03-12 02:07:30 +0000242 friend bool operator<(const Location &X, const Location &Y) {
243 if (X.File != Y.File)
244 return X.File < Y.File;
245 if (X.Line != Y.Line)
246 return X.Line < Y.Line;
247 return X.Column < Y.Column;
248 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000249 friend bool operator>(const Location &X, const Location &Y) { return Y < X; }
John Thompson4f8ba652013-03-12 02:07:30 +0000250 friend bool operator<=(const Location &X, const Location &Y) {
251 return !(Y < X);
252 }
253 friend bool operator>=(const Location &X, const Location &Y) {
254 return !(X < Y);
255 }
John Thompson4f8ba652013-03-12 02:07:30 +0000256};
257
John Thompson4f8ba652013-03-12 02:07:30 +0000258struct Entry {
John Thompson52d98862013-03-28 18:38:43 +0000259 enum EntryKind {
260 EK_Tag,
261 EK_Value,
262 EK_Macro,
263
264 EK_NumberOfKinds
John Thompson4f8ba652013-03-12 02:07:30 +0000265 } Kind;
John Thompsonf5db45b2013-03-27 01:02:46 +0000266
John Thompson4f8ba652013-03-12 02:07:30 +0000267 Location Loc;
John Thompson4e4d9b32013-03-28 01:20:19 +0000268
269 StringRef getKindName() { return getKindName(Kind); }
John Thompson52d98862013-03-28 18:38:43 +0000270 static StringRef getKindName(EntryKind kind);
John Thompson4f8ba652013-03-12 02:07:30 +0000271};
272
John Thompson4e4d9b32013-03-28 01:20:19 +0000273// Return a string representing the given kind.
John Thompson52d98862013-03-28 18:38:43 +0000274StringRef Entry::getKindName(Entry::EntryKind kind) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000275 switch (kind) {
John Thompson52d98862013-03-28 18:38:43 +0000276 case EK_Tag:
John Thompson4e4d9b32013-03-28 01:20:19 +0000277 return "tag";
John Thompson52d98862013-03-28 18:38:43 +0000278 case EK_Value:
John Thompson4e4d9b32013-03-28 01:20:19 +0000279 return "value";
John Thompson52d98862013-03-28 18:38:43 +0000280 case EK_Macro:
John Thompson4e4d9b32013-03-28 01:20:19 +0000281 return "macro";
John Thompson52d98862013-03-28 18:38:43 +0000282 case EK_NumberOfKinds:
John Thompson4e4d9b32013-03-28 01:20:19 +0000283 break;
John Thompson4e4d9b32013-03-28 01:20:19 +0000284 }
David Blaikiec66c07d2013-03-28 02:30:37 +0000285 llvm_unreachable("invalid Entry kind");
John Thompson4e4d9b32013-03-28 01:20:19 +0000286}
287
John Thompson4f8ba652013-03-12 02:07:30 +0000288struct HeaderEntry {
289 std::string Name;
290 Location Loc;
John Thompsonf5db45b2013-03-27 01:02:46 +0000291
John Thompson4f8ba652013-03-12 02:07:30 +0000292 friend bool operator==(const HeaderEntry &X, const HeaderEntry &Y) {
293 return X.Loc == Y.Loc && X.Name == Y.Name;
294 }
295 friend bool operator!=(const HeaderEntry &X, const HeaderEntry &Y) {
296 return !(X == Y);
297 }
298 friend bool operator<(const HeaderEntry &X, const HeaderEntry &Y) {
299 return X.Loc < Y.Loc || (X.Loc == Y.Loc && X.Name < Y.Name);
300 }
301 friend bool operator>(const HeaderEntry &X, const HeaderEntry &Y) {
302 return Y < X;
303 }
304 friend bool operator<=(const HeaderEntry &X, const HeaderEntry &Y) {
305 return !(Y < X);
306 }
307 friend bool operator>=(const HeaderEntry &X, const HeaderEntry &Y) {
308 return !(X < Y);
309 }
310};
311
312typedef std::vector<HeaderEntry> HeaderContents;
313
John Thompsonf5db45b2013-03-27 01:02:46 +0000314class EntityMap : public StringMap<SmallVector<Entry, 2> > {
John Thompson4f8ba652013-03-12 02:07:30 +0000315public:
John Thompsonf5db45b2013-03-27 01:02:46 +0000316 DenseMap<const FileEntry *, HeaderContents> HeaderContentMismatches;
317
John Thompson52d98862013-03-28 18:38:43 +0000318 void add(const std::string &Name, enum Entry::EntryKind Kind, Location Loc) {
John Thompson4f8ba652013-03-12 02:07:30 +0000319 // Record this entity in its header.
320 HeaderEntry HE = { Name, Loc };
321 CurHeaderContents[Loc.File].push_back(HE);
John Thompsonf5db45b2013-03-27 01:02:46 +0000322
John Thompson4f8ba652013-03-12 02:07:30 +0000323 // Check whether we've seen this entry before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000324 SmallVector<Entry, 2> &Entries = (*this)[Name];
John Thompson4f8ba652013-03-12 02:07:30 +0000325 for (unsigned I = 0, N = Entries.size(); I != N; ++I) {
326 if (Entries[I].Kind == Kind && Entries[I].Loc == Loc)
327 return;
328 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000329
John Thompson4f8ba652013-03-12 02:07:30 +0000330 // We have not seen this entry before; record it.
331 Entry E = { Kind, Loc };
332 Entries.push_back(E);
333 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000334
John Thompson4f8ba652013-03-12 02:07:30 +0000335 void mergeCurHeaderContents() {
John Thompsonf5db45b2013-03-27 01:02:46 +0000336 for (DenseMap<const FileEntry *, HeaderContents>::iterator
337 H = CurHeaderContents.begin(),
338 HEnd = CurHeaderContents.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000339 H != HEnd; ++H) {
340 // Sort contents.
341 std::sort(H->second.begin(), H->second.end());
342
343 // Check whether we've seen this header before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000344 DenseMap<const FileEntry *, HeaderContents>::iterator KnownH =
345 AllHeaderContents.find(H->first);
John Thompson4f8ba652013-03-12 02:07:30 +0000346 if (KnownH == AllHeaderContents.end()) {
347 // We haven't seen this header before; record its contents.
348 AllHeaderContents.insert(*H);
349 continue;
350 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000351
John Thompson4f8ba652013-03-12 02:07:30 +0000352 // If the header contents are the same, we're done.
353 if (H->second == KnownH->second)
354 continue;
John Thompsonf5db45b2013-03-27 01:02:46 +0000355
John Thompson4f8ba652013-03-12 02:07:30 +0000356 // Determine what changed.
John Thompsonf5db45b2013-03-27 01:02:46 +0000357 std::set_symmetric_difference(
358 H->second.begin(), H->second.end(), KnownH->second.begin(),
359 KnownH->second.end(),
360 std::back_inserter(HeaderContentMismatches[H->first]));
John Thompson4f8ba652013-03-12 02:07:30 +0000361 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000362
John Thompson4f8ba652013-03-12 02:07:30 +0000363 CurHeaderContents.clear();
364 }
John Thompson161381e2013-06-27 18:52:23 +0000365
John Thompson1f67ccb2013-03-12 18:51:47 +0000366private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000367 DenseMap<const FileEntry *, HeaderContents> CurHeaderContents;
368 DenseMap<const FileEntry *, HeaderContents> AllHeaderContents;
John Thompson4f8ba652013-03-12 02:07:30 +0000369};
370
John Thompson161381e2013-06-27 18:52:23 +0000371class CollectEntitiesVisitor
372 : public RecursiveASTVisitor<CollectEntitiesVisitor> {
John Thompson4f8ba652013-03-12 02:07:30 +0000373public:
374 CollectEntitiesVisitor(SourceManager &SM, EntityMap &Entities)
John Thompsonf5db45b2013-03-27 01:02:46 +0000375 : SM(SM), Entities(Entities) {}
376
John Thompson4f8ba652013-03-12 02:07:30 +0000377 bool TraverseStmt(Stmt *S) { return true; }
378 bool TraverseType(QualType T) { return true; }
379 bool TraverseTypeLoc(TypeLoc TL) { return true; }
380 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000381 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
382 return true;
383 }
384 bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo) {
385 return true;
386 }
John Thompson4f8ba652013-03-12 02:07:30 +0000387 bool TraverseTemplateName(TemplateName Template) { return true; }
388 bool TraverseTemplateArgument(const TemplateArgument &Arg) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000389 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
390 return true;
391 }
John Thompson4f8ba652013-03-12 02:07:30 +0000392 bool TraverseTemplateArguments(const TemplateArgument *Args,
John Thompsonf5db45b2013-03-27 01:02:46 +0000393 unsigned NumArgs) {
394 return true;
395 }
John Thompson4f8ba652013-03-12 02:07:30 +0000396 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; }
397 bool TraverseLambdaCapture(LambdaExpr::Capture C) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000398
John Thompson4f8ba652013-03-12 02:07:30 +0000399 bool VisitNamedDecl(NamedDecl *ND) {
400 // We only care about file-context variables.
401 if (!ND->getDeclContext()->isFileContext())
402 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000403
John Thompson4f8ba652013-03-12 02:07:30 +0000404 // Skip declarations that tend to be properly multiply-declared.
405 if (isa<NamespaceDecl>(ND) || isa<UsingDirectiveDecl>(ND) ||
John Thompsonf5db45b2013-03-27 01:02:46 +0000406 isa<NamespaceAliasDecl>(ND) ||
407 isa<ClassTemplateSpecializationDecl>(ND) || isa<UsingDecl>(ND) ||
408 isa<UsingShadowDecl>(ND) || isa<FunctionDecl>(ND) ||
409 isa<FunctionTemplateDecl>(ND) ||
John Thompson4f8ba652013-03-12 02:07:30 +0000410 (isa<TagDecl>(ND) &&
411 !cast<TagDecl>(ND)->isThisDeclarationADefinition()))
412 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000413
John Thompson4f8ba652013-03-12 02:07:30 +0000414 std::string Name = ND->getNameAsString();
415 if (Name.empty())
416 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000417
John Thompson4f8ba652013-03-12 02:07:30 +0000418 Location Loc(SM, ND->getLocation());
419 if (!Loc)
420 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000421
John Thompson52d98862013-03-28 18:38:43 +0000422 Entities.add(Name, isa<TagDecl>(ND) ? Entry::EK_Tag : Entry::EK_Value, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000423 return true;
424 }
John Thompson161381e2013-06-27 18:52:23 +0000425
John Thompson1f67ccb2013-03-12 18:51:47 +0000426private:
427 SourceManager &SM;
428 EntityMap &Entities;
John Thompson4f8ba652013-03-12 02:07:30 +0000429};
430
431class CollectEntitiesConsumer : public ASTConsumer {
John Thompson4f8ba652013-03-12 02:07:30 +0000432public:
John Thompson94faa4d2013-07-26 23:56:42 +0000433 CollectEntitiesConsumer(EntityMap &Entities,
434 PreprocessorTracker &preprocessorTracker,
435 Preprocessor &PP, StringRef InFile)
436 : Entities(Entities), PPTracker(preprocessorTracker), PP(PP) {
437 PPTracker.handlePreprocessorEntry(PP, InFile);
438 }
439
440 ~CollectEntitiesConsumer() { PPTracker.handlePreprocessorExit(); }
John Thompsonf5db45b2013-03-27 01:02:46 +0000441
John Thompson4f8ba652013-03-12 02:07:30 +0000442 virtual void HandleTranslationUnit(ASTContext &Ctx) {
443 SourceManager &SM = Ctx.getSourceManager();
John Thompsonf5db45b2013-03-27 01:02:46 +0000444
John Thompson4f8ba652013-03-12 02:07:30 +0000445 // Collect declared entities.
446 CollectEntitiesVisitor(SM, Entities)
John Thompsonf5db45b2013-03-27 01:02:46 +0000447 .TraverseDecl(Ctx.getTranslationUnitDecl());
448
John Thompson4f8ba652013-03-12 02:07:30 +0000449 // Collect macro definitions.
450 for (Preprocessor::macro_iterator M = PP.macro_begin(),
John Thompsonf5db45b2013-03-27 01:02:46 +0000451 MEnd = PP.macro_end();
John Thompson4f8ba652013-03-12 02:07:30 +0000452 M != MEnd; ++M) {
453 Location Loc(SM, M->second->getLocation());
454 if (!Loc)
455 continue;
456
John Thompson52d98862013-03-28 18:38:43 +0000457 Entities.add(M->first->getName().str(), Entry::EK_Macro, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000458 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000459
John Thompson4f8ba652013-03-12 02:07:30 +0000460 // Merge header contents.
461 Entities.mergeCurHeaderContents();
462 }
John Thompson161381e2013-06-27 18:52:23 +0000463
John Thompson1f67ccb2013-03-12 18:51:47 +0000464private:
465 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000466 PreprocessorTracker &PPTracker;
John Thompson1f67ccb2013-03-12 18:51:47 +0000467 Preprocessor &PP;
John Thompson4f8ba652013-03-12 02:07:30 +0000468};
469
470class CollectEntitiesAction : public SyntaxOnlyAction {
John Thompson1f67ccb2013-03-12 18:51:47 +0000471public:
John Thompson94faa4d2013-07-26 23:56:42 +0000472 CollectEntitiesAction(EntityMap &Entities,
473 PreprocessorTracker &preprocessorTracker)
474 : Entities(Entities), PPTracker(preprocessorTracker) {}
John Thompson161381e2013-06-27 18:52:23 +0000475
John Thompson4f8ba652013-03-12 02:07:30 +0000476protected:
John Thompson161381e2013-06-27 18:52:23 +0000477 virtual clang::ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
478 StringRef InFile) {
John Thompson94faa4d2013-07-26 23:56:42 +0000479 return new CollectEntitiesConsumer(Entities, PPTracker,
480 CI.getPreprocessor(), InFile);
John Thompson4f8ba652013-03-12 02:07:30 +0000481 }
John Thompson161381e2013-06-27 18:52:23 +0000482
John Thompson1f67ccb2013-03-12 18:51:47 +0000483private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000484 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000485 PreprocessorTracker &PPTracker;
John Thompson4f8ba652013-03-12 02:07:30 +0000486};
487
488class ModularizeFrontendActionFactory : public FrontendActionFactory {
John Thompson4f8ba652013-03-12 02:07:30 +0000489public:
John Thompson94faa4d2013-07-26 23:56:42 +0000490 ModularizeFrontendActionFactory(EntityMap &Entities,
491 PreprocessorTracker &preprocessorTracker)
492 : Entities(Entities), PPTracker(preprocessorTracker) {}
John Thompson4f8ba652013-03-12 02:07:30 +0000493
494 virtual CollectEntitiesAction *create() {
John Thompson94faa4d2013-07-26 23:56:42 +0000495 return new CollectEntitiesAction(Entities, PPTracker);
John Thompson4f8ba652013-03-12 02:07:30 +0000496 }
John Thompson161381e2013-06-27 18:52:23 +0000497
John Thompson1f67ccb2013-03-12 18:51:47 +0000498private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000499 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000500 PreprocessorTracker &PPTracker;
John Thompson4f8ba652013-03-12 02:07:30 +0000501};
502
503int main(int argc, const char **argv) {
John Thompsona2de1082013-03-26 01:17:48 +0000504
505 // This causes options to be parsed.
506 cl::ParseCommandLineOptions(argc, argv, "modularize.\n");
507
508 // No go if we have no header list file.
509 if (ListFileName.size() == 0) {
510 cl::PrintHelpMessage();
John Thompsonea6c8db2013-03-27 21:23:21 +0000511 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000512 }
John Thompsona2de1082013-03-26 01:17:48 +0000513
John Thompsonea6c8db2013-03-27 21:23:21 +0000514 // Get header file names.
John Thompsonf5db45b2013-03-27 01:02:46 +0000515 SmallVector<std::string, 32> Headers;
John Thompson54c83692013-06-18 19:56:05 +0000516 if (error_code ec = getHeaderFileNames(Headers, ListFileName, HeaderPrefix)) {
John Thompsonea6c8db2013-03-27 21:23:21 +0000517 errs() << argv[0] << ": error: Unable to get header list '" << ListFileName
518 << "': " << ec.message() << '\n';
519 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000520 }
John Thompsona2de1082013-03-26 01:17:48 +0000521
John Thompson4f8ba652013-03-12 02:07:30 +0000522 // Create the compilation database.
John Thompsona2de1082013-03-26 01:17:48 +0000523 SmallString<256> PathBuf;
John Thompsonf5db45b2013-03-27 01:02:46 +0000524 sys::fs::current_path(PathBuf);
525 OwningPtr<CompilationDatabase> Compilations;
526 Compilations.reset(
527 new FixedCompilationDatabase(Twine(PathBuf), CC1Arguments));
John Thompsona2de1082013-03-26 01:17:48 +0000528
John Thompson94faa4d2013-07-26 23:56:42 +0000529 // Create preprocessor tracker, to watch for macro and conditional problems.
530 OwningPtr<PreprocessorTracker> PPTracker(PreprocessorTracker::create());
531
John Thompson4f8ba652013-03-12 02:07:30 +0000532 // Parse all of the headers, detecting duplicates.
533 EntityMap Entities;
534 ClangTool Tool(*Compilations, Headers);
John Thompson94faa4d2013-07-26 23:56:42 +0000535 int HadErrors =
536 Tool.run(new ModularizeFrontendActionFactory(Entities, *PPTracker));
John Thompsonce601e22013-03-14 01:41:29 +0000537
John Thompson4e4d9b32013-03-28 01:20:19 +0000538 // Create a place to save duplicate entity locations, separate bins per kind.
539 typedef SmallVector<Location, 8> LocationArray;
John Thompson52d98862013-03-28 18:38:43 +0000540 typedef SmallVector<LocationArray, Entry::EK_NumberOfKinds> EntryBinArray;
John Thompson4e4d9b32013-03-28 01:20:19 +0000541 EntryBinArray EntryBins;
Michael Gottesman4b249212013-03-28 06:07:15 +0000542 int kindIndex;
John Thompson52d98862013-03-28 18:38:43 +0000543 for (kindIndex = 0; kindIndex < Entry::EK_NumberOfKinds; ++kindIndex) {
544 LocationArray array;
545 EntryBins.push_back(array);
Michael Gottesman4b249212013-03-28 06:07:15 +0000546 }
John Thompson4e4d9b32013-03-28 01:20:19 +0000547
John Thompson4f8ba652013-03-12 02:07:30 +0000548 // Check for the same entity being defined in multiple places.
549 for (EntityMap::iterator E = Entities.begin(), EEnd = Entities.end();
550 E != EEnd; ++E) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000551 // If only one occurance, exit early.
552 if (E->second.size() == 1)
553 continue;
554 // Clear entity locations.
555 for (EntryBinArray::iterator CI = EntryBins.begin(), CE = EntryBins.end();
556 CI != CE; ++CI) {
John Thompson52d98862013-03-28 18:38:43 +0000557 CI->clear();
John Thompson4e4d9b32013-03-28 01:20:19 +0000558 }
559 // Walk the entities of a single name, collecting the locations,
560 // separated into separate bins.
John Thompson4f8ba652013-03-12 02:07:30 +0000561 for (unsigned I = 0, N = E->second.size(); I != N; ++I) {
John Thompson52d98862013-03-28 18:38:43 +0000562 EntryBins[E->second[I].Kind].push_back(E->second[I].Loc);
John Thompson4e4d9b32013-03-28 01:20:19 +0000563 }
564 // Report any duplicate entity definition errors.
565 int kindIndex = 0;
566 for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end();
567 DI != DE; ++DI, ++kindIndex) {
John Thompson52d98862013-03-28 18:38:43 +0000568 int eCount = DI->size();
John Thompson4e4d9b32013-03-28 01:20:19 +0000569 // If only 1 occurance, skip;
570 if (eCount <= 1)
John Thompson4f8ba652013-03-12 02:07:30 +0000571 continue;
John Thompson52d98862013-03-28 18:38:43 +0000572 LocationArray::iterator FI = DI->begin();
John Thompsonb809dfc2013-07-19 14:19:31 +0000573 StringRef kindName = Entry::getKindName((Entry::EntryKind)kindIndex);
John Thompson4e4d9b32013-03-28 01:20:19 +0000574 errs() << "error: " << kindName << " '" << E->first()
575 << "' defined at multiple locations:\n";
John Thompson52d98862013-03-28 18:38:43 +0000576 for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000577 errs() << " " << FI->File->getName() << ":" << FI->Line << ":"
578 << FI->Column << "\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000579 }
John Thompson4f8ba652013-03-12 02:07:30 +0000580 HadErrors = 1;
581 }
582 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000583
John Thompson94faa4d2013-07-26 23:56:42 +0000584 // Complain about macro instance in header files that differ based on how
585 // they are included.
586 if (PPTracker->reportInconsistentMacros(errs()))
587 HadErrors = 1;
588
589 // Complain about preprocessor conditional directives in header files that
590 // differ based on how they are included.
591 if (PPTracker->reportInconsistentConditionals(errs()))
592 HadErrors = 1;
593
John Thompson4f8ba652013-03-12 02:07:30 +0000594 // Complain about any headers that have contents that differ based on how
595 // they are included.
John Thompsonce601e22013-03-14 01:41:29 +0000596 // FIXME: Could we provide information about which preprocessor conditionals
597 // are involved?
John Thompsonf5db45b2013-03-27 01:02:46 +0000598 for (DenseMap<const FileEntry *, HeaderContents>::iterator
599 H = Entities.HeaderContentMismatches.begin(),
600 HEnd = Entities.HeaderContentMismatches.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000601 H != HEnd; ++H) {
602 if (H->second.empty()) {
John Thompsonf5db45b2013-03-27 01:02:46 +0000603 errs() << "internal error: phantom header content mismatch\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000604 continue;
605 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000606
John Thompson4f8ba652013-03-12 02:07:30 +0000607 HadErrors = 1;
John Thompsonf5db45b2013-03-27 01:02:46 +0000608 errs() << "error: header '" << H->first->getName()
John Thompson94faa4d2013-07-26 23:56:42 +0000609 << "' has different contents depending on how it was included.\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000610 for (unsigned I = 0, N = H->second.size(); I != N; ++I) {
John Thompson161381e2013-06-27 18:52:23 +0000611 errs() << "note: '" << H->second[I].Name << "' in "
612 << H->second[I].Loc.File->getName() << " at "
613 << H->second[I].Loc.Line << ":" << H->second[I].Loc.Column
614 << " not always provided\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000615 }
616 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000617
John Thompson4f8ba652013-03-12 02:07:30 +0000618 return HadErrors;
619}