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