Coverage Report

Created: 2020-02-15 09:57

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Lex/MacroArgs.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- MacroArgs.cpp - Formal argument info for Macros ------------------===//
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 MacroArgs interface.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Lex/MacroArgs.h"
14
#include "clang/Lex/LexDiagnostic.h"
15
#include "clang/Lex/MacroInfo.h"
16
#include "clang/Lex/Preprocessor.h"
17
#include "llvm/ADT/SmallString.h"
18
#include "llvm/Support/SaveAndRestore.h"
19
#include <algorithm>
20
21
using namespace clang;
22
23
/// MacroArgs ctor function - This destroys the vector passed in.
24
MacroArgs *MacroArgs::create(const MacroInfo *MI,
25
                             ArrayRef<Token> UnexpArgTokens,
26
36.2M
                             bool VarargsElided, Preprocessor &PP) {
27
36.2M
  assert(MI->isFunctionLike() &&
28
36.2M
         "Can't have args for an object-like macro!");
29
36.2M
  MacroArgs **ResultEnt = nullptr;
30
36.2M
  unsigned ClosestMatch = ~0U;
31
36.2M
32
36.2M
  // See if we have an entry with a big enough argument list to reuse on the
33
36.2M
  // free list.  If so, reuse it.
34
127M
  for (MacroArgs **Entry = &PP.MacroArgCache; *Entry;
35
127M
       
Entry = &(*Entry)->ArgCache91.5M
) {
36
127M
    if ((*Entry)->NumUnexpArgTokens >= UnexpArgTokens.size() &&
37
127M
        
(*Entry)->NumUnexpArgTokens < ClosestMatch80.8M
) {
38
64.9M
      ResultEnt = Entry;
39
64.9M
40
64.9M
      // If we have an exact match, use it.
41
64.9M
      if ((*Entry)->NumUnexpArgTokens == UnexpArgTokens.size())
42
35.8M
        break;
43
29.0M
      // Otherwise, use the best fit.
44
29.0M
      ClosestMatch = (*Entry)->NumUnexpArgTokens;
45
29.0M
    }
46
127M
  }
47
36.2M
  MacroArgs *Result;
48
36.2M
  if (!ResultEnt) {
49
100k
    // Allocate memory for a MacroArgs object with the lexer tokens at the end,
50
100k
    // and construct the MacroArgs object.
51
100k
    Result = new (
52
100k
        llvm::safe_malloc(totalSizeToAlloc<Token>(UnexpArgTokens.size())))
53
100k
        MacroArgs(UnexpArgTokens.size(), VarargsElided, MI->getNumParams());
54
36.1M
  } else {
55
36.1M
    Result = *ResultEnt;
56
36.1M
    // Unlink this node from the preprocessors singly linked list.
57
36.1M
    *ResultEnt = Result->ArgCache;
58
36.1M
    Result->NumUnexpArgTokens = UnexpArgTokens.size();
59
36.1M
    Result->VarargsElided = VarargsElided;
60
36.1M
    Result->NumMacroArgs = MI->getNumParams();
61
36.1M
  }
62
36.2M
63
36.2M
  // Copy the actual unexpanded tokens to immediately after the result ptr.
64
36.2M
  if (!UnexpArgTokens.empty()) {
65
36.2M
    static_assert(std::is_trivial<Token>::value,
66
36.2M
                  "assume trivial copyability if copying into the "
67
36.2M
                  "uninitialized array (as opposed to reusing a cached "
68
36.2M
                  "MacroArgs)");
69
36.2M
    std::copy(UnexpArgTokens.begin(), UnexpArgTokens.end(),
70
36.2M
              Result->getTrailingObjects<Token>());
71
36.2M
  }
72
36.2M
73
36.2M
  return Result;
74
36.2M
}
75
76
/// destroy - Destroy and deallocate the memory for this object.
77
///
78
36.2M
void MacroArgs::destroy(Preprocessor &PP) {
79
36.2M
  // Don't clear PreExpArgTokens, just clear the entries.  Clearing the entries
80
36.2M
  // would deallocate the element vectors.
81
241M
  for (unsigned i = 0, e = PreExpArgTokens.size(); i != e; 
++i205M
)
82
205M
    PreExpArgTokens[i].clear();
83
36.2M
84
36.2M
  // Add this to the preprocessor's free list.
85
36.2M
  ArgCache = PP.MacroArgCache;
86
36.2M
  PP.MacroArgCache = this;
87
36.2M
}
88
89
/// deallocate - This should only be called by the Preprocessor when managing
90
/// its freelist.
91
19.0k
MacroArgs *MacroArgs::deallocate() {
92
19.0k
  MacroArgs *Next = ArgCache;
93
19.0k
94
19.0k
  // Run the dtor to deallocate the vectors.
95
19.0k
  this->~MacroArgs();
96
19.0k
  // Release the memory for the object.
97
19.0k
  static_assert(std::is_trivially_destructible<Token>::value,
98
19.0k
                "assume trivially destructible and forego destructors");
99
19.0k
  free(this);
100
19.0k
101
19.0k
  return Next;
102
19.0k
}
103
104
105
/// getArgLength - Given a pointer to an expanded or unexpanded argument,
106
/// return the number of tokens, not counting the EOF, that make up the
107
/// argument.
108
59.2M
unsigned MacroArgs::getArgLength(const Token *ArgPtr) {
109
59.2M
  unsigned NumArgTokens = 0;
110
251M
  for (; ArgPtr->isNot(tok::eof); 
++ArgPtr191M
)
111
191M
    ++NumArgTokens;
112
59.2M
  return NumArgTokens;
113
59.2M
}
114
115
116
/// getUnexpArgument - Return the unexpanded tokens for the specified formal.
117
///
118
60.2M
const Token *MacroArgs::getUnexpArgument(unsigned Arg) const {
119
60.2M
120
60.2M
  assert(Arg < getNumMacroArguments() && "Invalid arg #");
121
60.2M
  // The unexpanded argument tokens start immediately after the MacroArgs object
122
60.2M
  // in memory.
123
60.2M
  const Token *Start = getTrailingObjects<Token>();
124
60.2M
  const Token *Result = Start;
125
60.2M
126
60.2M
  // Scan to find Arg.
127
263M
  for (; Arg; 
++Result203M
) {
128
203M
    assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
129
203M
    if (Result->is(tok::eof))
130
64.2M
      --Arg;
131
203M
  }
132
60.2M
  assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
133
60.2M
  return Result;
134
60.2M
}
135
136
bool MacroArgs::invokedWithVariadicArgument(const MacroInfo *const MI,
137
35
                                            Preprocessor &PP) {
138
35
  if (!MI->isVariadic())
139
0
    return false;
140
35
  const int VariadicArgIndex = getNumMacroArguments() - 1;
141
35
  return getPreExpArgument(VariadicArgIndex, PP).front().isNot(tok::eof);
142
35
}
143
144
/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
145
/// by pre-expansion, return false.  Otherwise, conservatively return true.
146
bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok,
147
41.4M
                                     Preprocessor &PP) const {
148
41.4M
  // If there are no identifiers in the argument list, or if the identifiers are
149
41.4M
  // known to not be macros, pre-expansion won't modify it.
150
179M
  for (; ArgTok->isNot(tok::eof); 
++ArgTok137M
)
151
142M
    if (IdentifierInfo *II = ArgTok->getIdentifierInfo())
152
37.3M
      if (II->hasMacroDefinition())
153
5.16M
        // Return true even though the macro could be a function-like macro
154
5.16M
        // without a following '(' token, or could be disabled, or not visible.
155
5.16M
        return true;
156
41.4M
  
return false36.2M
;
157
41.4M
}
158
159
/// getPreExpArgument - Return the pre-expanded form of the specified
160
/// argument.
161
const std::vector<Token> &MacroArgs::getPreExpArgument(unsigned Arg,
162
5.16M
                                                       Preprocessor &PP) {
163
5.16M
  assert(Arg < getNumMacroArguments() && "Invalid argument number!");
164
5.16M
165
5.16M
  // If we have already computed this, return it.
166
5.16M
  if (PreExpArgTokens.size() < getNumMacroArguments())
167
68.9k
    PreExpArgTokens.resize(getNumMacroArguments());
168
5.16M
169
5.16M
  std::vector<Token> &Result = PreExpArgTokens[Arg];
170
5.16M
  if (!Result.empty()) 
return Result100k
;
171
5.06M
172
5.06M
  SaveAndRestore<bool> PreExpandingMacroArgs(PP.InMacroArgPreExpansion, true);
173
5.06M
174
5.06M
  const Token *AT = getUnexpArgument(Arg);
175
5.06M
  unsigned NumToks = getArgLength(AT)+1;  // Include the EOF.
176
5.06M
177
5.06M
  // Otherwise, we have to pre-expand this argument, populating Result.  To do
178
5.06M
  // this, we set up a fake TokenLexer to lex from the unexpanded argument
179
5.06M
  // list.  With this installed, we lex expanded tokens until we hit the EOF
180
5.06M
  // token at the end of the unexp list.
181
5.06M
  PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,
182
5.06M
                      false /*owns tokens*/, false /*is reinject*/);
