Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Lex/PPExpressions.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- PPExpressions.cpp - Preprocessor Expression Evaluation -----------===//
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 Preprocessor::EvaluateDirectiveExpression method,
10
// which parses and evaluates integer constant expressions for #if directives.
11
//
12
//===----------------------------------------------------------------------===//
13
//
14
// FIXME: implement testing for #assert's.
15
//
16
//===----------------------------------------------------------------------===//
17
18
#include "clang/Basic/IdentifierTable.h"
19
#include "clang/Basic/SourceLocation.h"
20
#include "clang/Basic/SourceManager.h"
21
#include "clang/Basic/TargetInfo.h"
22
#include "clang/Basic/TokenKinds.h"
23
#include "clang/Lex/CodeCompletionHandler.h"
24
#include "clang/Lex/LexDiagnostic.h"
25
#include "clang/Lex/LiteralSupport.h"
26
#include "clang/Lex/MacroInfo.h"
27
#include "clang/Lex/PPCallbacks.h"
28
#include "clang/Lex/Preprocessor.h"
29
#include "clang/Lex/Token.h"
30
#include "llvm/ADT/APSInt.h"
31
#include "llvm/ADT/STLExtras.h"
32
#include "llvm/ADT/SmallString.h"
33
#include "llvm/ADT/StringExtras.h"
34
#include "llvm/ADT/StringRef.h"
35
#include "llvm/Support/ErrorHandling.h"
36
#include "llvm/Support/SaveAndRestore.h"
37
#include <cassert>
38
39
using namespace clang;
40
41
namespace {
42
43
/// PPValue - Represents the value of a subexpression of a preprocessor
44
/// conditional and the source range covered by it.
45
class PPValue {
46
  SourceRange Range;
47
  IdentifierInfo *II = nullptr;
48
49
public:
50
  llvm::APSInt Val;
51
52
  // Default ctor - Construct an 'invalid' PPValue.
53
0
  PPValue(unsigned BitWidth) : Val(BitWidth) {}
54
55
  // If this value was produced by directly evaluating an identifier, produce
56
  // that identifier.
57
0
  IdentifierInfo *getIdentifier() const { return II; }
58
0
  void setIdentifier(IdentifierInfo *II) { this->II = II; }
59
60
0
  unsigned getBitWidth() const { return Val.getBitWidth(); }
61
0
  bool isUnsigned() const { return Val.isUnsigned(); }
62
63
0
  SourceRange getRange() const { return Range; }
64
65
0
  void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); }
66
0
  void setRange(SourceLocation B, SourceLocation E) {
67
0
    Range.setBegin(B); Range.setEnd(E);
68
0
  }
69
0
  void setBegin(SourceLocation L) { Range.setBegin(L); }
70
0
  void setEnd(SourceLocation L) { Range.setEnd(L); }
71
};
72
73
} // end anonymous namespace
74
75
static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
76
                                     Token &PeekTok, bool ValueLive,
77
                                     bool &IncludedUndefinedIds,
78
                                     Preprocessor &PP);
79
80
/// DefinedTracker - This struct is used while parsing expressions to keep track
81
/// of whether !defined(X) has been seen.
82
///
83
/// With this simple scheme, we handle the basic forms:
84
///    !defined(X)   and !defined X
85
/// but we also trivially handle (silly) stuff like:
86
///    !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
87
struct DefinedTracker {
88
  /// Each time a Value is evaluated, it returns information about whether the
89
  /// parsed value is of the form defined(X), !defined(X) or is something else.
90
  enum TrackerState {
91
    DefinedMacro,        // defined(X)
92
    NotDefinedMacro,     // !defined(X)
93
    Unknown              // Something else.
94
  } State;
95
  /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
96
  /// indicates the macro that was checked.
97
  IdentifierInfo *TheMacro;
98
  bool IncludedUndefinedIds = false;
99
};
100
101
/// EvaluateDefined - Process a 'defined(sym)' expression.
102
static bool EvaluateDefined(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
103
0
                            bool ValueLive, Preprocessor &PP) {
104
0
  SourceLocation beginLoc(PeekTok.getLocation());
105
0
  Result.setBegin(beginLoc);
106
107
  // Get the next token, don't expand it.
108
0
  PP.LexUnexpandedNonComment(PeekTok);
109
110
  // Two options, it can either be a pp-identifier or a (.
111
0
  SourceLocation LParenLoc;
112
0
  if (PeekTok.is(tok::l_paren)) {
113
    // Found a paren, remember we saw it and skip it.
114
0
    LParenLoc = PeekTok.getLocation();
115
0
    PP.LexUnexpandedNonComment(PeekTok);
116
0
  }
117
118
0
  if (PeekTok.is(tok::code_completion)) {
119
0
    if (PP.getCodeCompletionHandler())
120
0
      PP.getCodeCompletionHandler()->CodeCompleteMacroName(false);
121
0
    PP.setCodeCompletionReached();
122
0
    PP.LexUnexpandedNonComment(PeekTok);
123
0
  }
124
125
  // If we don't have a pp-identifier now, this is an error.
126
0
  if (PP.CheckMacroName(PeekTok, MU_Other))
127
0
    return true;
128
129
  // Otherwise, we got an identifier, is it defined to something?
130
0
  IdentifierInfo *II = PeekTok.getIdentifierInfo();
131
0
  MacroDefinition Macro = PP.getMacroDefinition(II);
132
0
  Result.Val = !!Macro;
133
0
  Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
134
0
  DT.IncludedUndefinedIds = !Macro;
135
136
0
  PP.emitMacroExpansionWarnings(PeekTok);
137
138
  // If there is a macro, mark it used.
139
0
  if (Result.Val != 0 && ValueLive)
140
0
    PP.markMacroAsUsed(Macro.getMacroInfo());
141
142
  // Save macro token for callback.
143
0
  Token macroToken(PeekTok);
144
145
  // If we are in parens, ensure we have a trailing ).
146
0
  if (LParenLoc.isValid()) {
147
    // Consume identifier.
148
0
    Result.setEnd(PeekTok.getLocation());
149
0
    PP.LexUnexpandedNonComment(PeekTok);
150
151
0
    if (PeekTok.isNot(tok::r_paren)) {
152
0
      PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_after)
153
0
          << "'defined'" << tok::r_paren;
154
0
      PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
155
0
      return true;
156
0
    }
157
    // Consume the ).
158
0
    PP.LexNonComment(PeekTok);
159
0
    Result.setEnd(PeekTok.getLocation());
160
0
  } else {
161
    // Consume identifier.
162
0
    Result.setEnd(PeekTok.getLocation());
163
0
    PP.LexNonComment(PeekTok);
164
0
  }
