1 //===- MacroInfo.cpp - Information about #defined identifiers -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the MacroInfo interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Lex/MacroInfo.h"
15 #include "clang/Basic/IdentifierTable.h"
16 #include "clang/Basic/LLVM.h"
17 #include "clang/Basic/SourceLocation.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Basic/TokenKinds.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Lex/Token.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/raw_ostream.h"
30 using namespace clang;
32 MacroInfo::MacroInfo(SourceLocation DefLoc)
33 : Location(DefLoc), IsDefinitionLengthCached(false), IsFunctionLike(false),
34 IsC99Varargs(false), IsGNUVarargs(false), IsBuiltinMacro(false),
35 HasCommaPasting(false), IsDisabled(false), IsUsed(false),
36 IsAllowRedefinitionsWithoutWarning(false), IsWarnIfUnused(false),
37 UsedForHeaderGuard(false) {}
39 unsigned MacroInfo::getDefinitionLengthSlow(const SourceManager &SM) const {
40 assert(!IsDefinitionLengthCached);
41 IsDefinitionLengthCached = true;
43 if (ReplacementTokens.empty())
44 return (DefinitionLength = 0);
46 const Token &firstToken = ReplacementTokens.front();
47 const Token &lastToken = ReplacementTokens.back();
48 SourceLocation macroStart = firstToken.getLocation();
49 SourceLocation macroEnd = lastToken.getLocation();
50 assert(macroStart.isValid() && macroEnd.isValid());
51 assert((macroStart.isFileID() || firstToken.is(tok::comment)) &&
52 "Macro defined in macro?");
53 assert((macroEnd.isFileID() || lastToken.is(tok::comment)) &&
54 "Macro defined in macro?");
55 std::pair<FileID, unsigned>
56 startInfo = SM.getDecomposedExpansionLoc(macroStart);
57 std::pair<FileID, unsigned>
58 endInfo = SM.getDecomposedExpansionLoc(macroEnd);
59 assert(startInfo.first == endInfo.first &&
60 "Macro definition spanning multiple FileIDs ?");
61 assert(startInfo.second <= endInfo.second);
62 DefinitionLength = endInfo.second - startInfo.second;
63 DefinitionLength += lastToken.getLength();
65 return DefinitionLength;
68 /// \brief Return true if the specified macro definition is equal to
69 /// this macro in spelling, arguments, and whitespace.
71 /// \param Syntactically if true, the macro definitions can be identical even
72 /// if they use different identifiers for the function macro parameters.
73 /// Otherwise the comparison is lexical and this implements the rules in
75 bool MacroInfo::isIdenticalTo(const MacroInfo &Other, Preprocessor &PP,
76 bool Syntactically) const {
77 bool Lexically = !Syntactically;
79 // Check # tokens in replacement, number of args, and various flags all match.
80 if (ReplacementTokens.size() != Other.ReplacementTokens.size() ||
81 getNumParams() != Other.getNumParams() ||
82 isFunctionLike() != Other.isFunctionLike() ||
83 isC99Varargs() != Other.isC99Varargs() ||
84 isGNUVarargs() != Other.isGNUVarargs())
89 for (param_iterator I = param_begin(), OI = Other.param_begin(),
92 if (*I != *OI) return false;
95 // Check all the tokens.
96 for (unsigned i = 0, e = ReplacementTokens.size(); i != e; ++i) {
97 const Token &A = ReplacementTokens[i];
98 const Token &B = Other.ReplacementTokens[i];
99 if (A.getKind() != B.getKind())
102 // If this isn't the first first token, check that the whitespace and
103 // start-of-line characteristics match.
105 (A.isAtStartOfLine() != B.isAtStartOfLine() ||
106 A.hasLeadingSpace() != B.hasLeadingSpace()))
109 // If this is an identifier, it is easy.
110 if (A.getIdentifierInfo() || B.getIdentifierInfo()) {
111 if (A.getIdentifierInfo() == B.getIdentifierInfo())
115 // With syntactic equivalence the parameter names can be different as long
116 // as they are used in the same place.
117 int AArgNum = getParameterNum(A.getIdentifierInfo());
120 if (AArgNum != Other.getParameterNum(B.getIdentifierInfo()))
125 // Otherwise, check the spelling.
126 if (PP.getSpelling(A) != PP.getSpelling(B))
133 LLVM_DUMP_METHOD void MacroInfo::dump() const {
134 llvm::raw_ostream &Out = llvm::errs();
136 // FIXME: Dump locations.
137 Out << "MacroInfo " << this;
138 if (IsBuiltinMacro) Out << " builtin";
139 if (IsDisabled) Out << " disabled";
140 if (IsUsed) Out << " used";
141 if (IsAllowRedefinitionsWithoutWarning)
142 Out << " allow_redefinitions_without_warning";
143 if (IsWarnIfUnused) Out << " warn_if_unused";
144 if (UsedForHeaderGuard) Out << " header_guard";
146 Out << "\n #define <macro>";
147 if (IsFunctionLike) {
149 for (unsigned I = 0; I != NumParameters; ++I) {
151 Out << ParameterList[I]->getName();
153 if (IsC99Varargs || IsGNUVarargs) {
154 if (NumParameters && IsC99Varargs) Out << ", ";
161 for (const Token &Tok : ReplacementTokens) {
162 // Leading space is semantically meaningful in a macro definition,
163 // so preserve it in the dump output.
164 if (First || Tok.hasLeadingSpace())
168 if (const char *Punc = tok::getPunctuatorSpelling(Tok.getKind()))
170 else if (Tok.isLiteral() && Tok.getLiteralData())
171 Out << StringRef(Tok.getLiteralData(), Tok.getLength());
172 else if (auto *II = Tok.getIdentifierInfo())
173 Out << II->getName();
175 Out << Tok.getName();
179 MacroDirective::DefInfo MacroDirective::getDefinition() {
180 MacroDirective *MD = this;
181 SourceLocation UndefLoc;
182 Optional<bool> isPublic;
183 for (; MD; MD = MD->getPrevious()) {
184 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
185 return DefInfo(DefMD, UndefLoc,
186 !isPublic.hasValue() || isPublic.getValue());
188 if (UndefMacroDirective *UndefMD = dyn_cast<UndefMacroDirective>(MD)) {
189 UndefLoc = UndefMD->getLocation();
193 VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD);
194 if (!isPublic.hasValue())
195 isPublic = VisMD->isPublic();
198 return DefInfo(nullptr, UndefLoc,
199 !isPublic.hasValue() || isPublic.getValue());
202 const MacroDirective::DefInfo
203 MacroDirective::findDirectiveAtLoc(SourceLocation L, SourceManager &SM) const {
204 assert(L.isValid() && "SourceLocation is invalid.");
205 for (DefInfo Def = getDefinition(); Def; Def = Def.getPreviousDefinition()) {
206 if (Def.getLocation().isInvalid() || // For macros defined on the command line.
207 SM.isBeforeInTranslationUnit(Def.getLocation(), L))
208 return (!Def.isUndefined() ||
209 SM.isBeforeInTranslationUnit(L, Def.getUndefLocation()))
215 LLVM_DUMP_METHOD void MacroDirective::dump() const {
216 llvm::raw_ostream &Out = llvm::errs();
219 case MD_Define: Out << "DefMacroDirective"; break;
220 case MD_Undefine: Out << "UndefMacroDirective"; break;
221 case MD_Visibility: Out << "VisibilityMacroDirective"; break;
224 // FIXME: Dump SourceLocation.
225 if (auto *Prev = getPrevious())
226 Out << " prev " << Prev;
227 if (IsFromPCH) Out << " from_pch";
229 if (isa<VisibilityMacroDirective>(this))
230 Out << (IsPublic ? " public" : " private");
232 if (auto *DMD = dyn_cast<DefMacroDirective>(this)) {
233 if (auto *Info = DMD->getInfo()) {
241 ModuleMacro *ModuleMacro::create(Preprocessor &PP, Module *OwningModule,
242 IdentifierInfo *II, MacroInfo *Macro,
243 ArrayRef<ModuleMacro *> Overrides) {
244 void *Mem = PP.getPreprocessorAllocator().Allocate(
245 sizeof(ModuleMacro) + sizeof(ModuleMacro *) * Overrides.size(),
246 alignof(ModuleMacro));
247 return new (Mem) ModuleMacro(OwningModule, II, Macro, Overrides);