1 //===- MacroInfo.h - Information about #defined identifiers -----*- C++ -*-===//
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 //===----------------------------------------------------------------------===//
11 /// Defines the clang::MacroInfo and clang::MacroDirective classes.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_LEX_MACROINFO_H
16 #define LLVM_CLANG_LEX_MACROINFO_H
18 #include "clang/Lex/Token.h"
19 #include "clang/Basic/LLVM.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/PointerIntPair.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/Allocator.h"
31 class DefMacroDirective;
37 /// Encapsulates the data about a macro definition (e.g. its tokens).
39 /// There's an instance of this class for every #define.
41 //===--------------------------------------------------------------------===//
42 // State set when the macro is defined.
44 /// The location the macro is defined.
45 SourceLocation Location;
47 /// The location of the last token in the macro.
48 SourceLocation EndLocation;
50 /// The list of arguments for a function-like macro.
52 /// ParameterList points to the first of NumParameters pointers.
54 /// This can be empty, for, e.g. "#define X()". In a C99-style variadic
55 /// macro, this includes the \c __VA_ARGS__ identifier on the list.
56 IdentifierInfo **ParameterList = nullptr;
58 /// \see ParameterList
59 unsigned NumParameters = 0;
61 /// This is the list of tokens that the macro is defined to.
62 SmallVector<Token, 8> ReplacementTokens;
64 /// Length in characters of the macro definition.
65 mutable unsigned DefinitionLength;
66 mutable bool IsDefinitionLengthCached : 1;
68 /// True if this macro is function-like, false if it is object-like.
69 bool IsFunctionLike : 1;
71 /// True if this macro is of the form "#define X(...)" or
72 /// "#define X(Y,Z,...)".
74 /// The __VA_ARGS__ token should be replaced with the contents of "..." in an
76 bool IsC99Varargs : 1;
78 /// True if this macro is of the form "#define X(a...)".
80 /// The "a" identifier in the replacement list will be replaced with all
81 /// arguments of the macro starting with the specified one.
82 bool IsGNUVarargs : 1;
84 /// True if this macro requires processing before expansion.
86 /// This is the case for builtin macros such as __LINE__, so long as they have
87 /// not been redefined, but not for regular predefined macros from the
88 /// "<built-in>" memory buffer (see Preprocessing::getPredefinesFileID).
89 bool IsBuiltinMacro : 1;
91 /// Whether this macro contains the sequence ", ## __VA_ARGS__"
92 bool HasCommaPasting : 1;
94 //===--------------------------------------------------------------------===//
95 // State that changes as the macro is used.
97 /// True if we have started an expansion of this macro already.
99 /// This disables recursive expansion, which would be quite bad for things
100 /// like \#define A A.
103 /// True if this macro is either defined in the main file and has
104 /// been used, or if it is not defined in the main file.
106 /// This is used to emit -Wunused-macros diagnostics.
109 /// True if this macro can be redefined without emitting a warning.
110 bool IsAllowRedefinitionsWithoutWarning : 1;
112 /// Must warn if the macro is unused at the end of translation unit.
113 bool IsWarnIfUnused : 1;
115 /// Whether this macro was used as header guard.
116 bool UsedForHeaderGuard : 1;
118 // Only the Preprocessor gets to create and destroy these.
119 MacroInfo(SourceLocation DefLoc);
120 ~MacroInfo() = default;
123 /// Return the location that the macro was defined at.
124 SourceLocation getDefinitionLoc() const { return Location; }
126 /// Set the location of the last token in the macro.
127 void setDefinitionEndLoc(SourceLocation EndLoc) { EndLocation = EndLoc; }
129 /// Return the location of the last token in the macro.
130 SourceLocation getDefinitionEndLoc() const { return EndLocation; }
132 /// Get length in characters of the macro definition.
133 unsigned getDefinitionLength(const SourceManager &SM) const {
134 if (IsDefinitionLengthCached)
135 return DefinitionLength;
136 return getDefinitionLengthSlow(SM);
139 /// Return true if the specified macro definition is equal to
140 /// this macro in spelling, arguments, and whitespace.
142 /// \param Syntactically if true, the macro definitions can be identical even
143 /// if they use different identifiers for the function macro parameters.
144 /// Otherwise the comparison is lexical and this implements the rules in
146 bool isIdenticalTo(const MacroInfo &Other, Preprocessor &PP,
147 bool Syntactically) const;
149 /// Set or clear the isBuiltinMacro flag.
150 void setIsBuiltinMacro(bool Val = true) { IsBuiltinMacro = Val; }
152 /// Set the value of the IsUsed flag.
153 void setIsUsed(bool Val) { IsUsed = Val; }
155 /// Set the value of the IsAllowRedefinitionsWithoutWarning flag.
156 void setIsAllowRedefinitionsWithoutWarning(bool Val) {
157 IsAllowRedefinitionsWithoutWarning = Val;
160 /// Set the value of the IsWarnIfUnused flag.
161 void setIsWarnIfUnused(bool val) { IsWarnIfUnused = val; }
163 /// Set the specified list of identifiers as the parameter list for
165 void setParameterList(ArrayRef<IdentifierInfo *> List,
166 llvm::BumpPtrAllocator &PPAllocator) {
167 assert(ParameterList == nullptr && NumParameters == 0 &&
168 "Parameter list already set!");
172 NumParameters = List.size();
173 ParameterList = PPAllocator.Allocate<IdentifierInfo *>(List.size());
174 std::copy(List.begin(), List.end(), ParameterList);
177 /// Parameters - The list of parameters for a function-like macro. This can
178 /// be empty, for, e.g. "#define X()".
179 using param_iterator = IdentifierInfo *const *;
180 bool param_empty() const { return NumParameters == 0; }
181 param_iterator param_begin() const { return ParameterList; }
182 param_iterator param_end() const { return ParameterList + NumParameters; }
183 unsigned getNumParams() const { return NumParameters; }
184 ArrayRef<const IdentifierInfo *> params() const {
185 return ArrayRef<const IdentifierInfo *>(ParameterList, NumParameters);
188 /// Return the parameter number of the specified identifier,
189 /// or -1 if the identifier is not a formal parameter identifier.
190 int getParameterNum(const IdentifierInfo *Arg) const {
191 for (param_iterator I = param_begin(), E = param_end(); I != E; ++I)
193 return I - param_begin();
197 /// Function/Object-likeness. Keep track of whether this macro has formal
199 void setIsFunctionLike() { IsFunctionLike = true; }
200 bool isFunctionLike() const { return IsFunctionLike; }
201 bool isObjectLike() const { return !IsFunctionLike; }
203 /// Varargs querying methods. This can only be set for function-like macros.
204 void setIsC99Varargs() { IsC99Varargs = true; }
205 void setIsGNUVarargs() { IsGNUVarargs = true; }
206 bool isC99Varargs() const { return IsC99Varargs; }
207 bool isGNUVarargs() const { return IsGNUVarargs; }
208 bool isVariadic() const { return IsC99Varargs | IsGNUVarargs; }
210 /// Return true if this macro requires processing before expansion.
212 /// This is true only for builtin macro, such as \__LINE__, whose values
213 /// are not given by fixed textual expansions. Regular predefined macros
214 /// from the "<built-in>" buffer are not reported as builtins by this
216 bool isBuiltinMacro() const { return IsBuiltinMacro; }
218 bool hasCommaPasting() const { return HasCommaPasting; }
219 void setHasCommaPasting() { HasCommaPasting = true; }
221 /// Return false if this macro is defined in the main file and has
222 /// not yet been used.
223 bool isUsed() const { return IsUsed; }
225 /// Return true if this macro can be redefined without warning.
226 bool isAllowRedefinitionsWithoutWarning() const {
227 return IsAllowRedefinitionsWithoutWarning;
230 /// Return true if we should emit a warning if the macro is unused.
231 bool isWarnIfUnused() const { return IsWarnIfUnused; }
233 /// Return the number of tokens that this macro expands to.
234 unsigned getNumTokens() const { return ReplacementTokens.size(); }
236 const Token &getReplacementToken(unsigned Tok) const {
237 assert(Tok < ReplacementTokens.size() && "Invalid token #");
238 return ReplacementTokens[Tok];
241 using tokens_iterator = SmallVectorImpl<Token>::const_iterator;
243 tokens_iterator tokens_begin() const { return ReplacementTokens.begin(); }
244 tokens_iterator tokens_end() const { return ReplacementTokens.end(); }
245 bool tokens_empty() const { return ReplacementTokens.empty(); }
246 ArrayRef<Token> tokens() const { return ReplacementTokens; }
248 /// Add the specified token to the replacement text for the macro.
249 void AddTokenToBody(const Token &Tok) {
251 !IsDefinitionLengthCached &&
252 "Changing replacement tokens after definition length got calculated");
253 ReplacementTokens.push_back(Tok);
256 /// Return true if this macro is enabled.
258 /// In other words, that we are not currently in an expansion of this macro.
259 bool isEnabled() const { return !IsDisabled; }
262 assert(IsDisabled && "Cannot enable an already-enabled macro!");
266 void DisableMacro() {
267 assert(!IsDisabled && "Cannot disable an already-disabled macro!");
271 /// Determine whether this macro was used for a header guard.
272 bool isUsedForHeaderGuard() const { return UsedForHeaderGuard; }
274 void setUsedForHeaderGuard(bool Val) { UsedForHeaderGuard = Val; }
279 friend class Preprocessor;
281 unsigned getDefinitionLengthSlow(const SourceManager &SM) const;
284 /// Encapsulates changes to the "macros namespace" (the location where
285 /// the macro name became active, the location where it was undefined, etc.).
287 /// MacroDirectives, associated with an identifier, are used to model the macro
288 /// history. Usually a macro definition (MacroInfo) is where a macro name
289 /// becomes active (MacroDirective) but #pragma push_macro / pop_macro can
290 /// create additional DefMacroDirectives for the same MacroInfo.
291 class MacroDirective {
300 /// Previous macro directive for the same identifier, or nullptr.
301 MacroDirective *Previous = nullptr;
305 /// MacroDirective kind.
308 /// True if the macro directive was loaded from a PCH file.
309 unsigned IsFromPCH : 1;
311 // Used by VisibilityMacroDirective ----------------------------------------//
313 /// Whether the macro has public visibility (when described in a
315 unsigned IsPublic : 1;
317 MacroDirective(Kind K, SourceLocation Loc)
318 : Loc(Loc), MDKind(K), IsFromPCH(false), IsPublic(true) {}
321 Kind getKind() const { return Kind(MDKind); }
323 SourceLocation getLocation() const { return Loc; }
325 /// Set previous definition of the macro with the same name.
326 void setPrevious(MacroDirective *Prev) { Previous = Prev; }
328 /// Get previous definition of the macro with the same name.
329 const MacroDirective *getPrevious() const { return Previous; }
331 /// Get previous definition of the macro with the same name.
332 MacroDirective *getPrevious() { return Previous; }
334 /// Return true if the macro directive was loaded from a PCH file.
335 bool isFromPCH() const { return IsFromPCH; }
337 void setIsFromPCH() { IsFromPCH = true; }
340 DefMacroDirective *DefDirective = nullptr;
341 SourceLocation UndefLoc;
342 bool IsPublic = true;
346 DefInfo(DefMacroDirective *DefDirective, SourceLocation UndefLoc,
348 : DefDirective(DefDirective), UndefLoc(UndefLoc), IsPublic(isPublic) {}
350 const DefMacroDirective *getDirective() const { return DefDirective; }
351 DefMacroDirective *getDirective() { return DefDirective; }
353 inline SourceLocation getLocation() const;
354 inline MacroInfo *getMacroInfo();
356 const MacroInfo *getMacroInfo() const {
357 return const_cast<DefInfo *>(this)->getMacroInfo();
360 SourceLocation getUndefLocation() const { return UndefLoc; }
361 bool isUndefined() const { return UndefLoc.isValid(); }
363 bool isPublic() const { return IsPublic; }
365 bool isValid() const { return DefDirective != nullptr; }
366 bool isInvalid() const { return !isValid(); }
368 explicit operator bool() const { return isValid(); }
370 inline DefInfo getPreviousDefinition();
372 const DefInfo getPreviousDefinition() const {
373 return const_cast<DefInfo *>(this)->getPreviousDefinition();
377 /// Traverses the macro directives history and returns the next
378 /// macro definition directive along with info about its undefined location
379 /// (if there is one) and if it is public or private.
380 DefInfo getDefinition();
381 const DefInfo getDefinition() const {
382 return const_cast<MacroDirective *>(this)->getDefinition();
385 bool isDefined() const {
386 if (const DefInfo Def = getDefinition())
387 return !Def.isUndefined();
391 const MacroInfo *getMacroInfo() const {
392 return getDefinition().getMacroInfo();
394 MacroInfo *getMacroInfo() { return getDefinition().getMacroInfo(); }
396 /// Find macro definition active in the specified source location. If
397 /// this macro was not defined there, return NULL.
398 const DefInfo findDirectiveAtLoc(SourceLocation L, SourceManager &SM) const;
402 static bool classof(const MacroDirective *) { return true; }
405 /// A directive for a defined macro or a macro imported from a module.
406 class DefMacroDirective : public MacroDirective {
410 DefMacroDirective(MacroInfo *MI, SourceLocation Loc)
411 : MacroDirective(MD_Define, Loc), Info(MI) {
412 assert(MI && "MacroInfo is null");
414 explicit DefMacroDirective(MacroInfo *MI)
415 : DefMacroDirective(MI, MI->getDefinitionLoc()) {}
417 /// The data for the macro definition.
418 const MacroInfo *getInfo() const { return Info; }
419 MacroInfo *getInfo() { return Info; }
421 static bool classof(const MacroDirective *MD) {
422 return MD->getKind() == MD_Define;
425 static bool classof(const DefMacroDirective *) { return true; }
428 /// A directive for an undefined macro.
429 class UndefMacroDirective : public MacroDirective {
431 explicit UndefMacroDirective(SourceLocation UndefLoc)
432 : MacroDirective(MD_Undefine, UndefLoc) {
433 assert(UndefLoc.isValid() && "Invalid UndefLoc!");
436 static bool classof(const MacroDirective *MD) {
437 return MD->getKind() == MD_Undefine;
440 static bool classof(const UndefMacroDirective *) { return true; }
443 /// A directive for setting the module visibility of a macro.
444 class VisibilityMacroDirective : public MacroDirective {
446 explicit VisibilityMacroDirective(SourceLocation Loc, bool Public)
447 : MacroDirective(MD_Visibility, Loc) {
451 /// Determine whether this macro is part of the public API of its
453 bool isPublic() const { return IsPublic; }
455 static bool classof(const MacroDirective *MD) {
456 return MD->getKind() == MD_Visibility;
459 static bool classof(const VisibilityMacroDirective *) { return true; }
462 inline SourceLocation MacroDirective::DefInfo::getLocation() const {
465 return DefDirective->getLocation();
468 inline MacroInfo *MacroDirective::DefInfo::getMacroInfo() {
471 return DefDirective->getInfo();
474 inline MacroDirective::DefInfo
475 MacroDirective::DefInfo::getPreviousDefinition() {
476 if (isInvalid() || DefDirective->getPrevious() == nullptr)
478 return DefDirective->getPrevious()->getDefinition();
481 /// Represents a macro directive exported by a module.
483 /// There's an instance of this class for every macro #define or #undef that is
484 /// the final directive for a macro name within a module. These entities also
485 /// represent the macro override graph.
487 /// These are stored in a FoldingSet in the preprocessor.
488 class ModuleMacro : public llvm::FoldingSetNode {
489 friend class Preprocessor;
491 /// The name defined by the macro.
494 /// The body of the #define, or nullptr if this is a #undef.
497 /// The module that exports this macro.
498 Module *OwningModule;
500 /// The number of module macros that override this one.
501 unsigned NumOverriddenBy = 0;
503 /// The number of modules whose macros are directly overridden by this one.
504 unsigned NumOverrides;
506 ModuleMacro(Module *OwningModule, IdentifierInfo *II, MacroInfo *Macro,
507 ArrayRef<ModuleMacro *> Overrides)
508 : II(II), Macro(Macro), OwningModule(OwningModule),
509 NumOverrides(Overrides.size()) {
510 std::copy(Overrides.begin(), Overrides.end(),
511 reinterpret_cast<ModuleMacro **>(this + 1));
515 static ModuleMacro *create(Preprocessor &PP, Module *OwningModule,
516 IdentifierInfo *II, MacroInfo *Macro,
517 ArrayRef<ModuleMacro *> Overrides);
519 void Profile(llvm::FoldingSetNodeID &ID) const {
520 return Profile(ID, OwningModule, II);
523 static void Profile(llvm::FoldingSetNodeID &ID, Module *OwningModule,
524 IdentifierInfo *II) {
525 ID.AddPointer(OwningModule);
529 /// Get the name of the macro.
530 IdentifierInfo *getName() const { return II; }
532 /// Get the ID of the module that exports this macro.
533 Module *getOwningModule() const { return OwningModule; }
535 /// Get definition for this exported #define, or nullptr if this
536 /// represents a #undef.
537 MacroInfo *getMacroInfo() const { return Macro; }
539 /// Iterators over the overridden module IDs.
541 using overrides_iterator = ModuleMacro *const *;
543 overrides_iterator overrides_begin() const {
544 return reinterpret_cast<overrides_iterator>(this + 1);
547 overrides_iterator overrides_end() const {
548 return overrides_begin() + NumOverrides;
551 ArrayRef<ModuleMacro *> overrides() const {
552 return llvm::makeArrayRef(overrides_begin(), overrides_end());
556 /// Get the number of macros that override this one.
557 unsigned getNumOverridingMacros() const { return NumOverriddenBy; }
560 /// A description of the current definition of a macro.
562 /// The definition of a macro comprises a set of (at least one) defining
563 /// entities, which are either local MacroDirectives or imported ModuleMacros.
564 class MacroDefinition {
565 llvm::PointerIntPair<DefMacroDirective *, 1, bool> LatestLocalAndAmbiguous;
566 ArrayRef<ModuleMacro *> ModuleMacros;
569 MacroDefinition() = default;
570 MacroDefinition(DefMacroDirective *MD, ArrayRef<ModuleMacro *> MMs,
572 : LatestLocalAndAmbiguous(MD, IsAmbiguous), ModuleMacros(MMs) {}
574 /// Determine whether there is a definition of this macro.
575 explicit operator bool() const {
576 return getLocalDirective() || !ModuleMacros.empty();
579 /// Get the MacroInfo that should be used for this definition.
580 MacroInfo *getMacroInfo() const {
581 if (!ModuleMacros.empty())
582 return ModuleMacros.back()->getMacroInfo();
583 if (auto *MD = getLocalDirective())
584 return MD->getMacroInfo();
588 /// \c true if the definition is ambiguous, \c false otherwise.
589 bool isAmbiguous() const { return LatestLocalAndAmbiguous.getInt(); }
591 /// Get the latest non-imported, non-\#undef'd macro definition
593 DefMacroDirective *getLocalDirective() const {
594 return LatestLocalAndAmbiguous.getPointer();
597 /// Get the active module macros for this macro.
598 ArrayRef<ModuleMacro *> getModuleMacros() const { return ModuleMacros; }
600 template <typename Fn> void forAllDefinitions(Fn F) const {
601 if (auto *MD = getLocalDirective())
602 F(MD->getMacroInfo());
603 for (auto *MM : getModuleMacros())
604 F(MM->getMacroInfo());
610 #endif // LLVM_CLANG_LEX_MACROINFO_H