165
166
  // [cpp.cond]p4:
167
  //   Prior to evaluation, macro invocations in the list of preprocessing
168
  //   tokens that will become the controlling constant expression are replaced
169
  //   (except for those macro names modified by the 'defined' unary operator),
170
  //   just as in normal text. If the token 'defined' is generated as a result
171
  //   of this replacement process or use of the 'defined' unary operator does
172
  //   not match one of the two specified forms prior to macro replacement, the
173
  //   behavior is undefined.
174
  // This isn't an idle threat, consider this program:
175
  //   #define FOO
176
  //   #define BAR defined(FOO)
177
  //   #if BAR
178
  //   ...
179
  //   #else
180
  //   ...
181
  //   #endif
182
  // clang and gcc will pick the #if branch while Visual Studio will take the
183
  // #else branch.  Emit a warning about this undefined behavior.
184
0
  if (beginLoc.isMacroID()) {
185
0
    bool IsFunctionTypeMacro =
186
0
        PP.getSourceManager()
187
0
            .getSLocEntry(PP.getSourceManager().getFileID(beginLoc))
188
0
            .getExpansion()
189
0
            .isFunctionMacroExpansion();
190
    // For object-type macros, it's easy to replace
191
    //   #define FOO defined(BAR)
192
    // with
193
    //   #if defined(BAR)
194
    //   #define FOO 1
195
    //   #else
196
    //   #define FOO 0
197
    //   #endif
198
    // and doing so makes sense since compilers handle this differently in
199
    // practice (see example further up).  But for function-type macros,
200
    // there is no good way to write
201
    //   # define FOO(x) (defined(M_ ## x) && M_ ## x)
202
    // in a different way, and compilers seem to agree on how to behave here.
203
    // So warn by default on object-type macros, but only warn in -pedantic
204
    // mode on function-type macros.
205
0
    if (IsFunctionTypeMacro)
206
0
      PP.Diag(beginLoc, diag::warn_defined_in_function_type_macro);
207
0
    else
208
0
      PP.Diag(beginLoc, diag::warn_defined_in_object_type_macro);
209
0
  }
210
211
  // Invoke the 'defined' callback.
212
0
  if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
213
0
    Callbacks->Defined(macroToken, Macro,
214
0
                       SourceRange(beginLoc, PeekTok.getLocation()));
215
0
  }
216
217
  // Success, remember that we saw defined(X).
218
0
  DT.State = DefinedTracker::DefinedMacro;
219
0
  DT.TheMacro = II;
220
0
  return false;
