blob: 8e0c409269bac2be36daf3e00935c873ed2cef57 [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.
74//
John Thompsonce601e22013-03-14 01:41:29 +000075// Future directions:
76//
77// Basically, we want to add new checks for whatever we can check with respect
78// to checking headers for module'ability.
79//
80// Some ideas:
81//
John Thompson3b1ee2b2013-03-28 02:46:25 +000082// 1. Try to figure out the preprocessor conditional directives that
John Thompson7c6e79f32013-07-29 19:07:00 +000083// contribute to problems and tie them to the inconsistent definitions.
John Thompsonce601e22013-03-14 01:41:29 +000084//
John Thompson3b1ee2b2013-03-28 02:46:25 +000085// 2. Check for correct and consistent usage of extern "C" {} and other
John Thompsonce601e22013-03-14 01:41:29 +000086// directives. Warn about #include inside extern "C" {}.
87//
John Thompson3b1ee2b2013-03-28 02:46:25 +000088// 3. What else?
John Thompsonce601e22013-03-14 01:41:29 +000089//
90// General clean-up and refactoring:
91//
92// 1. The Location class seems to be something that we might
93// want to design to be applicable to a wider range of tools, and stick it
94// somewhere into Tooling/ in mainline
95//
John Thompson4f8ba652013-03-12 02:07:30 +000096//===----------------------------------------------------------------------===//
John Thompsonf5db45b2013-03-27 01:02:46 +000097
John Thompsond977c1e2013-03-27 18:34:38 +000098#include "clang/AST/ASTConsumer.h"
99#include "clang/AST/ASTContext.h"
100#include "clang/AST/RecursiveASTVisitor.h"
101#include "clang/Basic/SourceManager.h"
102#include "clang/Frontend/CompilerInstance.h"
103#include "clang/Frontend/FrontendActions.h"
104#include "clang/Lex/Preprocessor.h"
105#include "clang/Tooling/CompilationDatabase.h"
106#include "clang/Tooling/Tooling.h"
107#include "llvm/ADT/OwningPtr.h"
108#include "llvm/ADT/StringRef.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000109#include "llvm/Config/config.h"
John Thompsona2de1082013-03-26 01:17:48 +0000110#include "llvm/Support/CommandLine.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000111#include "llvm/Support/FileSystem.h"
John Thompsonf5db45b2013-03-27 01:02:46 +0000112#include "llvm/Support/MemoryBuffer.h"
John Thompsona2de1082013-03-26 01:17:48 +0000113#include "llvm/Support/Path.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000114#include <algorithm>
John Thompsond977c1e2013-03-27 18:34:38 +0000115#include <fstream>
John Thompson4f8ba652013-03-12 02:07:30 +0000116#include <iterator>
John Thompsond977c1e2013-03-27 18:34:38 +0000117#include <string>
118#include <vector>
John Thompson94faa4d2013-07-26 23:56:42 +0000119#include "PreprocessorTracker.h"
John Thompson4f8ba652013-03-12 02:07:30 +0000120
121using namespace clang::tooling;
122using namespace clang;
John Thompsona2de1082013-03-26 01:17:48 +0000123using namespace llvm;
John Thompson94faa4d2013-07-26 23:56:42 +0000124using namespace Modularize;
John Thompson4f8ba652013-03-12 02:07:30 +0000125
John Thompsonea6c8db2013-03-27 21:23:21 +0000126// Option to specify a file name for a list of header files to check.
John Thompsonb809dfc2013-07-19 14:19:31 +0000127cl::opt<std::string>
128ListFileName(cl::Positional,
129 cl::desc("<name of file containing list of headers to check>"));
John Thompsonea6c8db2013-03-27 21:23:21 +0000130
131// Collect all other arguments, which will be passed to the front end.
John Thompson161381e2013-06-27 18:52:23 +0000132cl::list<std::string>
John Thompsonb809dfc2013-07-19 14:19:31 +0000133CC1Arguments(cl::ConsumeAfter,
134 cl::desc("<arguments to be passed to front end>..."));
John Thompsonea6c8db2013-03-27 21:23:21 +0000135
136// Option to specify a prefix to be prepended to the header names.
137cl::opt<std::string> HeaderPrefix(
138 "prefix", cl::init(""),
139 cl::desc(
140 "Prepend header file paths with this prefix."
141 " If not specified,"
142 " the files are considered to be relative to the header list file."));
143
144// Read the header list file and collect the header file names.
John Thompson54c83692013-06-18 19:56:05 +0000145error_code getHeaderFileNames(SmallVectorImpl<std::string> &headerFileNames,
John Thompsonea6c8db2013-03-27 21:23:21 +0000146 StringRef listFileName, StringRef headerPrefix) {
147
148 // By default, use the path component of the list file name.
149 SmallString<256> headerDirectory(listFileName);
150 sys::path::remove_filename(headerDirectory);
151
152 // Get the prefix if we have one.
153 if (headerPrefix.size() != 0)
154 headerDirectory = headerPrefix;
155
156 // Read the header list file into a buffer.
157 OwningPtr<MemoryBuffer> listBuffer;
John Thompson26b567a2013-06-19 20:35:50 +0000158 if (error_code ec = MemoryBuffer::getFile(listFileName, listBuffer)) {
John Thompsonea6c8db2013-03-27 21:23:21 +0000159 return ec;
160 }
161
162 // Parse the header list into strings.
163 SmallVector<StringRef, 32> strings;
164 listBuffer->getBuffer().split(strings, "\n", -1, false);
165
166 // Collect the header file names from the string list.
167 for (SmallVectorImpl<StringRef>::iterator I = strings.begin(),
168 E = strings.end();
169 I != E; ++I) {
170 StringRef line = (*I).trim();
171 // Ignore comments and empty lines.
172 if (line.empty() || (line[0] == '#'))
173 continue;
174 SmallString<256> headerFileName;
175 // Prepend header file name prefix if it's not absolute.
176 if (sys::path::is_absolute(line))
177 headerFileName = line;
178 else {
179 headerFileName = headerDirectory;
180 sys::path::append(headerFileName, line);
181 }
182 // Save the resulting header file path.
183 headerFileNames.push_back(headerFileName.str());
184 }
185
186 return error_code::success();
187}
188
John Thompsonce601e22013-03-14 01:41:29 +0000189// FIXME: The Location class seems to be something that we might
190// want to design to be applicable to a wider range of tools, and stick it
191// somewhere into Tooling/ in mainline
John Thompson4f8ba652013-03-12 02:07:30 +0000192struct Location {
193 const FileEntry *File;
194 unsigned Line, Column;
John Thompsonf5db45b2013-03-27 01:02:46 +0000195
196 Location() : File(), Line(), Column() {}
197
John Thompson4f8ba652013-03-12 02:07:30 +0000198 Location(SourceManager &SM, SourceLocation Loc) : File(), Line(), Column() {
199 Loc = SM.getExpansionLoc(Loc);
200 if (Loc.isInvalid())
201 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000202
John Thompson4f8ba652013-03-12 02:07:30 +0000203 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(Loc);
204 File = SM.getFileEntryForID(Decomposed.first);
205 if (!File)
206 return;
John Thompsonf5db45b2013-03-27 01:02:46 +0000207
John Thompson4f8ba652013-03-12 02:07:30 +0000208 Line = SM.getLineNumber(Decomposed.first, Decomposed.second);
209 Column = SM.getColumnNumber(Decomposed.first, Decomposed.second);
210 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000211
John Thompson4f8ba652013-03-12 02:07:30 +0000212 operator bool() const { return File != 0; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000213
John Thompson4f8ba652013-03-12 02:07:30 +0000214 friend bool operator==(const Location &X, const Location &Y) {
215 return X.File == Y.File && X.Line == Y.Line && X.Column == Y.Column;
216 }
217
218 friend bool operator!=(const Location &X, const Location &Y) {
219 return !(X == Y);
220 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000221
John Thompson4f8ba652013-03-12 02:07:30 +0000222 friend bool operator<(const Location &X, const Location &Y) {
223 if (X.File != Y.File)
224 return X.File < Y.File;
225 if (X.Line != Y.Line)
226 return X.Line < Y.Line;
227 return X.Column < Y.Column;
228 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000229 friend bool operator>(const Location &X, const Location &Y) { return Y < X; }
John Thompson4f8ba652013-03-12 02:07:30 +0000230 friend bool operator<=(const Location &X, const Location &Y) {
231 return !(Y < X);
232 }
233 friend bool operator>=(const Location &X, const Location &Y) {
234 return !(X < Y);
235 }
John Thompson4f8ba652013-03-12 02:07:30 +0000236};
237
John Thompson4f8ba652013-03-12 02:07:30 +0000238struct Entry {
John Thompson52d98862013-03-28 18:38:43 +0000239 enum EntryKind {
240 EK_Tag,
241 EK_Value,
242 EK_Macro,
243
244 EK_NumberOfKinds
John Thompson4f8ba652013-03-12 02:07:30 +0000245 } Kind;
John Thompsonf5db45b2013-03-27 01:02:46 +0000246
John Thompson4f8ba652013-03-12 02:07:30 +0000247 Location Loc;
John Thompson4e4d9b32013-03-28 01:20:19 +0000248
249 StringRef getKindName() { return getKindName(Kind); }
John Thompson52d98862013-03-28 18:38:43 +0000250 static StringRef getKindName(EntryKind kind);
John Thompson4f8ba652013-03-12 02:07:30 +0000251};
252
John Thompson4e4d9b32013-03-28 01:20:19 +0000253// Return a string representing the given kind.
John Thompson52d98862013-03-28 18:38:43 +0000254StringRef Entry::getKindName(Entry::EntryKind kind) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000255 switch (kind) {
John Thompson52d98862013-03-28 18:38:43 +0000256 case EK_Tag:
John Thompson4e4d9b32013-03-28 01:20:19 +0000257 return "tag";
John Thompson52d98862013-03-28 18:38:43 +0000258 case EK_Value:
John Thompson4e4d9b32013-03-28 01:20:19 +0000259 return "value";
John Thompson52d98862013-03-28 18:38:43 +0000260 case EK_Macro:
John Thompson4e4d9b32013-03-28 01:20:19 +0000261 return "macro";
John Thompson52d98862013-03-28 18:38:43 +0000262 case EK_NumberOfKinds:
John Thompson4e4d9b32013-03-28 01:20:19 +0000263 break;
John Thompson4e4d9b32013-03-28 01:20:19 +0000264 }
David Blaikiec66c07d2013-03-28 02:30:37 +0000265 llvm_unreachable("invalid Entry kind");
John Thompson4e4d9b32013-03-28 01:20:19 +0000266}
267
John Thompson4f8ba652013-03-12 02:07:30 +0000268struct HeaderEntry {
269 std::string Name;
270 Location Loc;
John Thompsonf5db45b2013-03-27 01:02:46 +0000271
John Thompson4f8ba652013-03-12 02:07:30 +0000272 friend bool operator==(const HeaderEntry &X, const HeaderEntry &Y) {
273 return X.Loc == Y.Loc && X.Name == Y.Name;
274 }
275 friend bool operator!=(const HeaderEntry &X, const HeaderEntry &Y) {
276 return !(X == Y);
277 }
278 friend bool operator<(const HeaderEntry &X, const HeaderEntry &Y) {
279 return X.Loc < Y.Loc || (X.Loc == Y.Loc && X.Name < Y.Name);
280 }
281 friend bool operator>(const HeaderEntry &X, const HeaderEntry &Y) {
282 return Y < X;
283 }
284 friend bool operator<=(const HeaderEntry &X, const HeaderEntry &Y) {
285 return !(Y < X);
286 }
287 friend bool operator>=(const HeaderEntry &X, const HeaderEntry &Y) {
288 return !(X < Y);
289 }
290};
291
292typedef std::vector<HeaderEntry> HeaderContents;
293
John Thompsonf5db45b2013-03-27 01:02:46 +0000294class EntityMap : public StringMap<SmallVector<Entry, 2> > {
John Thompson4f8ba652013-03-12 02:07:30 +0000295public:
John Thompsonf5db45b2013-03-27 01:02:46 +0000296 DenseMap<const FileEntry *, HeaderContents> HeaderContentMismatches;
297
John Thompson52d98862013-03-28 18:38:43 +0000298 void add(const std::string &Name, enum Entry::EntryKind Kind, Location Loc) {
John Thompson4f8ba652013-03-12 02:07:30 +0000299 // Record this entity in its header.
300 HeaderEntry HE = { Name, Loc };
301 CurHeaderContents[Loc.File].push_back(HE);
John Thompsonf5db45b2013-03-27 01:02:46 +0000302
John Thompson4f8ba652013-03-12 02:07:30 +0000303 // Check whether we've seen this entry before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000304 SmallVector<Entry, 2> &Entries = (*this)[Name];
John Thompson4f8ba652013-03-12 02:07:30 +0000305 for (unsigned I = 0, N = Entries.size(); I != N; ++I) {
306 if (Entries[I].Kind == Kind && Entries[I].Loc == Loc)
307 return;
308 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000309
John Thompson4f8ba652013-03-12 02:07:30 +0000310 // We have not seen this entry before; record it.
311 Entry E = { Kind, Loc };
312 Entries.push_back(E);
313 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000314
John Thompson4f8ba652013-03-12 02:07:30 +0000315 void mergeCurHeaderContents() {
John Thompsonf5db45b2013-03-27 01:02:46 +0000316 for (DenseMap<const FileEntry *, HeaderContents>::iterator
317 H = CurHeaderContents.begin(),
318 HEnd = CurHeaderContents.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000319 H != HEnd; ++H) {
320 // Sort contents.
321 std::sort(H->second.begin(), H->second.end());
322
323 // Check whether we've seen this header before.
John Thompsonf5db45b2013-03-27 01:02:46 +0000324 DenseMap<const FileEntry *, HeaderContents>::iterator KnownH =
325 AllHeaderContents.find(H->first);
John Thompson4f8ba652013-03-12 02:07:30 +0000326 if (KnownH == AllHeaderContents.end()) {
327 // We haven't seen this header before; record its contents.
328 AllHeaderContents.insert(*H);
329 continue;
330 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000331
John Thompson4f8ba652013-03-12 02:07:30 +0000332 // If the header contents are the same, we're done.
333 if (H->second == KnownH->second)
334 continue;
John Thompsonf5db45b2013-03-27 01:02:46 +0000335
John Thompson4f8ba652013-03-12 02:07:30 +0000336 // Determine what changed.
John Thompsonf5db45b2013-03-27 01:02:46 +0000337 std::set_symmetric_difference(
338 H->second.begin(), H->second.end(), KnownH->second.begin(),
339 KnownH->second.end(),
340 std::back_inserter(HeaderContentMismatches[H->first]));
John Thompson4f8ba652013-03-12 02:07:30 +0000341 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000342
John Thompson4f8ba652013-03-12 02:07:30 +0000343 CurHeaderContents.clear();
344 }
John Thompson161381e2013-06-27 18:52:23 +0000345
John Thompson1f67ccb2013-03-12 18:51:47 +0000346private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000347 DenseMap<const FileEntry *, HeaderContents> CurHeaderContents;
348 DenseMap<const FileEntry *, HeaderContents> AllHeaderContents;
John Thompson4f8ba652013-03-12 02:07:30 +0000349};
350
John Thompson161381e2013-06-27 18:52:23 +0000351class CollectEntitiesVisitor
352 : public RecursiveASTVisitor<CollectEntitiesVisitor> {
John Thompson4f8ba652013-03-12 02:07:30 +0000353public:
354 CollectEntitiesVisitor(SourceManager &SM, EntityMap &Entities)
John Thompsonf5db45b2013-03-27 01:02:46 +0000355 : SM(SM), Entities(Entities) {}
356
John Thompson4f8ba652013-03-12 02:07:30 +0000357 bool TraverseStmt(Stmt *S) { return true; }
358 bool TraverseType(QualType T) { return true; }
359 bool TraverseTypeLoc(TypeLoc TL) { return true; }
360 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000361 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
362 return true;
363 }
364 bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo) {
365 return true;
366 }
John Thompson4f8ba652013-03-12 02:07:30 +0000367 bool TraverseTemplateName(TemplateName Template) { return true; }
368 bool TraverseTemplateArgument(const TemplateArgument &Arg) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000369 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
370 return true;
371 }
John Thompson4f8ba652013-03-12 02:07:30 +0000372 bool TraverseTemplateArguments(const TemplateArgument *Args,
John Thompsonf5db45b2013-03-27 01:02:46 +0000373 unsigned NumArgs) {
374 return true;
375 }
John Thompson4f8ba652013-03-12 02:07:30 +0000376 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; }
377 bool TraverseLambdaCapture(LambdaExpr::Capture C) { return true; }
John Thompsonf5db45b2013-03-27 01:02:46 +0000378
John Thompson4f8ba652013-03-12 02:07:30 +0000379 bool VisitNamedDecl(NamedDecl *ND) {
380 // We only care about file-context variables.
381 if (!ND->getDeclContext()->isFileContext())
382 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000383
John Thompson4f8ba652013-03-12 02:07:30 +0000384 // Skip declarations that tend to be properly multiply-declared.
385 if (isa<NamespaceDecl>(ND) || isa<UsingDirectiveDecl>(ND) ||
John Thompsonf5db45b2013-03-27 01:02:46 +0000386 isa<NamespaceAliasDecl>(ND) ||
387 isa<ClassTemplateSpecializationDecl>(ND) || isa<UsingDecl>(ND) ||
388 isa<UsingShadowDecl>(ND) || isa<FunctionDecl>(ND) ||
389 isa<FunctionTemplateDecl>(ND) ||
John Thompson4f8ba652013-03-12 02:07:30 +0000390 (isa<TagDecl>(ND) &&
391 !cast<TagDecl>(ND)->isThisDeclarationADefinition()))
392 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000393
John Thompson4f8ba652013-03-12 02:07:30 +0000394 std::string Name = ND->getNameAsString();
395 if (Name.empty())
396 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000397
John Thompson4f8ba652013-03-12 02:07:30 +0000398 Location Loc(SM, ND->getLocation());
399 if (!Loc)
400 return true;
John Thompsonf5db45b2013-03-27 01:02:46 +0000401
John Thompson52d98862013-03-28 18:38:43 +0000402 Entities.add(Name, isa<TagDecl>(ND) ? Entry::EK_Tag : Entry::EK_Value, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000403 return true;
404 }
John Thompson161381e2013-06-27 18:52:23 +0000405
John Thompson1f67ccb2013-03-12 18:51:47 +0000406private:
407 SourceManager &SM;
408 EntityMap &Entities;
John Thompson4f8ba652013-03-12 02:07:30 +0000409};
410
411class CollectEntitiesConsumer : public ASTConsumer {
John Thompson4f8ba652013-03-12 02:07:30 +0000412public:
John Thompson94faa4d2013-07-26 23:56:42 +0000413 CollectEntitiesConsumer(EntityMap &Entities,
414 PreprocessorTracker &preprocessorTracker,
415 Preprocessor &PP, StringRef InFile)
416 : Entities(Entities), PPTracker(preprocessorTracker), PP(PP) {
417 PPTracker.handlePreprocessorEntry(PP, InFile);
418 }
419
420 ~CollectEntitiesConsumer() { PPTracker.handlePreprocessorExit(); }
John Thompsonf5db45b2013-03-27 01:02:46 +0000421
John Thompson4f8ba652013-03-12 02:07:30 +0000422 virtual void HandleTranslationUnit(ASTContext &Ctx) {
423 SourceManager &SM = Ctx.getSourceManager();
John Thompsonf5db45b2013-03-27 01:02:46 +0000424
John Thompson4f8ba652013-03-12 02:07:30 +0000425 // Collect declared entities.
426 CollectEntitiesVisitor(SM, Entities)
John Thompsonf5db45b2013-03-27 01:02:46 +0000427 .TraverseDecl(Ctx.getTranslationUnitDecl());
428
John Thompson4f8ba652013-03-12 02:07:30 +0000429 // Collect macro definitions.
430 for (Preprocessor::macro_iterator M = PP.macro_begin(),
John Thompsonf5db45b2013-03-27 01:02:46 +0000431 MEnd = PP.macro_end();
John Thompson4f8ba652013-03-12 02:07:30 +0000432 M != MEnd; ++M) {
433 Location Loc(SM, M->second->getLocation());
434 if (!Loc)
435 continue;
436
John Thompson52d98862013-03-28 18:38:43 +0000437 Entities.add(M->first->getName().str(), Entry::EK_Macro, Loc);
John Thompson4f8ba652013-03-12 02:07:30 +0000438 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000439
John Thompson4f8ba652013-03-12 02:07:30 +0000440 // Merge header contents.
441 Entities.mergeCurHeaderContents();
442 }
John Thompson161381e2013-06-27 18:52:23 +0000443
John Thompson1f67ccb2013-03-12 18:51:47 +0000444private:
445 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000446 PreprocessorTracker &PPTracker;
John Thompson1f67ccb2013-03-12 18:51:47 +0000447 Preprocessor &PP;
John Thompson4f8ba652013-03-12 02:07:30 +0000448};
449
450class CollectEntitiesAction : public SyntaxOnlyAction {
John Thompson1f67ccb2013-03-12 18:51:47 +0000451public:
John Thompson94faa4d2013-07-26 23:56:42 +0000452 CollectEntitiesAction(EntityMap &Entities,
453 PreprocessorTracker &preprocessorTracker)
454 : Entities(Entities), PPTracker(preprocessorTracker) {}
John Thompson161381e2013-06-27 18:52:23 +0000455
John Thompson4f8ba652013-03-12 02:07:30 +0000456protected:
John Thompson161381e2013-06-27 18:52:23 +0000457 virtual clang::ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
458 StringRef InFile) {
John Thompson94faa4d2013-07-26 23:56:42 +0000459 return new CollectEntitiesConsumer(Entities, PPTracker,
460 CI.getPreprocessor(), InFile);
John Thompson4f8ba652013-03-12 02:07:30 +0000461 }
John Thompson161381e2013-06-27 18:52:23 +0000462
John Thompson1f67ccb2013-03-12 18:51:47 +0000463private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000464 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000465 PreprocessorTracker &PPTracker;
John Thompson4f8ba652013-03-12 02:07:30 +0000466};
467
468class ModularizeFrontendActionFactory : public FrontendActionFactory {
John Thompson4f8ba652013-03-12 02:07:30 +0000469public:
John Thompson94faa4d2013-07-26 23:56:42 +0000470 ModularizeFrontendActionFactory(EntityMap &Entities,
471 PreprocessorTracker &preprocessorTracker)
472 : Entities(Entities), PPTracker(preprocessorTracker) {}
John Thompson4f8ba652013-03-12 02:07:30 +0000473
474 virtual CollectEntitiesAction *create() {
John Thompson94faa4d2013-07-26 23:56:42 +0000475 return new CollectEntitiesAction(Entities, PPTracker);
John Thompson4f8ba652013-03-12 02:07:30 +0000476 }
John Thompson161381e2013-06-27 18:52:23 +0000477
John Thompson1f67ccb2013-03-12 18:51:47 +0000478private:
John Thompsonf5db45b2013-03-27 01:02:46 +0000479 EntityMap &Entities;
John Thompson94faa4d2013-07-26 23:56:42 +0000480 PreprocessorTracker &PPTracker;
John Thompson4f8ba652013-03-12 02:07:30 +0000481};
482
483int main(int argc, const char **argv) {
John Thompsona2de1082013-03-26 01:17:48 +0000484
485 // This causes options to be parsed.
486 cl::ParseCommandLineOptions(argc, argv, "modularize.\n");
487
488 // No go if we have no header list file.
489 if (ListFileName.size() == 0) {
490 cl::PrintHelpMessage();
John Thompsonea6c8db2013-03-27 21:23:21 +0000491 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000492 }
John Thompsona2de1082013-03-26 01:17:48 +0000493
John Thompsonea6c8db2013-03-27 21:23:21 +0000494 // Get header file names.
John Thompsonf5db45b2013-03-27 01:02:46 +0000495 SmallVector<std::string, 32> Headers;
John Thompson54c83692013-06-18 19:56:05 +0000496 if (error_code ec = getHeaderFileNames(Headers, ListFileName, HeaderPrefix)) {
John Thompsonea6c8db2013-03-27 21:23:21 +0000497 errs() << argv[0] << ": error: Unable to get header list '" << ListFileName
498 << "': " << ec.message() << '\n';
499 return 1;
John Thompson4f8ba652013-03-12 02:07:30 +0000500 }
John Thompsona2de1082013-03-26 01:17:48 +0000501
John Thompson4f8ba652013-03-12 02:07:30 +0000502 // Create the compilation database.
John Thompsona2de1082013-03-26 01:17:48 +0000503 SmallString<256> PathBuf;
John Thompsonf5db45b2013-03-27 01:02:46 +0000504 sys::fs::current_path(PathBuf);
505 OwningPtr<CompilationDatabase> Compilations;
506 Compilations.reset(
507 new FixedCompilationDatabase(Twine(PathBuf), CC1Arguments));
John Thompsona2de1082013-03-26 01:17:48 +0000508
John Thompson94faa4d2013-07-26 23:56:42 +0000509 // Create preprocessor tracker, to watch for macro and conditional problems.
510 OwningPtr<PreprocessorTracker> PPTracker(PreprocessorTracker::create());
511
John Thompson4f8ba652013-03-12 02:07:30 +0000512 // Parse all of the headers, detecting duplicates.
513 EntityMap Entities;
514 ClangTool Tool(*Compilations, Headers);
John Thompson94faa4d2013-07-26 23:56:42 +0000515 int HadErrors =
516 Tool.run(new ModularizeFrontendActionFactory(Entities, *PPTracker));
John Thompsonce601e22013-03-14 01:41:29 +0000517
John Thompson4e4d9b32013-03-28 01:20:19 +0000518 // Create a place to save duplicate entity locations, separate bins per kind.
519 typedef SmallVector<Location, 8> LocationArray;
John Thompson52d98862013-03-28 18:38:43 +0000520 typedef SmallVector<LocationArray, Entry::EK_NumberOfKinds> EntryBinArray;
John Thompson4e4d9b32013-03-28 01:20:19 +0000521 EntryBinArray EntryBins;
Michael Gottesman4b249212013-03-28 06:07:15 +0000522 int kindIndex;
John Thompson52d98862013-03-28 18:38:43 +0000523 for (kindIndex = 0; kindIndex < Entry::EK_NumberOfKinds; ++kindIndex) {
524 LocationArray array;
525 EntryBins.push_back(array);
Michael Gottesman4b249212013-03-28 06:07:15 +0000526 }
John Thompson4e4d9b32013-03-28 01:20:19 +0000527
John Thompson4f8ba652013-03-12 02:07:30 +0000528 // Check for the same entity being defined in multiple places.
529 for (EntityMap::iterator E = Entities.begin(), EEnd = Entities.end();
530 E != EEnd; ++E) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000531 // If only one occurance, exit early.
532 if (E->second.size() == 1)
533 continue;
534 // Clear entity locations.
535 for (EntryBinArray::iterator CI = EntryBins.begin(), CE = EntryBins.end();
536 CI != CE; ++CI) {
John Thompson52d98862013-03-28 18:38:43 +0000537 CI->clear();
John Thompson4e4d9b32013-03-28 01:20:19 +0000538 }
539 // Walk the entities of a single name, collecting the locations,
540 // separated into separate bins.
John Thompson4f8ba652013-03-12 02:07:30 +0000541 for (unsigned I = 0, N = E->second.size(); I != N; ++I) {
John Thompson52d98862013-03-28 18:38:43 +0000542 EntryBins[E->second[I].Kind].push_back(E->second[I].Loc);
John Thompson4e4d9b32013-03-28 01:20:19 +0000543 }
544 // Report any duplicate entity definition errors.
545 int kindIndex = 0;
546 for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end();
547 DI != DE; ++DI, ++kindIndex) {
John Thompson52d98862013-03-28 18:38:43 +0000548 int eCount = DI->size();
John Thompson4e4d9b32013-03-28 01:20:19 +0000549 // If only 1 occurance, skip;
550 if (eCount <= 1)
John Thompson4f8ba652013-03-12 02:07:30 +0000551 continue;
John Thompson52d98862013-03-28 18:38:43 +0000552 LocationArray::iterator FI = DI->begin();
John Thompsonb809dfc2013-07-19 14:19:31 +0000553 StringRef kindName = Entry::getKindName((Entry::EntryKind)kindIndex);
John Thompson4e4d9b32013-03-28 01:20:19 +0000554 errs() << "error: " << kindName << " '" << E->first()
555 << "' defined at multiple locations:\n";
John Thompson52d98862013-03-28 18:38:43 +0000556 for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) {
John Thompson4e4d9b32013-03-28 01:20:19 +0000557 errs() << " " << FI->File->getName() << ":" << FI->Line << ":"
558 << FI->Column << "\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000559 }
John Thompson4f8ba652013-03-12 02:07:30 +0000560 HadErrors = 1;
561 }
562 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000563
John Thompson94faa4d2013-07-26 23:56:42 +0000564 // Complain about macro instance in header files that differ based on how
565 // they are included.
566 if (PPTracker->reportInconsistentMacros(errs()))
567 HadErrors = 1;
568
569 // Complain about preprocessor conditional directives in header files that
570 // differ based on how they are included.
571 if (PPTracker->reportInconsistentConditionals(errs()))
572 HadErrors = 1;
573
John Thompson4f8ba652013-03-12 02:07:30 +0000574 // Complain about any headers that have contents that differ based on how
575 // they are included.
John Thompsonce601e22013-03-14 01:41:29 +0000576 // FIXME: Could we provide information about which preprocessor conditionals
577 // are involved?
John Thompsonf5db45b2013-03-27 01:02:46 +0000578 for (DenseMap<const FileEntry *, HeaderContents>::iterator
579 H = Entities.HeaderContentMismatches.begin(),
580 HEnd = Entities.HeaderContentMismatches.end();
John Thompson4f8ba652013-03-12 02:07:30 +0000581 H != HEnd; ++H) {
582 if (H->second.empty()) {
John Thompsonf5db45b2013-03-27 01:02:46 +0000583 errs() << "internal error: phantom header content mismatch\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000584 continue;
585 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000586
John Thompson4f8ba652013-03-12 02:07:30 +0000587 HadErrors = 1;
John Thompsonf5db45b2013-03-27 01:02:46 +0000588 errs() << "error: header '" << H->first->getName()
John Thompson94faa4d2013-07-26 23:56:42 +0000589 << "' has different contents depending on how it was included.\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000590 for (unsigned I = 0, N = H->second.size(); I != N; ++I) {
John Thompson161381e2013-06-27 18:52:23 +0000591 errs() << "note: '" << H->second[I].Name << "' in "
592 << H->second[I].Loc.File->getName() << " at "
593 << H->second[I].Loc.Line << ":" << H->second[I].Loc.Column
594 << " not always provided\n";
John Thompson4f8ba652013-03-12 02:07:30 +0000595 }
596 }
John Thompsonf5db45b2013-03-27 01:02:46 +0000597
John Thompson4f8ba652013-03-12 02:07:30 +0000598 return HadErrors;
599}