183
5.06M
184
5.06M
  // Lex all of the macro-expanded tokens into Result.
185
13.8M
  do {
186
13.8M
    Result.push_back(Token());
187
13.8M
    Token &Tok = Result.back();
188
13.8M
    PP.Lex(Tok);
189
13.8M
  } while (Result.back().isNot(tok::eof));
190
5.06M
191
5.06M
  // Pop the token stream off the top of the stack.  We know that the internal
192
5.06M
  // pointer inside of it is to the "end" of the token stream, but the stack
193
5.06M
  // will not otherwise be popped until the next token is lexed.  The problem is
194
5.06M
  // that the token may be lexed sometime after the vector of tokens itself is
195
5.06M
  // destroyed, which would be badness.
196
5.06M
  if (PP.InCachingLexMode())
197
0
    PP.ExitCachingLexMode();
198
5.06M
  PP.RemoveTopOfLexerStack();
199
5.06M
  return Result;
200
5.06M
}
201
202
203
/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
204
/// tokens into the literal string token that should be produced by the C #
205
/// preprocessor operator.  If Charify is true, then it should be turned into
206
/// a character literal for the Microsoft charize (#@) extension.
207
///
208
Token MacroArgs::StringifyArgument(const Token *ArgToks,
209
                                   Preprocessor &PP, bool Charify,
210
                                   SourceLocation ExpansionLocStart,
211
210k
                                   SourceLocation ExpansionLocEnd) {
212
210k
  Token Tok;
213
210k
  Tok.startToken();
214
210k
  Tok.setKind(Charify ? 
tok::char_constant1
:
tok::string_literal210k
);
215
210k
216
210k
  const Token *ArgTokStart = ArgToks;
217
210k
218
210k
  // Stringify all the tokens.
219
210k
  SmallString<128> Result;
220
210k
  Result += "\"";
221
210k
222
210k
  bool isFirst = true;
223
423k
  for (; ArgToks->isNot(tok::eof); 
++ArgToks213k
) {
224
213k
    const Token &Tok = *ArgToks;
225
213k
    if (!isFirst && 
(2.56k
Tok.hasLeadingSpace()2.56k
||
Tok.isAtStartOfLine()1.84k
))
226
725
      Result += ' ';
227
213k
    isFirst = false;
228
213k
229
213k
    // If this is a string or character constant, escape the token as specified
230
213k
    // by 6.10.3.2p2.
231
213k
    if (tok::isStringLiteral(Tok.getKind()) || // "foo", u8R"x(foo)x"_bar, etc.
232
213k
        
Tok.is(tok::char_constant)213k
|| // 'x'
233
213k
        
Tok.is(tok::wide_char_constant)213k
|| // L'x'.
234
213k
        
Tok.is(tok::utf8_char_constant)213k
|| // u8'x'.
235
213k
        
Tok.is(tok::utf16_char_constant)213k
|| // u'x'.
236
213k
        
Tok.is(tok::utf32_char_constant)213k
) { // U'x'.
237
99
      bool Invalid = false;
238
99
      std::string TokStr = PP.getSpelling(Tok, &Invalid);
239
99
      if (!Invalid) {
240
99
        std::string Str = Lexer::Stringify(TokStr);
241
99
        Result.append(Str.begin(), Str.end());
242
99
      }
243
213k
    } else if (Tok.is(tok::code_completion)) {
244
2
      PP.CodeCompleteNaturalLanguage();
245
213k
    } else {
246
213k
      // Otherwise, just append the token.  Do some gymnastics to get the token
247
213k
      // in place and avoid copies where possible.
248
213k
      unsigned CurStrLen = Result.size();
249
213k
      Result.resize(CurStrLen+Tok.getLength());
250
213k
      const char *BufPtr = Result.data() + CurStrLen;
251
213k
      bool Invalid = false;
252
213k
      unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr, &Invalid);
253
213k
254
213k
      if (!Invalid) {
255
213k
        // If getSpelling returned a pointer to an already uniqued version of
256
213k
        // the string instead of filling in BufPtr, memcpy it onto our string.
257
213k
        if (ActualTokLen && 
BufPtr != &Result[CurStrLen]213k
)
258
213k
          memcpy(&Result[CurStrLen], BufPtr, ActualTokLen);
259
213k
260
213k
        // If the token was dirty, the spelling may be shorter than the token.
261
213k
        if (ActualTokLen != Tok.getLength())
262
0
          Result.resize(CurStrLen+ActualTokLen);
263
213k
      }
264
213k
    }
265
213k
  }