221
0
}
222
223
/// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
224
/// return the computed value in Result.  Return true if there was an error
225
/// parsing.  This function also returns information about the form of the
226
/// expression in DT.  See above for information on what DT means.
227
///
228
/// If ValueLive is false, then this value is being evaluated in a context where
229
/// the result is not used.  As such, avoid diagnostics that relate to
230
/// evaluation.
231
static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
232
0
                          bool ValueLive, Preprocessor &PP) {
233
0
  DT.State = DefinedTracker::Unknown;
234
235
0
  Result.setIdentifier(nullptr);
236
237
0
  if (PeekTok.is(tok::code_completion)) {
238
0
    if (PP.getCodeCompletionHandler())
239
0
      PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression();
240
0
    PP.setCodeCompletionReached();
241
0
    PP.LexNonComment(PeekTok);
242
0
  }
243
244
0
  switch (PeekTok.getKind()) {
245
0
  default:
246
    // If this token's spelling is a pp-identifier, check to see if it is
247
    // 'defined' or if it is a macro.  Note that we check here because many
248
    // keywords are pp-identifiers, so we can't check the kind.
249
0
    if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
250
      // Handle "defined X" and "defined(X)".
251
0
      if (II->isStr("defined"))
252
0
        return EvaluateDefined(Result, PeekTok, DT, ValueLive, PP);
253
254
0
      if (!II->isCPlusPlusOperatorKeyword()) {
255
        // If this identifier isn't 'defined' or one of the special
256
        // preprocessor keywords and it wasn't macro expanded, it turns
257
        // into a simple 0
258
0
        if (ValueLive) {
259
0
          PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II;
260
261
0
          const DiagnosticsEngine &DiagEngine = PP.getDiagnostics();
262
          // If 'Wundef' is enabled, do not emit 'undef-prefix' diagnostics.
263
0
          if (DiagEngine.isIgnored(diag::warn_pp_undef_identifier,
264
0
                                   PeekTok.getLocation())) {
265
0
            const std::vector<std::string> UndefPrefixes =
266
0
                DiagEngine.getDiagnosticOptions().UndefPrefixes;
267
0
            const StringRef IdentifierName = II->getName();
268
0
            if (llvm::any_of(UndefPrefixes,
269
0
                             [&IdentifierName](const std::string &Prefix) {
270
0
                               return IdentifierName.starts_with(Prefix);
271
0
                             }))
272
0
              PP.Diag(PeekTok, diag::warn_pp_undef_prefix)
273
0
                  << AddFlagValue{llvm::join(UndefPrefixes, ",")} << II;
274
0
          }
275
0
        }
276
0
        Result.Val = 0;
277
0
        Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
278
0
        Result.setIdentifier(II);
279
0
        Result.setRange(PeekTok.getLocation());
280
0
        DT.IncludedUndefinedIds = true;
281
0
        PP.LexNonComment(PeekTok);
282
0
        return false;
283
0
      }
284
0
    }
285
0
    PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
286
0
    return true;
287
0
  case tok::eod:
288
0
  case tok::r_paren:
289
    // If there is no expression, report and exit.
290
0
    PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
291
0
    return true;
292
0
  case tok::numeric_constant: {
293
0
    SmallString<64> IntegerBuffer;
294
0
    bool NumberInvalid = false;
295
0
    StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
296
0
                                              &NumberInvalid);
297
0
    if (NumberInvalid)
298
0
      return true; // a diagnostic was already reported
299
300
0
    NumericLiteralParser Literal(Spelling, PeekTok.getLocation(),
301
0
                                 PP.getSourceManager(), PP.getLangOpts(),
302
0
                                 PP.getTargetInfo(), PP.getDiagnostics());
303
0
    if (Literal.hadError)
304
0
      return true; // a diagnostic was already reported.
305
306
0
    if (Literal.isFloatingLiteral() || Literal.isImaginary) {
307
0
      PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
308
0
      return true;
309
0
    }
310
0
    assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
311
312
    // Complain about, and drop, any ud-suffix.
313
0
    if (Literal.hasUDSuffix())
314
0
      PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
315
316
    // 'long long' is a C99 or C++11 feature.
317
0
    if (!PP.getLangOpts().C99 && Literal.isLongLong) {
318
0
      if (PP.getLangOpts().CPlusPlus)
319
0
        PP.Diag(PeekTok,
320
0
             PP.getLangOpts().CPlusPlus11 ?
321
0
             diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
322
0
      else
323
0
        PP.Diag(PeekTok, diag::ext_c99_longlong);
324
0
    }
325
326
    // 'z/uz' literals are a C++23 feature.
327
0
    if (Literal.isSizeT)
328
0
      PP.Diag(PeekTok, PP.getLangOpts().CPlusPlus
329
0
                           ? PP.getLangOpts().CPlusPlus23
330
0
                                 ? diag::warn_cxx20_compat_size_t_suffix
331
0
                                 : diag::ext_cxx23_size_t_suffix
332
0
                           : diag::err_cxx23_size_t_suffix);
333
334
    // 'wb/uwb' literals are a C23 feature. We explicitly do not support the
335
    // suffix in C++ as an extension because a library-based UDL that resolves
336
    // to a library type may be more appropriate there.
337
0
    if (Literal.isBitInt)
338
0
      PP.Diag(PeekTok, PP.getLangOpts().C23
339
0
                           ? diag::warn_c23_compat_bitint_suffix
340
0
                           : diag::ext_c23_bitint_suffix);
341
342
    // Parse the integer literal into Result.
343
0
    if (Literal.GetIntegerValue(Result.Val)) {
344
      // Overflow parsing integer literal.
345
0
      if (ValueLive)
346
0
        PP.Diag(PeekTok, diag::err_integer_literal_too_large)
347
0
            << /* Unsigned */ 1;
348
0
      Result.Val.setIsUnsigned(true);
349
0
    } else {
350
      // Set the signedness of the result to match whether there was a U suffix
351
      // or not.
352
0
      Result.Val.setIsUnsigned(Literal.isUnsigned);
353
354
      // Detect overflow based on whether the value is signed.  If signed
355
      // and if the value is too large, emit a warning "integer constant is so
356
      // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
357
      // is 64-bits.
358
0
      if (!Literal.isUnsigned && Result.Val.isNegative()) {
359
        // Octal, hexadecimal, and binary literals are implicitly unsigned if
360
        // the value does not fit into a signed integer type.
361
0
        if (ValueLive && Literal.getRadix() == 10)
362
0
          PP.Diag(PeekTok, diag::ext_integer_literal_too_large_for_signed);
363
0
        Result.Val.setIsUnsigned(true);
364
0
      }
365
0
    }
366
367
    // Consume the token.
368
0
    Result.setRange(PeekTok.getLocation());
369
0
    PP.LexNonComment(PeekTok);
370
0
    return false;
371
0
  }
372
0
  case tok::char_constant:          // 'x'
373
0
  case tok::wide_char_constant:     // L'x'
374
0
  case tok::utf8_char_constant:     // u8'x'
375
0
  case tok::utf16_char_constant:    // u'x'
376
0
  case tok::utf32_char_constant: {  // U'x'
377
    // Complain about, and drop, any ud-suffix.
378
0
    if (PeekTok.hasUDSuffix())
379
0
      PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
380
381
0
    SmallString<32> CharBuffer;
382
0
    bool CharInvalid = false;
383
0
    StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
384
0
    if (CharInvalid)
385
0
      return true;
386
387
0
    CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
388
0
                              PeekTok.getLocation(), PP, PeekTok.getKind());
389
0
    if (Literal.hadError())
390
0
      return true;  // A diagnostic was already emitted.
391
392
    // Character literals are always int or wchar_t, expand to intmax_t.
393
0
    const TargetInfo &TI = PP.getTargetInfo();
394
0
    unsigned NumBits;
395
0
    if (Literal.isMultiChar())
396
0
      NumBits = TI.getIntWidth();
397
0
    else if (Literal.isWide())
398
0
      NumBits = TI.getWCharWidth();
399
0
    else if (Literal.isUTF16())
400
0
      NumBits = TI.getChar16Width();
401
0
    else if (Literal.isUTF32())
402
0
      NumBits = TI.getChar32Width();
403
0
    else // char or char8_t
404
0
      NumBits = TI.getCharWidth();
405
406
    // Set the width.
407
0
    llvm::APSInt Val(NumBits);
408
    // Set the value.
409
0
    Val = Literal.getValue();
410
    // Set the signedness. UTF-16 and UTF-32 are always unsigned
411
    // UTF-8 is unsigned if -fchar8_t is specified.
412
0
    if (Literal.isWide())
413
0
      Val.setIsUnsigned(!TargetInfo::isTypeSigned(TI.getWCharType()));
414
0
    else if (Literal.isUTF16() || Literal.isUTF32())
415
0
      Val.setIsUnsigned(true);
416
0
    else if (Literal.isUTF8()) {
417
0
      if (PP.getLangOpts().CPlusPlus)
418
0
        Val.setIsUnsigned(
419
0
            PP.getLangOpts().Char8 ? true : !PP.getLangOpts().CharIsSigned);
420
0
      else
421
0
        Val.setIsUnsigned(true);
422
0
    } else
423
0
      Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
424
425
0
    if (Result.Val.getBitWidth() > Val.getBitWidth()) {
426
0
      Result.Val = Val.extend(Result.Val.getBitWidth());
427
0
    } else {
428
0
      assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
429
0
             "intmax_t smaller than char/wchar_t?");
430
0
      Result.Val = Val;
431
0
    }
