Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Lex/MacroInfo.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- MacroInfo.cpp - Information about #defined identifiers -------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements the MacroInfo interface.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Lex/MacroInfo.h"
14
#include "clang/Basic/IdentifierTable.h"
15
#include "clang/Basic/LLVM.h"
16
#include "clang/Basic/SourceLocation.h"
17
#include "clang/Basic/SourceManager.h"
18
#include "clang/Basic/TokenKinds.h"
19
#include "clang/Lex/Preprocessor.h"
20
#include "clang/Lex/Token.h"
21
#include "llvm/ADT/StringRef.h"
22
#include "llvm/Support/Casting.h"
23
#include "llvm/Support/Compiler.h"
24
#include "llvm/Support/raw_ostream.h"
25
#include <cassert>
26
#include <optional>
27
#include <utility>
28
29
using namespace clang;
30
31
namespace {
32
33
// MacroInfo is expected to take 40 bytes on platforms with an 8 byte pointer
34
// and 4 byte SourceLocation.
35
template <int> class MacroInfoSizeChecker {
36
public:
37
  [[maybe_unused]] constexpr static bool AsExpected = true;
38
};
39
template <> class MacroInfoSizeChecker<8> {
40
public:
41
  [[maybe_unused]] constexpr static bool AsExpected =
42
      sizeof(MacroInfo) == (32 + sizeof(SourceLocation) * 2);
43
};
44
45
static_assert(MacroInfoSizeChecker<sizeof(void *)>::AsExpected,
46
              "Unexpected size of MacroInfo");
47
48
} // end namespace
49
50
MacroInfo::MacroInfo(SourceLocation DefLoc)
51
    : Location(DefLoc), IsDefinitionLengthCached(false), IsFunctionLike(false),
52
      IsC99Varargs(false), IsGNUVarargs(false), IsBuiltinMacro(false),
53
      HasCommaPasting(false), IsDisabled(false), IsUsed(false),
54
      IsAllowRedefinitionsWithoutWarning(false), IsWarnIfUnused(false),
55
19.7k
      UsedForHeaderGuard(false) {}