266
210k
267
210k
  // If the last character of the string is a \, and if it isn't escaped, this
268
210k
  // is an invalid string literal, diagnose it as specified in C99.
269
210k
  if (Result.back() == '\\') {
270
0
    // Count the number of consecutive \ characters.  If even, then they are
271
0
    // just escaped backslashes, otherwise it's an error.
272
0
    unsigned FirstNonSlash = Result.size()-2;
273
0
    // Guaranteed to find the starting " if nothing else.
274
0
    while (Result[FirstNonSlash] == '\\')
275
0
      --FirstNonSlash;
276
0
    if ((Result.size()-1-FirstNonSlash) & 1) {
277
0
      // Diagnose errors for things like: #define F(X) #X   /   F(\)
278
0
      PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
279
0
      Result.pop_back();  // remove one of the \'s.
280
0
    }
281
0
  }
282
210k
  Result += '"';
283
210k
284
210k
  // If this is the charify operation and the result is not a legal character
285
210k
  // constant, diagnose it.
286
210k
  if (Charify) {
287
1
    // First step, turn double quotes into single quotes:
288
1
    Result[0] = '\'';
289
1
    Result[Result.size()-1] = '\'';
290
1
291
1
    // Check for bogus character.
292
1
    bool isBad = false;
293
1
    if (Result.size() == 3)
294
1
      isBad = Result[1] == '\'';   // ''' is not legal. '\' already fixed above.
295
0
    else
296
0
      isBad = (Result.size() != 4 || Result[1] != '\\');  // Not '\x'
297
1
298
1
    if (isBad) {
299
0
      PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
300
0
      Result = "' '";  // Use something arbitrary, but legal.
301
0
    }
302
1
  }
303
210k
304
210k
  PP.CreateString(Result, Tok,
305
210k
                  ExpansionLocStart, ExpansionLocEnd);
306
210k
  return Tok;
307
210k
}