432
433
    // Consume the token.
434
0
    Result.setRange(PeekTok.getLocation());
435
0
    PP.LexNonComment(PeekTok);
436
0
    return false;
437
0
  }
438
0
  case tok::l_paren: {
439
0
    SourceLocation Start = PeekTok.getLocation();
440
0
    PP.LexNonComment(PeekTok);  // Eat the (.
441
    // Parse the value and if there are any binary operators involved, parse
442
    // them.
443
0
    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
444
445
    // If this is a silly value like (X), which doesn't need parens, check for
446
    // !(defined X).
447
0
    if (PeekTok.is(tok::r_paren)) {
448
      // Just use DT unmodified as our result.
449
0
    } else {
450
      // Otherwise, we have something like (x+y), and we consumed '(x'.
451
0
      if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive,
452
0
                                   DT.IncludedUndefinedIds, PP))
453
0
        return true;
454
455
0
      if (PeekTok.isNot(tok::r_paren)) {
456
0
        PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
457
0
          << Result.getRange();
458
0
        PP.Diag(Start, diag::note_matching) << tok::l_paren;
459
0
        return true;
460
0
      }
461
0
      DT.State = DefinedTracker::Unknown;
462
0
    }
463
0
    Result.setRange(Start, PeekTok.getLocation());
464
0
    Result.setIdentifier(nullptr);
465
0
    PP.LexNonComment(PeekTok);  // Eat the ).
466
0
    return false;
467
0
  }
468
0
  case tok::plus: {
469
0
    SourceLocation Start = PeekTok.getLocation();
470
    // Unary plus doesn't modify the value.
471
0
    PP.LexNonComment(PeekTok);
472
0
    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
473
0
    Result.setBegin(Start);
474
0
    Result.setIdentifier(nullptr);
475
0
    return false;
476
0
  }