56
57
0
unsigned MacroInfo::getDefinitionLengthSlow(const SourceManager &SM) const {
58
0
  assert(!IsDefinitionLengthCached);
59
0
  IsDefinitionLengthCached = true;
60
61
0
  ArrayRef<Token> ReplacementTokens = tokens();
62
0
  if (ReplacementTokens.empty())
63
0
    return (DefinitionLength = 0);
64
65
0
  const Token &firstToken = ReplacementTokens.front();
66
0
  const Token &lastToken = ReplacementTokens.back();
67
0
  SourceLocation macroStart = firstToken.getLocation();
68
0
  SourceLocation macroEnd = lastToken.getLocation();
69
0
  assert(macroStart.isValid() && macroEnd.isValid());
70
0
  assert((macroStart.isFileID() || firstToken.is(tok::comment)) &&
71
0
         "Macro defined in macro?");
72
0
  assert((macroEnd.isFileID() || lastToken.is(tok::comment)) &&
73
0
         "Macro defined in macro?");
74
0
  std::pair<FileID, unsigned>
75
0
      startInfo = SM.getDecomposedExpansionLoc(macroStart);
76
0
  std::pair<FileID, unsigned>
77
0
      endInfo = SM.getDecomposedExpansionLoc(macroEnd);
78
0
  assert(startInfo.first == endInfo.first &&
79
0
         "Macro definition spanning multiple FileIDs ?");
80
0
  assert(startInfo.second <= endInfo.second);
81
0
  DefinitionLength = endInfo.second - startInfo.second;
82
0
  DefinitionLength += lastToken.getLength();
83
84
0
  return DefinitionLength;
85
0
}
86
87
/// Return true if the specified macro definition is equal to
88
/// this macro in spelling, arguments, and whitespace.
89
///
90
/// \param Syntactically if true, the macro definitions can be identical even
91
/// if they use different identifiers for the function macro parameters.
92
/// Otherwise the comparison is lexical and this implements the rules in
93
/// C99 6.10.3.
94
bool MacroInfo::isIdenticalTo(const MacroInfo &Other, Preprocessor &PP,
95
0
                              bool Syntactically) const {
96
0
  bool Lexically = !Syntactically;
97
98
  // Check # tokens in replacement, number of args, and various flags all match.
99
0
  if (getNumTokens() != Other.getNumTokens() ||
100
0
      getNumParams() != Other.getNumParams() ||
101
0
      isFunctionLike() != Other.isFunctionLike() ||
102
0
      isC99Varargs() != Other.isC99Varargs() ||
103
0
      isGNUVarargs() != Other.isGNUVarargs())
104
0
    return false;
105
106
0
  if (Lexically) {
107
    // Check arguments.
108
0
    for (param_iterator I = param_begin(), OI = Other.param_begin(),
109
0
                        E = param_end();
110
0
         I != E; ++I, ++OI)
111
0
      if (*I != *OI) return false;
112
0
  }
113
114
  // Check all the tokens.
115
0
  for (unsigned i = 0; i != NumReplacementTokens; ++i) {
116
0
    const Token &A = ReplacementTokens[i];
117
0
    const Token &B = Other.ReplacementTokens[i];
118
0
    if (A.getKind() != B.getKind())
119
0
      return false;
120
121
    // If this isn't the first token, check that the whitespace and
122
    // start-of-line characteristics match.
123
0
    if (i != 0 &&
124
0
        (A.isAtStartOfLine() != B.isAtStartOfLine() ||
125
0
         A.hasLeadingSpace() != B.hasLeadingSpace()))
126
0
      return false;
127
128
    // If this is an identifier, it is easy.
129
0
    if (A.getIdentifierInfo() || B.getIdentifierInfo()) {
130
0
      if (A.getIdentifierInfo() == B.getIdentifierInfo())
131
0
        continue;
132
0
      if (Lexically)
133
0
        return false;
134
      // With syntactic equivalence the parameter names can be different as long
135
      // as they are used in the same place.
136
0
      int AArgNum = getParameterNum(A.getIdentifierInfo());
137
0
      if (AArgNum == -1)
138
0
        return false;
139
0
      if (AArgNum != Other.getParameterNum(B.getIdentifierInfo()))
140
0
        return false;
141
0
      continue;
142
0
    }
143
144
    // Otherwise, check the spelling.
145
0
    if (PP.getSpelling(A) != PP.getSpelling(B))
146
0
      return false;
147
0
  }
148
149
0
  return true;
150
0
}
151
152
0
LLVM_DUMP_METHOD void MacroInfo::dump() const {
153
0
  llvm::raw_ostream &Out = llvm::errs();
154
155
  // FIXME: Dump locations.
156
0
  Out << "MacroInfo " << this;
157
0
  if (IsBuiltinMacro) Out << " builtin";
158
0
  if (IsDisabled) Out << " disabled";
159
0
  if (IsUsed) Out << " used";
160
0
  if (IsAllowRedefinitionsWithoutWarning)
161
0
    Out << " allow_redefinitions_without_warning";
162
0
  if (IsWarnIfUnused) Out << " warn_if_unused";
163
0
  if (UsedForHeaderGuard) Out << " header_guard";
164
165
0
  Out << "\n    #define <macro>";
166
0
  if (IsFunctionLike) {
167
0
    Out << "(";
168
0
    for (unsigned I = 0; I != NumParameters; ++I) {
169
0
      if (I) Out << ", ";
170
0
      Out << ParameterList[I]->getName();
171
0
    }
172
0
    if (IsC99Varargs || IsGNUVarargs) {
173
0
      if (NumParameters && IsC99Varargs) Out << ", ";
174
0
      Out << "...";
175
0
    }
176
0
    Out << ")";
177
0
  }
178
179
0
  bool First = true;
180
0
  for (const Token &Tok : tokens()) {
181
    // Leading space is semantically meaningful in a macro definition,
182
    // so preserve it in the dump output.
183
0
    if (First || Tok.hasLeadingSpace())
184
0
      Out << " ";
185
0
    First = false;
186
187
0
    if (const char *Punc = tok::getPunctuatorSpelling(Tok.getKind()))
188
0
      Out << Punc;
189
0
    else if (Tok.isLiteral() && Tok.getLiteralData())
190
0
      Out << StringRef(Tok.getLiteralData(), Tok.getLength());
191
0
    else if (auto *II = Tok.getIdentifierInfo())
192
0
      Out << II->getName();
193
0
    else
194
0
      Out << Tok.getName();
195
0
  }
196
0
}
197
198
19.8k
MacroDirective::DefInfo MacroDirective::getDefinition() {
199
19.8k
  MacroDirective *MD = this;
200
19.8k
  SourceLocation UndefLoc;
201
19.8k
  std::optional<bool> isPublic;
202
19.8k
  for (; MD; MD = MD->getPrevious()) {
203
19.8k
    if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
204
19.8k
      return DefInfo(DefMD, UndefLoc, !isPublic || *isPublic);
205
206
0
    if (UndefMacroDirective *UndefMD = dyn_cast<UndefMacroDirective>(MD)) {
207
0
      UndefLoc = UndefMD->getLocation();
208
0
      continue;
209
0
    }
210
211
0
    VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD);
212
0
    if (!isPublic)
213
0
      isPublic = VisMD->isPublic();
214
0
  }