477
0
  case tok::minus: {
478
0
    SourceLocation Loc = PeekTok.getLocation();
479
0
    PP.LexNonComment(PeekTok);
480
0
    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
481
0
    Result.setBegin(Loc);
482
0
    Result.setIdentifier(nullptr);
483
484
    // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
485
0
    Result.Val = -Result.Val;
486
487
    // -MININT is the only thing that overflows.  Unsigned never overflows.
488
0
    bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
489
490
    // If this operator is live and overflowed, report the issue.
491
0
    if (Overflow && ValueLive)
492
0
      PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
493
494
0
    DT.State = DefinedTracker::Unknown;
495
0
    return false;
496
0
  }
497
498
0
  case tok::tilde: {
499
0
    SourceLocation Start = PeekTok.getLocation();
500
0
    PP.LexNonComment(PeekTok);
501
0
    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
502
0
    Result.setBegin(Start);
503
0
    Result.setIdentifier(nullptr);
504
505
    // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
506
0
    Result.Val = ~Result.Val;
507
0
    DT.State = DefinedTracker::Unknown;
508
0
    return false;
509
0
  }
510
511
0
  case tok::exclaim: {
512
0
    SourceLocation Start = PeekTok.getLocation();
513
0
    PP.LexNonComment(PeekTok);
514
0
    if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
515
0
    Result.setBegin(Start);
516
0
    Result.Val = !Result.Val;
517
    // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
518
0
    Result.Val.setIsUnsigned(false);
519
0
    Result.setIdentifier(nullptr);
520
521
0
    if (DT.State == DefinedTracker::DefinedMacro)
522
0
      DT.State = DefinedTracker::NotDefinedMacro;
523
0
    else if (DT.State == DefinedTracker::NotDefinedMacro)
524
0
      DT.State = DefinedTracker::DefinedMacro;
525
0
    return false;
526
0
  }
527
0
  case tok::kw_true:
528
0
  case tok::kw_false:
529
0
    Result.Val = PeekTok.getKind() == tok::kw_true;
530
0
    Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
531
0
    Result.setIdentifier(PeekTok.getIdentifierInfo());
532
0
    Result.setRange(PeekTok.getLocation());
533
0
    PP.LexNonComment(PeekTok);
534
0
    return false;
535
536
  // FIXME: Handle #assert
537
0
  }
538
0
}
539
540
/// getPrecedence - Return the precedence of the specified binary operator
541
/// token.  This returns:
542
///   ~0 - Invalid token.
543
///   14 -> 3 - various operators.
544
///    0 - 'eod' or ')'
545
0
static unsigned getPrecedence(tok::TokenKind Kind) {
546
0
  switch (Kind) {
547
0
  default: return ~0U;
548
0
  case tok::percent:
549
0
  case tok::slash:
550
0
  case tok::star:                 return 14;
551
0
  case tok::plus:
552
0
  case tok::minus:                return 13;
553
0
  case tok::lessless:
554
0
  case tok::greatergreater:       return 12;
555
0
  case tok::lessequal:
556
0
  case tok::less:
557
0
  case tok::greaterequal:
558
0
  case tok::greater:              return 11;
559
0
  case tok::exclaimequal:
560
0
  case tok::equalequal:           return 10;
561
0
  case tok::amp:                  return 9;
562
0
  case tok::caret:                return 8;
563
0
  case tok::pipe:                 return 7;
564
0
  case tok::ampamp:               return 6;
565
0
  case tok::pipepipe:             return 5;
566
0
  case tok::question:             return 4;
567
0
  case tok::comma:                return 3;
568
0
  case tok::colon:                return 2;
569
0
  case tok::r_paren:              return 0;// Lowest priority, end of expr.
570
0
  case tok::eod:                  return 0;// Lowest priority, end of directive.
571
0
  }
572
0
}
573
574
static void diagnoseUnexpectedOperator(Preprocessor &PP, PPValue &LHS,
575
0
                                       Token &Tok) {
576
0
  if (Tok.is(tok::l_paren) && LHS.getIdentifier())
577
0
    PP.Diag(LHS.getRange().getBegin(), diag::err_pp_expr_bad_token_lparen)
578
0
        << LHS.getIdentifier();
579
0
  else
580
0
    PP.Diag(Tok.getLocation(), diag::err_pp_expr_bad_token_binop)
581
0
        << LHS.getRange();
582
0
}
583
584
/// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
585
/// PeekTok, and whose precedence is PeekPrec.  This returns the result in LHS.
586
///
587
/// If ValueLive is false, then this value is being evaluated in a context where
588
/// the result is not used.  As such, avoid diagnostics that relate to
589
/// evaluation, such as division by zero warnings.
590
static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
591
                                     Token &PeekTok, bool ValueLive,
592
                                     bool &IncludedUndefinedIds,
593
0
                                     Preprocessor &PP) {
594
0
  unsigned PeekPrec = getPrecedence(PeekTok.getKind());
595
  // If this token isn't valid, report the error.
596
0
  if (PeekPrec == ~0U) {
597
0
    diagnoseUnexpectedOperator(PP, LHS, PeekTok);
598
0
    return true;
599
0
  }
600
601
0
  while (true) {
602
    // If this token has a lower precedence than we are allowed to parse, return
603
    // it so that higher levels of the recursion can parse it.
604
0
    if (PeekPrec < MinPrec)
605
0
      return false;
606
607
0
    tok::TokenKind Operator = PeekTok.getKind();
608
609
    // If this is a short-circuiting operator, see if the RHS of the operator is
610
    // dead.  Note that this cannot just clobber ValueLive.  Consider
611
    // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)".  In
612
    // this example, the RHS of the && being dead does not make the rest of the
613
    // expr dead.
614
0
    bool RHSIsLive;
615
0
    if (Operator == tok::ampamp && LHS.Val == 0)
616
0
      RHSIsLive = false;   // RHS of "0 && x" is dead.
617
0
    else if (Operator == tok::pipepipe && LHS.Val != 0)
618
0
      RHSIsLive = false;   // RHS of "1 || x" is dead.
619
0
    else if (Operator == tok::question && LHS.Val == 0)
620
0
      RHSIsLive = false;   // RHS (x) of "0 ? x : y" is dead.
621
0
    else
622
0
      RHSIsLive = ValueLive;
623
624
    // Consume the operator, remembering the operator's location for reporting.
625
0
    SourceLocation OpLoc = PeekTok.getLocation();
626
0
    PP.LexNonComment(PeekTok);
627
628
0
    PPValue RHS(LHS.getBitWidth());
629
    // Parse the RHS of the operator.
630
0
    DefinedTracker DT;
631
0
    if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
632
0
    IncludedUndefinedIds = DT.IncludedUndefinedIds;
633
634
    // Remember the precedence of this operator and get the precedence of the
635
    // operator immediately to the right of the RHS.
636
0
    unsigned ThisPrec = PeekPrec;
637
0
    PeekPrec = getPrecedence(PeekTok.getKind());
638
639
    // If this token isn't valid, report the error.
640
0
    if (PeekPrec == ~0U) {
641
0
      diagnoseUnexpectedOperator(PP, RHS, PeekTok);
642
0
      return true;
643
0
    }
644
645
    // Decide whether to include the next binop in this subexpression.  For
646
    // example, when parsing x+y*z and looking at '*', we want to recursively
647
    // handle y*z as a single subexpression.  We do this because the precedence
648
    // of * is higher than that of +.  The only strange case we have to handle
649
    // here is for the ?: operator, where the precedence is actually lower than
650
    // the LHS of the '?'.  The grammar rule is:
651
    //
652
    // conditional-expression ::=
653
    //    logical-OR-expression ? expression : conditional-expression
654
    // where 'expression' is actually comma-expression.
655
0
    unsigned RHSPrec;
656
0
    if (Operator == tok::question)
657
      // The RHS of "?" should be maximally consumed as an expression.
658
0
      RHSPrec = getPrecedence(tok::comma);
659
0
    else  // All others should munch while higher precedence.
660
0
      RHSPrec = ThisPrec+1;
661
662
0
    if (PeekPrec >= RHSPrec) {
663
0
      if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive,
664
0
                                   IncludedUndefinedIds, PP))
665
0
        return true;
666
0
      PeekPrec = getPrecedence(PeekTok.getKind());
667
0
    }
668
0
    assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
669
670
    // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
671
    // either operand is unsigned.
672
0
    llvm::APSInt Res(LHS.getBitWidth());
673
0
    switch (Operator) {
674
0
    case tok::question:       // No UAC for x and y in "x ? y : z".
675
0
    case tok::lessless:       // Shift amount doesn't UAC with shift value.
676
0
    case tok::greatergreater: // Shift amount doesn't UAC with shift value.
677
0
    case tok::comma:          // Comma operands are not subject to UACs.
678
0
    case tok::pipepipe:       // Logical || does not do UACs.
679
0
    case tok::ampamp:         // Logical && does not do UACs.
680
0
      break;                  // No UAC
681
0
    default:
682
0
      Res.setIsUnsigned(LHS.isUnsigned() || RHS.isUnsigned());
683
      // If this just promoted something from signed to unsigned, and if the
684
      // value was negative, warn about it.
685
0
      if (ValueLive && Res.isUnsigned()) {
686
0
        if (!LHS.isUnsigned() && LHS.Val.isNegative())
687
0
          PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 0
688
0
            << toString(LHS.Val, 10, true) + " to " +
689
0
               toString(LHS.Val, 10, false)
690
0
            << LHS.getRange() << RHS.getRange();
691
0
        if (!RHS.isUnsigned() && RHS.Val.isNegative())
692
0
          PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 1
693
0
            << toString(RHS.Val, 10, true) + " to " +
694
0
               toString(RHS.Val, 10, false)
695
0
            << LHS.getRange() << RHS.getRange();
696
0
      }
697
0
      LHS.Val.setIsUnsigned(Res.isUnsigned());
698
0
      RHS.Val.setIsUnsigned(Res.isUnsigned());
699
0
    }
700
701
0
    bool Overflow = false;