215
216
0
  return DefInfo(nullptr, UndefLoc, !isPublic || *isPublic);
217
19.8k
}
218
219
const MacroDirective::DefInfo
220
MacroDirective::findDirectiveAtLoc(SourceLocation L,
221
0
                                   const SourceManager &SM) const {
222
0
  assert(L.isValid() && "SourceLocation is invalid.");
223
0
  for (DefInfo Def = getDefinition(); Def; Def = Def.getPreviousDefinition()) {
224
0
    if (Def.getLocation().isInvalid() ||  // For macros defined on the command line.
225
0
        SM.isBeforeInTranslationUnit(Def.getLocation(), L))
226
0
      return (!Def.isUndefined() ||
227
0
              SM.isBeforeInTranslationUnit(L, Def.getUndefLocation()))
228
0
                  ? Def : DefInfo();
229
0
  }
230
0
  return DefInfo();
231
0
}
232
233
0
LLVM_DUMP_METHOD void MacroDirective::dump() const {
234
0
  llvm::raw_ostream &Out = llvm::errs();
235
236
0
  switch (getKind()) {
237
0
  case MD_Define: Out << "DefMacroDirective"; break;
238
0
  case MD_Undefine: Out << "UndefMacroDirective"; break;
239
0
  case MD_Visibility: Out << "VisibilityMacroDirective"; break;
240
0
  }
241
0
  Out << " " << this;
242
  // FIXME: Dump SourceLocation.
243
0
  if (auto *Prev = getPrevious())
244
0
    Out << " prev " << Prev;
245
0
  if (IsFromPCH) Out << " from_pch";
246
247
0
  if (isa<VisibilityMacroDirective>(this))
248
0
    Out << (IsPublic ? " public" : " private");
249
250
0
  if (auto *DMD = dyn_cast<DefMacroDirective>(this)) {
251
0
    if (auto *Info = DMD->getInfo()) {
252
0
      Out << "\n  ";
253
0
      Info->dump();
254
0
    }
255
0
  }
256
0
  Out << "\n";
257
0
}
258
259
ModuleMacro *ModuleMacro::create(Preprocessor &PP, Module *OwningModule,
260
                                 IdentifierInfo *II, MacroInfo *Macro,
261
0
                                 ArrayRef<ModuleMacro *> Overrides) {
262
0
  void *Mem = PP.getPreprocessorAllocator().Allocate(
263
0
      sizeof(ModuleMacro) + sizeof(ModuleMacro *) * Overrides.size(),
264
0
      alignof(ModuleMacro));
265
0
  return new (Mem) ModuleMacro(OwningModule, II, Macro, Overrides);
266
0
}