702
0
    switch (Operator) {
703
0
    default: llvm_unreachable("Unknown operator token!");
704
0
    case tok::percent:
705
0
      if (RHS.Val != 0)
706
0
        Res = LHS.Val % RHS.Val;
707
0
      else if (ValueLive) {
708
0
        PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
709
0
          << LHS.getRange() << RHS.getRange();
710
0
        return true;
711
0
      }
712
0
      break;
713
0
    case tok::slash:
714
0
      if (RHS.Val != 0) {
715
0
        if (LHS.Val.isSigned())
716
0
          Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
717
0
        else
718
0
          Res = LHS.Val / RHS.Val;
719
0
      } else if (ValueLive) {
720
0
        PP.Diag(OpLoc, diag::err_pp_division_by_zero)
721
0
          << LHS.getRange() << RHS.getRange();
722
0
        return true;
723
0
      }
724
0
      break;
725
726
0
    case tok::star:
727
0
      if (Res.isSigned())
728
0
        Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
729
0
      else
730
0
        Res = LHS.Val * RHS.Val;
731
0
      break;
732
0
    case tok::lessless: {
733
      // Determine whether overflow is about to happen.
734
0
      if (LHS.isUnsigned())
735
0
        Res = LHS.Val.ushl_ov(RHS.Val, Overflow);
736
0
      else
737
0
        Res = llvm::APSInt(LHS.Val.sshl_ov(RHS.Val, Overflow), false);
738
0
      break;
739
0
    }
740
0
    case tok::greatergreater: {
741
      // Determine whether overflow is about to happen.
742
0
      unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
743
0
      if (ShAmt >= LHS.getBitWidth()) {
744
0
        Overflow = true;
745
0
        ShAmt = LHS.getBitWidth()-1;
746
0
      }
747
0
      Res = LHS.Val >> ShAmt;
748
0
      break;
749
0
    }
750
0
    case tok::plus:
751
0
      if (LHS.isUnsigned())
752
0
        Res = LHS.Val + RHS.Val;
753
0
      else
754
0
        Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
755
0
      break;
756
0
    case tok::minus:
757
0
      if (LHS.isUnsigned())
758
0
        Res = LHS.Val - RHS.Val;
759
0
      else
760
0
        Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
761
0
      break;
762
0
    case tok::lessequal:
763
0
      Res = LHS.Val <= RHS.Val;
764
0
      Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
765
0
      break;
766
0
    case tok::less:
767
0
      Res = LHS.Val < RHS.Val;
768
0
      Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
769
0
      break;
770
0
    case tok::greaterequal:
771
0
      Res = LHS.Val >= RHS.Val;
772
0
      Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
773
0
      break;
774
0
    case tok::greater:
775
0
      Res = LHS.Val > RHS.Val;
776
0
      Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
777
0
      break;
778
0
    case tok::exclaimequal:
779
0
      Res = LHS.Val != RHS.Val;
780
0
      Res.setIsUnsigned(false);  // C99 6.5.9p3, result is always int (signed)
781
0
      break;
782
0
    case tok::equalequal:
783
0
      Res = LHS.Val == RHS.Val;
784
0
      Res.setIsUnsigned(false);  // C99 6.5.9p3, result is always int (signed)
785
0
      break;
786
0
    case tok::amp:
787
0
      Res = LHS.Val & RHS.Val;
788
0
      break;
789
0
    case tok::caret:
790
0
      Res = LHS.Val ^ RHS.Val;
791
0
      break;
792
0
    case tok::pipe:
793
0
      Res = LHS.Val | RHS.Val;
794
0
      break;
795
0
    case tok::ampamp:
796
0
      Res = (LHS.Val != 0 && RHS.Val != 0);
797
0
      Res.setIsUnsigned(false);  // C99 6.5.13p3, result is always int (signed)
798
0
      break;
799
0
    case tok::pipepipe:
800
0
      Res = (LHS.Val != 0 || RHS.Val != 0);
801
0
      Res.setIsUnsigned(false);  // C99 6.5.14p3, result is always int (signed)
802
0
      break;
803
0
    case tok::comma:
804
      // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
805
      // if not being evaluated.
806
0
      if (!PP.getLangOpts().C99 || ValueLive)
807
0
        PP.Diag(OpLoc, diag::ext_pp_comma_expr)
808
0
          << LHS.getRange() << RHS.getRange();
809
0
      Res = RHS.Val; // LHS = LHS,RHS -> RHS.
810
0
      break;
811
0
    case tok::question: {
812
      // Parse the : part of the expression.
813
0
      if (PeekTok.isNot(tok::colon)) {
814
0
        PP.Diag(PeekTok.getLocation(), diag::err_expected)
815
0
            << tok::colon << LHS.getRange() << RHS.getRange();
816
0
        PP.Diag(OpLoc, diag::note_matching) << tok::question;
817
0
        return true;
818
0
      }
819
      // Consume the :.
820
0
      PP.LexNonComment(PeekTok);
821
822
      // Evaluate the value after the :.
823
0
      bool AfterColonLive = ValueLive && LHS.Val == 0;
824
0
      PPValue AfterColonVal(LHS.getBitWidth());
825
0
      DefinedTracker DT;
826
0
      if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
827
0
        return true;
828
829
      // Parse anything after the : with the same precedence as ?.  We allow
830
      // things of equal precedence because ?: is right associative.
831
0
      if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
832
0
                                   PeekTok, AfterColonLive,
833
0
                                   IncludedUndefinedIds, PP))
834
0
        return true;
835
836
      // Now that we have the condition, the LHS and the RHS of the :, evaluate.
837
0
      Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
838
0
      RHS.setEnd(AfterColonVal.getRange().getEnd());
839
840
      // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
841
      // either operand is unsigned.
842
0
      Res.setIsUnsigned(RHS.isUnsigned() || AfterColonVal.isUnsigned());
843
844
      // Figure out the precedence of the token after the : part.
845
0
      PeekPrec = getPrecedence(PeekTok.getKind());
846
0
      break;
847
0
    }
848
0
    case tok::colon:
849
      // Don't allow :'s to float around without being part of ?: exprs.
850
0
      PP.Diag(OpLoc, diag::err_pp_colon_without_question)
851
0
        << LHS.getRange() << RHS.getRange();
852
0
      return true;
853
0
    }
854
855
    // If this operator is live and overflowed, report the issue.
856
0
    if (Overflow && ValueLive)
857
0
      PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
858
0
        << LHS.getRange() << RHS.getRange();
859
860
    // Put the result back into 'LHS' for our next iteration.
861
0
    LHS.Val = Res;
862
0
    LHS.setEnd(RHS.getRange().getEnd());
863
0
    RHS.setIdentifier(nullptr);
864
0
  }
865
0
}
866
867
/// EvaluateDirectiveExpression - Evaluate an integer constant expression that
868
/// may occur after a #if or #elif directive.  If the expression is equivalent
869
/// to "!defined(X)" return X in IfNDefMacro.
870
Preprocessor::DirectiveEvalResult
871
0
Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
872
0
  SaveAndRestore PPDir(ParsingIfOrElifDirective, true);
873
  // Save the current state of 'DisableMacroExpansion' and reset it to false. If
874
  // 'DisableMacroExpansion' is true, then we must be in a macro argument list
875
  // in which case a directive is undefined behavior.  We want macros to be able
876
  // to recursively expand in order to get more gcc-list behavior, so we force
877
  // DisableMacroExpansion to false and restore it when we're done parsing the
878
  // expression.
879
0
  bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
880
0
  DisableMacroExpansion = false;
881
882
  // Peek ahead one token.
883
0
  Token Tok;
884
0
  LexNonComment(Tok);
885
886
  // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
887
0
  unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
888
889
0
  PPValue ResVal(BitWidth);
890
0
  DefinedTracker DT;
891
0
  SourceLocation ExprStartLoc = SourceMgr.getExpansionLoc(Tok.getLocation());
892
0
  if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
893
    // Parse error, skip the rest of the macro line.
894
0
    SourceRange ConditionRange = ExprStartLoc;
895
0
    if (Tok.isNot(tok::eod))
896
0
      ConditionRange = DiscardUntilEndOfDirective();
897
898
    // Restore 'DisableMacroExpansion'.
899
0
    DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
900
901
    // We cannot trust the source range from the value because there was a
902
    // parse error. Track the range manually -- the end of the directive is the
903
    // end of the condition range.
904
0
    return {false,
905
0
            DT.IncludedUndefinedIds,
906
0
            {ExprStartLoc, ConditionRange.getEnd()}};
907
0
  }
908
909
  // If we are at the end of the expression after just parsing a value, there
910
  // must be no (unparenthesized) binary operators involved, so we can exit
911
  // directly.
912
0
  if (Tok.is(tok::eod)) {
913
    // If the expression we parsed was of the form !defined(macro), return the
914
    // macro in IfNDefMacro.
915
0
    if (DT.State == DefinedTracker::NotDefinedMacro)
916
0
      IfNDefMacro = DT.TheMacro;
917
918
    // Restore 'DisableMacroExpansion'.
919
0
    DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
920
0
    return {ResVal.Val != 0, DT.IncludedUndefinedIds, ResVal.getRange()};
921
0
  }
922
923
  // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
924
  // operator and the stuff after it.
925
0
  if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
926
0
                               Tok, true, DT.IncludedUndefinedIds, *this)) {
927
    // Parse error, skip the rest of the macro line.
928
0
    if (Tok.isNot(tok::eod))
929
0
      DiscardUntilEndOfDirective();
930
931
    // Restore 'DisableMacroExpansion'.
932
0
    DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
933
0
    return {false, DT.IncludedUndefinedIds, ResVal.getRange()};
934
0
  }
935
936
  // If we aren't at the tok::eod token, something bad happened, like an extra
937
  // ')' token.
938
0
  if (Tok.isNot(tok::eod)) {
939
0
    Diag(Tok, diag::err_pp_expected_eol);
940
0
    DiscardUntilEndOfDirective();
941
0
  }
942
943
  // Restore 'DisableMacroExpansion'.
944
0
  DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
945
0
  return {ResVal.Val != 0, DT.IncludedUndefinedIds, ResVal.getRange()};
946
0
}