xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Lex/PPExpressions.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===--- PPExpressions.cpp - Preprocessor Expression Evaluation -----------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This file implements the Preprocessor::EvaluateDirectiveExpression method,
107330f729Sjoerg // which parses and evaluates integer constant expressions for #if directives.
117330f729Sjoerg //
127330f729Sjoerg //===----------------------------------------------------------------------===//
137330f729Sjoerg //
147330f729Sjoerg // FIXME: implement testing for #assert's.
157330f729Sjoerg //
167330f729Sjoerg //===----------------------------------------------------------------------===//
177330f729Sjoerg 
187330f729Sjoerg #include "clang/Basic/IdentifierTable.h"
197330f729Sjoerg #include "clang/Basic/SourceLocation.h"
207330f729Sjoerg #include "clang/Basic/SourceManager.h"
217330f729Sjoerg #include "clang/Basic/TargetInfo.h"
227330f729Sjoerg #include "clang/Basic/TokenKinds.h"
237330f729Sjoerg #include "clang/Lex/CodeCompletionHandler.h"
247330f729Sjoerg #include "clang/Lex/LexDiagnostic.h"
257330f729Sjoerg #include "clang/Lex/LiteralSupport.h"
267330f729Sjoerg #include "clang/Lex/MacroInfo.h"
277330f729Sjoerg #include "clang/Lex/PPCallbacks.h"
28*e038c9c4Sjoerg #include "clang/Lex/Preprocessor.h"
297330f729Sjoerg #include "clang/Lex/Token.h"
307330f729Sjoerg #include "llvm/ADT/APSInt.h"
31*e038c9c4Sjoerg #include "llvm/ADT/STLExtras.h"
327330f729Sjoerg #include "llvm/ADT/SmallString.h"
33*e038c9c4Sjoerg #include "llvm/ADT/StringExtras.h"
347330f729Sjoerg #include "llvm/ADT/StringRef.h"
357330f729Sjoerg #include "llvm/Support/ErrorHandling.h"
367330f729Sjoerg #include "llvm/Support/SaveAndRestore.h"
377330f729Sjoerg #include <cassert>
387330f729Sjoerg 
397330f729Sjoerg using namespace clang;
407330f729Sjoerg 
417330f729Sjoerg namespace {
427330f729Sjoerg 
437330f729Sjoerg /// PPValue - Represents the value of a subexpression of a preprocessor
447330f729Sjoerg /// conditional and the source range covered by it.
457330f729Sjoerg class PPValue {
467330f729Sjoerg   SourceRange Range;
477330f729Sjoerg   IdentifierInfo *II;
487330f729Sjoerg 
497330f729Sjoerg public:
507330f729Sjoerg   llvm::APSInt Val;
517330f729Sjoerg 
527330f729Sjoerg   // Default ctor - Construct an 'invalid' PPValue.
PPValue(unsigned BitWidth)537330f729Sjoerg   PPValue(unsigned BitWidth) : Val(BitWidth) {}
547330f729Sjoerg 
557330f729Sjoerg   // If this value was produced by directly evaluating an identifier, produce
567330f729Sjoerg   // that identifier.
getIdentifier() const577330f729Sjoerg   IdentifierInfo *getIdentifier() const { return II; }
setIdentifier(IdentifierInfo * II)587330f729Sjoerg   void setIdentifier(IdentifierInfo *II) { this->II = II; }
597330f729Sjoerg 
getBitWidth() const607330f729Sjoerg   unsigned getBitWidth() const { return Val.getBitWidth(); }
isUnsigned() const617330f729Sjoerg   bool isUnsigned() const { return Val.isUnsigned(); }
627330f729Sjoerg 
getRange() const637330f729Sjoerg   SourceRange getRange() const { return Range; }
647330f729Sjoerg 
setRange(SourceLocation L)657330f729Sjoerg   void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); }
setRange(SourceLocation B,SourceLocation E)667330f729Sjoerg   void setRange(SourceLocation B, SourceLocation E) {
677330f729Sjoerg     Range.setBegin(B); Range.setEnd(E);
687330f729Sjoerg   }
setBegin(SourceLocation L)697330f729Sjoerg   void setBegin(SourceLocation L) { Range.setBegin(L); }
setEnd(SourceLocation L)707330f729Sjoerg   void setEnd(SourceLocation L) { Range.setEnd(L); }
717330f729Sjoerg };
727330f729Sjoerg 
737330f729Sjoerg } // end anonymous namespace
747330f729Sjoerg 
757330f729Sjoerg static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
767330f729Sjoerg                                      Token &PeekTok, bool ValueLive,
777330f729Sjoerg                                      bool &IncludedUndefinedIds,
787330f729Sjoerg                                      Preprocessor &PP);
797330f729Sjoerg 
807330f729Sjoerg /// DefinedTracker - This struct is used while parsing expressions to keep track
817330f729Sjoerg /// of whether !defined(X) has been seen.
827330f729Sjoerg ///
837330f729Sjoerg /// With this simple scheme, we handle the basic forms:
847330f729Sjoerg ///    !defined(X)   and !defined X
857330f729Sjoerg /// but we also trivially handle (silly) stuff like:
867330f729Sjoerg ///    !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
877330f729Sjoerg struct DefinedTracker {
887330f729Sjoerg   /// Each time a Value is evaluated, it returns information about whether the
897330f729Sjoerg   /// parsed value is of the form defined(X), !defined(X) or is something else.
907330f729Sjoerg   enum TrackerState {
917330f729Sjoerg     DefinedMacro,        // defined(X)
927330f729Sjoerg     NotDefinedMacro,     // !defined(X)
937330f729Sjoerg     Unknown              // Something else.
947330f729Sjoerg   } State;
957330f729Sjoerg   /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
967330f729Sjoerg   /// indicates the macro that was checked.
977330f729Sjoerg   IdentifierInfo *TheMacro;
987330f729Sjoerg   bool IncludedUndefinedIds = false;
997330f729Sjoerg };
1007330f729Sjoerg 
1017330f729Sjoerg /// EvaluateDefined - Process a 'defined(sym)' expression.
EvaluateDefined(PPValue & Result,Token & PeekTok,DefinedTracker & DT,bool ValueLive,Preprocessor & PP)1027330f729Sjoerg static bool EvaluateDefined(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
1037330f729Sjoerg                             bool ValueLive, Preprocessor &PP) {
1047330f729Sjoerg   SourceLocation beginLoc(PeekTok.getLocation());
1057330f729Sjoerg   Result.setBegin(beginLoc);
1067330f729Sjoerg 
1077330f729Sjoerg   // Get the next token, don't expand it.
1087330f729Sjoerg   PP.LexUnexpandedNonComment(PeekTok);
1097330f729Sjoerg 
1107330f729Sjoerg   // Two options, it can either be a pp-identifier or a (.
1117330f729Sjoerg   SourceLocation LParenLoc;
1127330f729Sjoerg   if (PeekTok.is(tok::l_paren)) {
1137330f729Sjoerg     // Found a paren, remember we saw it and skip it.
1147330f729Sjoerg     LParenLoc = PeekTok.getLocation();
1157330f729Sjoerg     PP.LexUnexpandedNonComment(PeekTok);
1167330f729Sjoerg   }
1177330f729Sjoerg 
1187330f729Sjoerg   if (PeekTok.is(tok::code_completion)) {
1197330f729Sjoerg     if (PP.getCodeCompletionHandler())
1207330f729Sjoerg       PP.getCodeCompletionHandler()->CodeCompleteMacroName(false);
1217330f729Sjoerg     PP.setCodeCompletionReached();
1227330f729Sjoerg     PP.LexUnexpandedNonComment(PeekTok);
1237330f729Sjoerg   }
1247330f729Sjoerg 
1257330f729Sjoerg   // If we don't have a pp-identifier now, this is an error.
1267330f729Sjoerg   if (PP.CheckMacroName(PeekTok, MU_Other))
1277330f729Sjoerg     return true;
1287330f729Sjoerg 
1297330f729Sjoerg   // Otherwise, we got an identifier, is it defined to something?
1307330f729Sjoerg   IdentifierInfo *II = PeekTok.getIdentifierInfo();
1317330f729Sjoerg   MacroDefinition Macro = PP.getMacroDefinition(II);
1327330f729Sjoerg   Result.Val = !!Macro;
1337330f729Sjoerg   Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
1347330f729Sjoerg   DT.IncludedUndefinedIds = !Macro;
1357330f729Sjoerg 
1367330f729Sjoerg   // If there is a macro, mark it used.
1377330f729Sjoerg   if (Result.Val != 0 && ValueLive)
1387330f729Sjoerg     PP.markMacroAsUsed(Macro.getMacroInfo());
1397330f729Sjoerg 
1407330f729Sjoerg   // Save macro token for callback.
1417330f729Sjoerg   Token macroToken(PeekTok);
1427330f729Sjoerg 
1437330f729Sjoerg   // If we are in parens, ensure we have a trailing ).
1447330f729Sjoerg   if (LParenLoc.isValid()) {
1457330f729Sjoerg     // Consume identifier.
1467330f729Sjoerg     Result.setEnd(PeekTok.getLocation());
1477330f729Sjoerg     PP.LexUnexpandedNonComment(PeekTok);
1487330f729Sjoerg 
1497330f729Sjoerg     if (PeekTok.isNot(tok::r_paren)) {
1507330f729Sjoerg       PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_after)
1517330f729Sjoerg           << "'defined'" << tok::r_paren;
1527330f729Sjoerg       PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1537330f729Sjoerg       return true;
1547330f729Sjoerg     }
1557330f729Sjoerg     // Consume the ).
1567330f729Sjoerg     PP.LexNonComment(PeekTok);
1577330f729Sjoerg     Result.setEnd(PeekTok.getLocation());
1587330f729Sjoerg   } else {
1597330f729Sjoerg     // Consume identifier.
1607330f729Sjoerg     Result.setEnd(PeekTok.getLocation());
1617330f729Sjoerg     PP.LexNonComment(PeekTok);
1627330f729Sjoerg   }
1637330f729Sjoerg 
1647330f729Sjoerg   // [cpp.cond]p4:
1657330f729Sjoerg   //   Prior to evaluation, macro invocations in the list of preprocessing
1667330f729Sjoerg   //   tokens that will become the controlling constant expression are replaced
1677330f729Sjoerg   //   (except for those macro names modified by the 'defined' unary operator),
1687330f729Sjoerg   //   just as in normal text. If the token 'defined' is generated as a result
1697330f729Sjoerg   //   of this replacement process or use of the 'defined' unary operator does
1707330f729Sjoerg   //   not match one of the two specified forms prior to macro replacement, the
1717330f729Sjoerg   //   behavior is undefined.
1727330f729Sjoerg   // This isn't an idle threat, consider this program:
1737330f729Sjoerg   //   #define FOO
1747330f729Sjoerg   //   #define BAR defined(FOO)
1757330f729Sjoerg   //   #if BAR
1767330f729Sjoerg   //   ...
1777330f729Sjoerg   //   #else
1787330f729Sjoerg   //   ...
1797330f729Sjoerg   //   #endif
1807330f729Sjoerg   // clang and gcc will pick the #if branch while Visual Studio will take the
1817330f729Sjoerg   // #else branch.  Emit a warning about this undefined behavior.
1827330f729Sjoerg   if (beginLoc.isMacroID()) {
1837330f729Sjoerg     bool IsFunctionTypeMacro =
1847330f729Sjoerg         PP.getSourceManager()
1857330f729Sjoerg             .getSLocEntry(PP.getSourceManager().getFileID(beginLoc))
1867330f729Sjoerg             .getExpansion()
1877330f729Sjoerg             .isFunctionMacroExpansion();
1887330f729Sjoerg     // For object-type macros, it's easy to replace
1897330f729Sjoerg     //   #define FOO defined(BAR)
1907330f729Sjoerg     // with
1917330f729Sjoerg     //   #if defined(BAR)
1927330f729Sjoerg     //   #define FOO 1
1937330f729Sjoerg     //   #else
1947330f729Sjoerg     //   #define FOO 0
1957330f729Sjoerg     //   #endif
1967330f729Sjoerg     // and doing so makes sense since compilers handle this differently in
1977330f729Sjoerg     // practice (see example further up).  But for function-type macros,
1987330f729Sjoerg     // there is no good way to write
1997330f729Sjoerg     //   # define FOO(x) (defined(M_ ## x) && M_ ## x)
2007330f729Sjoerg     // in a different way, and compilers seem to agree on how to behave here.
2017330f729Sjoerg     // So warn by default on object-type macros, but only warn in -pedantic
2027330f729Sjoerg     // mode on function-type macros.
2037330f729Sjoerg     if (IsFunctionTypeMacro)
2047330f729Sjoerg       PP.Diag(beginLoc, diag::warn_defined_in_function_type_macro);
2057330f729Sjoerg     else
2067330f729Sjoerg       PP.Diag(beginLoc, diag::warn_defined_in_object_type_macro);
2077330f729Sjoerg   }
2087330f729Sjoerg 
2097330f729Sjoerg   // Invoke the 'defined' callback.
2107330f729Sjoerg   if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
2117330f729Sjoerg     Callbacks->Defined(macroToken, Macro,
2127330f729Sjoerg                        SourceRange(beginLoc, PeekTok.getLocation()));
2137330f729Sjoerg   }
2147330f729Sjoerg 
2157330f729Sjoerg   // Success, remember that we saw defined(X).
2167330f729Sjoerg   DT.State = DefinedTracker::DefinedMacro;
2177330f729Sjoerg   DT.TheMacro = II;
2187330f729Sjoerg   return false;
2197330f729Sjoerg }
2207330f729Sjoerg 
2217330f729Sjoerg /// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
2227330f729Sjoerg /// return the computed value in Result.  Return true if there was an error
2237330f729Sjoerg /// parsing.  This function also returns information about the form of the
2247330f729Sjoerg /// expression in DT.  See above for information on what DT means.
2257330f729Sjoerg ///
2267330f729Sjoerg /// If ValueLive is false, then this value is being evaluated in a context where
2277330f729Sjoerg /// the result is not used.  As such, avoid diagnostics that relate to
2287330f729Sjoerg /// evaluation.
EvaluateValue(PPValue & Result,Token & PeekTok,DefinedTracker & DT,bool ValueLive,Preprocessor & PP)2297330f729Sjoerg static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
2307330f729Sjoerg                           bool ValueLive, Preprocessor &PP) {
2317330f729Sjoerg   DT.State = DefinedTracker::Unknown;
2327330f729Sjoerg 
2337330f729Sjoerg   Result.setIdentifier(nullptr);
2347330f729Sjoerg 
2357330f729Sjoerg   if (PeekTok.is(tok::code_completion)) {
2367330f729Sjoerg     if (PP.getCodeCompletionHandler())
2377330f729Sjoerg       PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression();
2387330f729Sjoerg     PP.setCodeCompletionReached();
2397330f729Sjoerg     PP.LexNonComment(PeekTok);
2407330f729Sjoerg   }
2417330f729Sjoerg 
2427330f729Sjoerg   switch (PeekTok.getKind()) {
2437330f729Sjoerg   default:
2447330f729Sjoerg     // If this token's spelling is a pp-identifier, check to see if it is
2457330f729Sjoerg     // 'defined' or if it is a macro.  Note that we check here because many
2467330f729Sjoerg     // keywords are pp-identifiers, so we can't check the kind.
2477330f729Sjoerg     if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
2487330f729Sjoerg       // Handle "defined X" and "defined(X)".
2497330f729Sjoerg       if (II->isStr("defined"))
2507330f729Sjoerg         return EvaluateDefined(Result, PeekTok, DT, ValueLive, PP);
2517330f729Sjoerg 
2527330f729Sjoerg       if (!II->isCPlusPlusOperatorKeyword()) {
2537330f729Sjoerg         // If this identifier isn't 'defined' or one of the special
2547330f729Sjoerg         // preprocessor keywords and it wasn't macro expanded, it turns
2557330f729Sjoerg         // into a simple 0
256*e038c9c4Sjoerg         if (ValueLive) {
2577330f729Sjoerg           PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II;
258*e038c9c4Sjoerg 
259*e038c9c4Sjoerg           const DiagnosticsEngine &DiagEngine = PP.getDiagnostics();
260*e038c9c4Sjoerg           // If 'Wundef' is enabled, do not emit 'undef-prefix' diagnostics.
261*e038c9c4Sjoerg           if (DiagEngine.isIgnored(diag::warn_pp_undef_identifier,
262*e038c9c4Sjoerg                                    PeekTok.getLocation())) {
263*e038c9c4Sjoerg             const std::vector<std::string> UndefPrefixes =
264*e038c9c4Sjoerg                 DiagEngine.getDiagnosticOptions().UndefPrefixes;
265*e038c9c4Sjoerg             const StringRef IdentifierName = II->getName();
266*e038c9c4Sjoerg             if (llvm::any_of(UndefPrefixes,
267*e038c9c4Sjoerg                              [&IdentifierName](const std::string &Prefix) {
268*e038c9c4Sjoerg                                return IdentifierName.startswith(Prefix);
269*e038c9c4Sjoerg                              }))
270*e038c9c4Sjoerg               PP.Diag(PeekTok, diag::warn_pp_undef_prefix)
271*e038c9c4Sjoerg                   << AddFlagValue{llvm::join(UndefPrefixes, ",")} << II;
272*e038c9c4Sjoerg           }
273*e038c9c4Sjoerg         }
2747330f729Sjoerg         Result.Val = 0;
2757330f729Sjoerg         Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
2767330f729Sjoerg         Result.setIdentifier(II);
2777330f729Sjoerg         Result.setRange(PeekTok.getLocation());
2787330f729Sjoerg         DT.IncludedUndefinedIds = true;
2797330f729Sjoerg         PP.LexNonComment(PeekTok);
2807330f729Sjoerg         return false;
2817330f729Sjoerg       }
2827330f729Sjoerg     }
2837330f729Sjoerg     PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
2847330f729Sjoerg     return true;
2857330f729Sjoerg   case tok::eod:
2867330f729Sjoerg   case tok::r_paren:
2877330f729Sjoerg     // If there is no expression, report and exit.
2887330f729Sjoerg     PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
2897330f729Sjoerg     return true;
2907330f729Sjoerg   case tok::numeric_constant: {
2917330f729Sjoerg     SmallString<64> IntegerBuffer;
2927330f729Sjoerg     bool NumberInvalid = false;
2937330f729Sjoerg     StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
2947330f729Sjoerg                                               &NumberInvalid);
2957330f729Sjoerg     if (NumberInvalid)
2967330f729Sjoerg       return true; // a diagnostic was already reported
2977330f729Sjoerg 
298*e038c9c4Sjoerg     NumericLiteralParser Literal(Spelling, PeekTok.getLocation(),
299*e038c9c4Sjoerg                                  PP.getSourceManager(), PP.getLangOpts(),
300*e038c9c4Sjoerg                                  PP.getTargetInfo(), PP.getDiagnostics());
3017330f729Sjoerg     if (Literal.hadError)
3027330f729Sjoerg       return true; // a diagnostic was already reported.
3037330f729Sjoerg 
3047330f729Sjoerg     if (Literal.isFloatingLiteral() || Literal.isImaginary) {
3057330f729Sjoerg       PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
3067330f729Sjoerg       return true;
3077330f729Sjoerg     }
3087330f729Sjoerg     assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
3097330f729Sjoerg 
3107330f729Sjoerg     // Complain about, and drop, any ud-suffix.
3117330f729Sjoerg     if (Literal.hasUDSuffix())
3127330f729Sjoerg       PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
3137330f729Sjoerg 
3147330f729Sjoerg     // 'long long' is a C99 or C++11 feature.
3157330f729Sjoerg     if (!PP.getLangOpts().C99 && Literal.isLongLong) {
3167330f729Sjoerg       if (PP.getLangOpts().CPlusPlus)
3177330f729Sjoerg         PP.Diag(PeekTok,
3187330f729Sjoerg              PP.getLangOpts().CPlusPlus11 ?
3197330f729Sjoerg              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3207330f729Sjoerg       else
3217330f729Sjoerg         PP.Diag(PeekTok, diag::ext_c99_longlong);
3227330f729Sjoerg     }
3237330f729Sjoerg 
324*e038c9c4Sjoerg     // 'z/uz' literals are a C++2b feature.
325*e038c9c4Sjoerg     if (Literal.isSizeT)
326*e038c9c4Sjoerg       PP.Diag(PeekTok, PP.getLangOpts().CPlusPlus
327*e038c9c4Sjoerg                            ? PP.getLangOpts().CPlusPlus2b
328*e038c9c4Sjoerg                                  ? diag::warn_cxx20_compat_size_t_suffix
329*e038c9c4Sjoerg                                  : diag::ext_cxx2b_size_t_suffix
330*e038c9c4Sjoerg                            : diag::err_cxx2b_size_t_suffix);
331*e038c9c4Sjoerg 
3327330f729Sjoerg     // Parse the integer literal into Result.
3337330f729Sjoerg     if (Literal.GetIntegerValue(Result.Val)) {
3347330f729Sjoerg       // Overflow parsing integer literal.
3357330f729Sjoerg       if (ValueLive)
3367330f729Sjoerg         PP.Diag(PeekTok, diag::err_integer_literal_too_large)
3377330f729Sjoerg             << /* Unsigned */ 1;
3387330f729Sjoerg       Result.Val.setIsUnsigned(true);
3397330f729Sjoerg     } else {
3407330f729Sjoerg       // Set the signedness of the result to match whether there was a U suffix
3417330f729Sjoerg       // or not.
3427330f729Sjoerg       Result.Val.setIsUnsigned(Literal.isUnsigned);
3437330f729Sjoerg 
3447330f729Sjoerg       // Detect overflow based on whether the value is signed.  If signed
3457330f729Sjoerg       // and if the value is too large, emit a warning "integer constant is so
3467330f729Sjoerg       // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
3477330f729Sjoerg       // is 64-bits.
3487330f729Sjoerg       if (!Literal.isUnsigned && Result.Val.isNegative()) {
3497330f729Sjoerg         // Octal, hexadecimal, and binary literals are implicitly unsigned if
3507330f729Sjoerg         // the value does not fit into a signed integer type.
3517330f729Sjoerg         if (ValueLive && Literal.getRadix() == 10)
3527330f729Sjoerg           PP.Diag(PeekTok, diag::ext_integer_literal_too_large_for_signed);
3537330f729Sjoerg         Result.Val.setIsUnsigned(true);
3547330f729Sjoerg       }
3557330f729Sjoerg     }
3567330f729Sjoerg 
3577330f729Sjoerg     // Consume the token.
3587330f729Sjoerg     Result.setRange(PeekTok.getLocation());
3597330f729Sjoerg     PP.LexNonComment(PeekTok);
3607330f729Sjoerg     return false;
3617330f729Sjoerg   }
3627330f729Sjoerg   case tok::char_constant:          // 'x'
3637330f729Sjoerg   case tok::wide_char_constant:     // L'x'
3647330f729Sjoerg   case tok::utf8_char_constant:     // u8'x'
3657330f729Sjoerg   case tok::utf16_char_constant:    // u'x'
3667330f729Sjoerg   case tok::utf32_char_constant: {  // U'x'
3677330f729Sjoerg     // Complain about, and drop, any ud-suffix.
3687330f729Sjoerg     if (PeekTok.hasUDSuffix())
3697330f729Sjoerg       PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
3707330f729Sjoerg 
3717330f729Sjoerg     SmallString<32> CharBuffer;
3727330f729Sjoerg     bool CharInvalid = false;
3737330f729Sjoerg     StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
3747330f729Sjoerg     if (CharInvalid)
3757330f729Sjoerg       return true;
3767330f729Sjoerg 
3777330f729Sjoerg     CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
3787330f729Sjoerg                               PeekTok.getLocation(), PP, PeekTok.getKind());
3797330f729Sjoerg     if (Literal.hadError())
3807330f729Sjoerg       return true;  // A diagnostic was already emitted.
3817330f729Sjoerg 
3827330f729Sjoerg     // Character literals are always int or wchar_t, expand to intmax_t.
3837330f729Sjoerg     const TargetInfo &TI = PP.getTargetInfo();
3847330f729Sjoerg     unsigned NumBits;
3857330f729Sjoerg     if (Literal.isMultiChar())
3867330f729Sjoerg       NumBits = TI.getIntWidth();
3877330f729Sjoerg     else if (Literal.isWide())
3887330f729Sjoerg       NumBits = TI.getWCharWidth();
3897330f729Sjoerg     else if (Literal.isUTF16())
3907330f729Sjoerg       NumBits = TI.getChar16Width();
3917330f729Sjoerg     else if (Literal.isUTF32())
3927330f729Sjoerg       NumBits = TI.getChar32Width();
3937330f729Sjoerg     else // char or char8_t
3947330f729Sjoerg       NumBits = TI.getCharWidth();
3957330f729Sjoerg 
3967330f729Sjoerg     // Set the width.
3977330f729Sjoerg     llvm::APSInt Val(NumBits);
3987330f729Sjoerg     // Set the value.
3997330f729Sjoerg     Val = Literal.getValue();
4007330f729Sjoerg     // Set the signedness. UTF-16 and UTF-32 are always unsigned
4017330f729Sjoerg     if (Literal.isWide())
4027330f729Sjoerg       Val.setIsUnsigned(!TargetInfo::isTypeSigned(TI.getWCharType()));
4037330f729Sjoerg     else if (!Literal.isUTF16() && !Literal.isUTF32())
4047330f729Sjoerg       Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
4057330f729Sjoerg 
4067330f729Sjoerg     if (Result.Val.getBitWidth() > Val.getBitWidth()) {
4077330f729Sjoerg       Result.Val = Val.extend(Result.Val.getBitWidth());
4087330f729Sjoerg     } else {
4097330f729Sjoerg       assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
4107330f729Sjoerg              "intmax_t smaller than char/wchar_t?");
4117330f729Sjoerg       Result.Val = Val;
4127330f729Sjoerg     }
4137330f729Sjoerg 
4147330f729Sjoerg     // Consume the token.
4157330f729Sjoerg     Result.setRange(PeekTok.getLocation());
4167330f729Sjoerg     PP.LexNonComment(PeekTok);
4177330f729Sjoerg     return false;
4187330f729Sjoerg   }
4197330f729Sjoerg   case tok::l_paren: {
4207330f729Sjoerg     SourceLocation Start = PeekTok.getLocation();
4217330f729Sjoerg     PP.LexNonComment(PeekTok);  // Eat the (.
4227330f729Sjoerg     // Parse the value and if there are any binary operators involved, parse
4237330f729Sjoerg     // them.
4247330f729Sjoerg     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
4257330f729Sjoerg 
4267330f729Sjoerg     // If this is a silly value like (X), which doesn't need parens, check for
4277330f729Sjoerg     // !(defined X).
4287330f729Sjoerg     if (PeekTok.is(tok::r_paren)) {
4297330f729Sjoerg       // Just use DT unmodified as our result.
4307330f729Sjoerg     } else {
4317330f729Sjoerg       // Otherwise, we have something like (x+y), and we consumed '(x'.
4327330f729Sjoerg       if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive,
4337330f729Sjoerg                                    DT.IncludedUndefinedIds, PP))
4347330f729Sjoerg         return true;
4357330f729Sjoerg 
4367330f729Sjoerg       if (PeekTok.isNot(tok::r_paren)) {
4377330f729Sjoerg         PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
4387330f729Sjoerg           << Result.getRange();
4397330f729Sjoerg         PP.Diag(Start, diag::note_matching) << tok::l_paren;
4407330f729Sjoerg         return true;
4417330f729Sjoerg       }
4427330f729Sjoerg       DT.State = DefinedTracker::Unknown;
4437330f729Sjoerg     }
4447330f729Sjoerg     Result.setRange(Start, PeekTok.getLocation());
4457330f729Sjoerg     Result.setIdentifier(nullptr);
4467330f729Sjoerg     PP.LexNonComment(PeekTok);  // Eat the ).
4477330f729Sjoerg     return false;
4487330f729Sjoerg   }
4497330f729Sjoerg   case tok::plus: {
4507330f729Sjoerg     SourceLocation Start = PeekTok.getLocation();
4517330f729Sjoerg     // Unary plus doesn't modify the value.
4527330f729Sjoerg     PP.LexNonComment(PeekTok);
4537330f729Sjoerg     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
4547330f729Sjoerg     Result.setBegin(Start);
4557330f729Sjoerg     Result.setIdentifier(nullptr);
4567330f729Sjoerg     return false;
4577330f729Sjoerg   }
4587330f729Sjoerg   case tok::minus: {
4597330f729Sjoerg     SourceLocation Loc = PeekTok.getLocation();
4607330f729Sjoerg     PP.LexNonComment(PeekTok);
4617330f729Sjoerg     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
4627330f729Sjoerg     Result.setBegin(Loc);
4637330f729Sjoerg     Result.setIdentifier(nullptr);
4647330f729Sjoerg 
4657330f729Sjoerg     // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
4667330f729Sjoerg     Result.Val = -Result.Val;
4677330f729Sjoerg 
4687330f729Sjoerg     // -MININT is the only thing that overflows.  Unsigned never overflows.
4697330f729Sjoerg     bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
4707330f729Sjoerg 
4717330f729Sjoerg     // If this operator is live and overflowed, report the issue.
4727330f729Sjoerg     if (Overflow && ValueLive)
4737330f729Sjoerg       PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
4747330f729Sjoerg 
4757330f729Sjoerg     DT.State = DefinedTracker::Unknown;
4767330f729Sjoerg     return false;
4777330f729Sjoerg   }
4787330f729Sjoerg 
4797330f729Sjoerg   case tok::tilde: {
4807330f729Sjoerg     SourceLocation Start = PeekTok.getLocation();
4817330f729Sjoerg     PP.LexNonComment(PeekTok);
4827330f729Sjoerg     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
4837330f729Sjoerg     Result.setBegin(Start);
4847330f729Sjoerg     Result.setIdentifier(nullptr);
4857330f729Sjoerg 
4867330f729Sjoerg     // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
4877330f729Sjoerg     Result.Val = ~Result.Val;
4887330f729Sjoerg     DT.State = DefinedTracker::Unknown;
4897330f729Sjoerg     return false;
4907330f729Sjoerg   }
4917330f729Sjoerg 
4927330f729Sjoerg   case tok::exclaim: {
4937330f729Sjoerg     SourceLocation Start = PeekTok.getLocation();
4947330f729Sjoerg     PP.LexNonComment(PeekTok);
4957330f729Sjoerg     if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
4967330f729Sjoerg     Result.setBegin(Start);
4977330f729Sjoerg     Result.Val = !Result.Val;
4987330f729Sjoerg     // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
4997330f729Sjoerg     Result.Val.setIsUnsigned(false);
5007330f729Sjoerg     Result.setIdentifier(nullptr);
5017330f729Sjoerg 
5027330f729Sjoerg     if (DT.State == DefinedTracker::DefinedMacro)
5037330f729Sjoerg       DT.State = DefinedTracker::NotDefinedMacro;
5047330f729Sjoerg     else if (DT.State == DefinedTracker::NotDefinedMacro)
5057330f729Sjoerg       DT.State = DefinedTracker::DefinedMacro;
5067330f729Sjoerg     return false;
5077330f729Sjoerg   }
5087330f729Sjoerg   case tok::kw_true:
5097330f729Sjoerg   case tok::kw_false:
5107330f729Sjoerg     Result.Val = PeekTok.getKind() == tok::kw_true;
5117330f729Sjoerg     Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
5127330f729Sjoerg     Result.setIdentifier(PeekTok.getIdentifierInfo());
5137330f729Sjoerg     Result.setRange(PeekTok.getLocation());
5147330f729Sjoerg     PP.LexNonComment(PeekTok);
5157330f729Sjoerg     return false;
5167330f729Sjoerg 
5177330f729Sjoerg   // FIXME: Handle #assert
5187330f729Sjoerg   }
5197330f729Sjoerg }
5207330f729Sjoerg 
5217330f729Sjoerg /// getPrecedence - Return the precedence of the specified binary operator
5227330f729Sjoerg /// token.  This returns:
5237330f729Sjoerg ///   ~0 - Invalid token.
5247330f729Sjoerg ///   14 -> 3 - various operators.
5257330f729Sjoerg ///    0 - 'eod' or ')'
getPrecedence(tok::TokenKind Kind)5267330f729Sjoerg static unsigned getPrecedence(tok::TokenKind Kind) {
5277330f729Sjoerg   switch (Kind) {
5287330f729Sjoerg   default: return ~0U;
5297330f729Sjoerg   case tok::percent:
5307330f729Sjoerg   case tok::slash:
5317330f729Sjoerg   case tok::star:                 return 14;
5327330f729Sjoerg   case tok::plus:
5337330f729Sjoerg   case tok::minus:                return 13;
5347330f729Sjoerg   case tok::lessless:
5357330f729Sjoerg   case tok::greatergreater:       return 12;
5367330f729Sjoerg   case tok::lessequal:
5377330f729Sjoerg   case tok::less:
5387330f729Sjoerg   case tok::greaterequal:
5397330f729Sjoerg   case tok::greater:              return 11;
5407330f729Sjoerg   case tok::exclaimequal:
5417330f729Sjoerg   case tok::equalequal:           return 10;
5427330f729Sjoerg   case tok::amp:                  return 9;
5437330f729Sjoerg   case tok::caret:                return 8;
5447330f729Sjoerg   case tok::pipe:                 return 7;
5457330f729Sjoerg   case tok::ampamp:               return 6;
5467330f729Sjoerg   case tok::pipepipe:             return 5;
5477330f729Sjoerg   case tok::question:             return 4;
5487330f729Sjoerg   case tok::comma:                return 3;
5497330f729Sjoerg   case tok::colon:                return 2;
5507330f729Sjoerg   case tok::r_paren:              return 0;// Lowest priority, end of expr.
5517330f729Sjoerg   case tok::eod:                  return 0;// Lowest priority, end of directive.
5527330f729Sjoerg   }
5537330f729Sjoerg }
5547330f729Sjoerg 
diagnoseUnexpectedOperator(Preprocessor & PP,PPValue & LHS,Token & Tok)5557330f729Sjoerg static void diagnoseUnexpectedOperator(Preprocessor &PP, PPValue &LHS,
5567330f729Sjoerg                                        Token &Tok) {
5577330f729Sjoerg   if (Tok.is(tok::l_paren) && LHS.getIdentifier())
5587330f729Sjoerg     PP.Diag(LHS.getRange().getBegin(), diag::err_pp_expr_bad_token_lparen)
5597330f729Sjoerg         << LHS.getIdentifier();
5607330f729Sjoerg   else
5617330f729Sjoerg     PP.Diag(Tok.getLocation(), diag::err_pp_expr_bad_token_binop)
5627330f729Sjoerg         << LHS.getRange();
5637330f729Sjoerg }
5647330f729Sjoerg 
5657330f729Sjoerg /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
5667330f729Sjoerg /// PeekTok, and whose precedence is PeekPrec.  This returns the result in LHS.
5677330f729Sjoerg ///
5687330f729Sjoerg /// If ValueLive is false, then this value is being evaluated in a context where
5697330f729Sjoerg /// the result is not used.  As such, avoid diagnostics that relate to
5707330f729Sjoerg /// evaluation, such as division by zero warnings.
EvaluateDirectiveSubExpr(PPValue & LHS,unsigned MinPrec,Token & PeekTok,bool ValueLive,bool & IncludedUndefinedIds,Preprocessor & PP)5717330f729Sjoerg static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
5727330f729Sjoerg                                      Token &PeekTok, bool ValueLive,
5737330f729Sjoerg                                      bool &IncludedUndefinedIds,
5747330f729Sjoerg                                      Preprocessor &PP) {
5757330f729Sjoerg   unsigned PeekPrec = getPrecedence(PeekTok.getKind());
5767330f729Sjoerg   // If this token isn't valid, report the error.
5777330f729Sjoerg   if (PeekPrec == ~0U) {
5787330f729Sjoerg     diagnoseUnexpectedOperator(PP, LHS, PeekTok);
5797330f729Sjoerg     return true;
5807330f729Sjoerg   }
5817330f729Sjoerg 
5827330f729Sjoerg   while (true) {
5837330f729Sjoerg     // If this token has a lower precedence than we are allowed to parse, return
5847330f729Sjoerg     // it so that higher levels of the recursion can parse it.
5857330f729Sjoerg     if (PeekPrec < MinPrec)
5867330f729Sjoerg       return false;
5877330f729Sjoerg 
5887330f729Sjoerg     tok::TokenKind Operator = PeekTok.getKind();
5897330f729Sjoerg 
5907330f729Sjoerg     // If this is a short-circuiting operator, see if the RHS of the operator is
5917330f729Sjoerg     // dead.  Note that this cannot just clobber ValueLive.  Consider
5927330f729Sjoerg     // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)".  In
5937330f729Sjoerg     // this example, the RHS of the && being dead does not make the rest of the
5947330f729Sjoerg     // expr dead.
5957330f729Sjoerg     bool RHSIsLive;
5967330f729Sjoerg     if (Operator == tok::ampamp && LHS.Val == 0)
5977330f729Sjoerg       RHSIsLive = false;   // RHS of "0 && x" is dead.
5987330f729Sjoerg     else if (Operator == tok::pipepipe && LHS.Val != 0)
5997330f729Sjoerg       RHSIsLive = false;   // RHS of "1 || x" is dead.
6007330f729Sjoerg     else if (Operator == tok::question && LHS.Val == 0)
6017330f729Sjoerg       RHSIsLive = false;   // RHS (x) of "0 ? x : y" is dead.
6027330f729Sjoerg     else
6037330f729Sjoerg       RHSIsLive = ValueLive;
6047330f729Sjoerg 
6057330f729Sjoerg     // Consume the operator, remembering the operator's location for reporting.
6067330f729Sjoerg     SourceLocation OpLoc = PeekTok.getLocation();
6077330f729Sjoerg     PP.LexNonComment(PeekTok);
6087330f729Sjoerg 
6097330f729Sjoerg     PPValue RHS(LHS.getBitWidth());
6107330f729Sjoerg     // Parse the RHS of the operator.
6117330f729Sjoerg     DefinedTracker DT;
6127330f729Sjoerg     if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
6137330f729Sjoerg     IncludedUndefinedIds = DT.IncludedUndefinedIds;
6147330f729Sjoerg 
6157330f729Sjoerg     // Remember the precedence of this operator and get the precedence of the
6167330f729Sjoerg     // operator immediately to the right of the RHS.
6177330f729Sjoerg     unsigned ThisPrec = PeekPrec;
6187330f729Sjoerg     PeekPrec = getPrecedence(PeekTok.getKind());
6197330f729Sjoerg 
6207330f729Sjoerg     // If this token isn't valid, report the error.
6217330f729Sjoerg     if (PeekPrec == ~0U) {
6227330f729Sjoerg       diagnoseUnexpectedOperator(PP, RHS, PeekTok);
6237330f729Sjoerg       return true;
6247330f729Sjoerg     }
6257330f729Sjoerg 
6267330f729Sjoerg     // Decide whether to include the next binop in this subexpression.  For
6277330f729Sjoerg     // example, when parsing x+y*z and looking at '*', we want to recursively
6287330f729Sjoerg     // handle y*z as a single subexpression.  We do this because the precedence
6297330f729Sjoerg     // of * is higher than that of +.  The only strange case we have to handle
6307330f729Sjoerg     // here is for the ?: operator, where the precedence is actually lower than
6317330f729Sjoerg     // the LHS of the '?'.  The grammar rule is:
6327330f729Sjoerg     //
6337330f729Sjoerg     // conditional-expression ::=
6347330f729Sjoerg     //    logical-OR-expression ? expression : conditional-expression
6357330f729Sjoerg     // where 'expression' is actually comma-expression.
6367330f729Sjoerg     unsigned RHSPrec;
6377330f729Sjoerg     if (Operator == tok::question)
6387330f729Sjoerg       // The RHS of "?" should be maximally consumed as an expression.
6397330f729Sjoerg       RHSPrec = getPrecedence(tok::comma);
6407330f729Sjoerg     else  // All others should munch while higher precedence.
6417330f729Sjoerg       RHSPrec = ThisPrec+1;
6427330f729Sjoerg 
6437330f729Sjoerg     if (PeekPrec >= RHSPrec) {
6447330f729Sjoerg       if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive,
6457330f729Sjoerg                                    IncludedUndefinedIds, PP))
6467330f729Sjoerg         return true;
6477330f729Sjoerg       PeekPrec = getPrecedence(PeekTok.getKind());
6487330f729Sjoerg     }
6497330f729Sjoerg     assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
6507330f729Sjoerg 
6517330f729Sjoerg     // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
6527330f729Sjoerg     // either operand is unsigned.
6537330f729Sjoerg     llvm::APSInt Res(LHS.getBitWidth());
6547330f729Sjoerg     switch (Operator) {
6557330f729Sjoerg     case tok::question:       // No UAC for x and y in "x ? y : z".
6567330f729Sjoerg     case tok::lessless:       // Shift amount doesn't UAC with shift value.
6577330f729Sjoerg     case tok::greatergreater: // Shift amount doesn't UAC with shift value.
6587330f729Sjoerg     case tok::comma:          // Comma operands are not subject to UACs.
6597330f729Sjoerg     case tok::pipepipe:       // Logical || does not do UACs.
6607330f729Sjoerg     case tok::ampamp:         // Logical && does not do UACs.
6617330f729Sjoerg       break;                  // No UAC
6627330f729Sjoerg     default:
6637330f729Sjoerg       Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
6647330f729Sjoerg       // If this just promoted something from signed to unsigned, and if the
6657330f729Sjoerg       // value was negative, warn about it.
6667330f729Sjoerg       if (ValueLive && Res.isUnsigned()) {
6677330f729Sjoerg         if (!LHS.isUnsigned() && LHS.Val.isNegative())
6687330f729Sjoerg           PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 0
6697330f729Sjoerg             << LHS.Val.toString(10, true) + " to " +
6707330f729Sjoerg                LHS.Val.toString(10, false)
6717330f729Sjoerg             << LHS.getRange() << RHS.getRange();
6727330f729Sjoerg         if (!RHS.isUnsigned() && RHS.Val.isNegative())
6737330f729Sjoerg           PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 1
6747330f729Sjoerg             << RHS.Val.toString(10, true) + " to " +
6757330f729Sjoerg                RHS.Val.toString(10, false)
6767330f729Sjoerg             << LHS.getRange() << RHS.getRange();
6777330f729Sjoerg       }
6787330f729Sjoerg       LHS.Val.setIsUnsigned(Res.isUnsigned());
6797330f729Sjoerg       RHS.Val.setIsUnsigned(Res.isUnsigned());
6807330f729Sjoerg     }
6817330f729Sjoerg 
6827330f729Sjoerg     bool Overflow = false;
6837330f729Sjoerg     switch (Operator) {
6847330f729Sjoerg     default: llvm_unreachable("Unknown operator token!");
6857330f729Sjoerg     case tok::percent:
6867330f729Sjoerg       if (RHS.Val != 0)
6877330f729Sjoerg         Res = LHS.Val % RHS.Val;
6887330f729Sjoerg       else if (ValueLive) {
6897330f729Sjoerg         PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
6907330f729Sjoerg           << LHS.getRange() << RHS.getRange();
6917330f729Sjoerg         return true;
6927330f729Sjoerg       }
6937330f729Sjoerg       break;
6947330f729Sjoerg     case tok::slash:
6957330f729Sjoerg       if (RHS.Val != 0) {
6967330f729Sjoerg         if (LHS.Val.isSigned())
6977330f729Sjoerg           Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
6987330f729Sjoerg         else
6997330f729Sjoerg           Res = LHS.Val / RHS.Val;
7007330f729Sjoerg       } else if (ValueLive) {
7017330f729Sjoerg         PP.Diag(OpLoc, diag::err_pp_division_by_zero)
7027330f729Sjoerg           << LHS.getRange() << RHS.getRange();
7037330f729Sjoerg         return true;
7047330f729Sjoerg       }
7057330f729Sjoerg       break;
7067330f729Sjoerg 
7077330f729Sjoerg     case tok::star:
7087330f729Sjoerg       if (Res.isSigned())
7097330f729Sjoerg         Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
7107330f729Sjoerg       else
7117330f729Sjoerg         Res = LHS.Val * RHS.Val;
7127330f729Sjoerg       break;
7137330f729Sjoerg     case tok::lessless: {
7147330f729Sjoerg       // Determine whether overflow is about to happen.
7157330f729Sjoerg       if (LHS.isUnsigned())
7167330f729Sjoerg         Res = LHS.Val.ushl_ov(RHS.Val, Overflow);
7177330f729Sjoerg       else
7187330f729Sjoerg         Res = llvm::APSInt(LHS.Val.sshl_ov(RHS.Val, Overflow), false);
7197330f729Sjoerg       break;
7207330f729Sjoerg     }
7217330f729Sjoerg     case tok::greatergreater: {
7227330f729Sjoerg       // Determine whether overflow is about to happen.
7237330f729Sjoerg       unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
7247330f729Sjoerg       if (ShAmt >= LHS.getBitWidth()) {
7257330f729Sjoerg         Overflow = true;
7267330f729Sjoerg         ShAmt = LHS.getBitWidth()-1;
7277330f729Sjoerg       }
7287330f729Sjoerg       Res = LHS.Val >> ShAmt;
7297330f729Sjoerg       break;
7307330f729Sjoerg     }
7317330f729Sjoerg     case tok::plus:
7327330f729Sjoerg       if (LHS.isUnsigned())
7337330f729Sjoerg         Res = LHS.Val + RHS.Val;
7347330f729Sjoerg       else
7357330f729Sjoerg         Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
7367330f729Sjoerg       break;
7377330f729Sjoerg     case tok::minus:
7387330f729Sjoerg       if (LHS.isUnsigned())
7397330f729Sjoerg         Res = LHS.Val - RHS.Val;
7407330f729Sjoerg       else
7417330f729Sjoerg         Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
7427330f729Sjoerg       break;
7437330f729Sjoerg     case tok::lessequal:
7447330f729Sjoerg       Res = LHS.Val <= RHS.Val;
7457330f729Sjoerg       Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
7467330f729Sjoerg       break;
7477330f729Sjoerg     case tok::less:
7487330f729Sjoerg       Res = LHS.Val < RHS.Val;
7497330f729Sjoerg       Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
7507330f729Sjoerg       break;
7517330f729Sjoerg     case tok::greaterequal:
7527330f729Sjoerg       Res = LHS.Val >= RHS.Val;
7537330f729Sjoerg       Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
7547330f729Sjoerg       break;
7557330f729Sjoerg     case tok::greater:
7567330f729Sjoerg       Res = LHS.Val > RHS.Val;
7577330f729Sjoerg       Res.setIsUnsigned(false);  // C99 6.5.8p6, result is always int (signed)
7587330f729Sjoerg       break;
7597330f729Sjoerg     case tok::exclaimequal:
7607330f729Sjoerg       Res = LHS.Val != RHS.Val;
7617330f729Sjoerg       Res.setIsUnsigned(false);  // C99 6.5.9p3, result is always int (signed)
7627330f729Sjoerg       break;
7637330f729Sjoerg     case tok::equalequal:
7647330f729Sjoerg       Res = LHS.Val == RHS.Val;
7657330f729Sjoerg       Res.setIsUnsigned(false);  // C99 6.5.9p3, result is always int (signed)
7667330f729Sjoerg       break;
7677330f729Sjoerg     case tok::amp:
7687330f729Sjoerg       Res = LHS.Val & RHS.Val;
7697330f729Sjoerg       break;
7707330f729Sjoerg     case tok::caret:
7717330f729Sjoerg       Res = LHS.Val ^ RHS.Val;
7727330f729Sjoerg       break;
7737330f729Sjoerg     case tok::pipe:
7747330f729Sjoerg       Res = LHS.Val | RHS.Val;
7757330f729Sjoerg       break;
7767330f729Sjoerg     case tok::ampamp:
7777330f729Sjoerg       Res = (LHS.Val != 0 && RHS.Val != 0);
7787330f729Sjoerg       Res.setIsUnsigned(false);  // C99 6.5.13p3, result is always int (signed)
7797330f729Sjoerg       break;
7807330f729Sjoerg     case tok::pipepipe:
7817330f729Sjoerg       Res = (LHS.Val != 0 || RHS.Val != 0);
7827330f729Sjoerg       Res.setIsUnsigned(false);  // C99 6.5.14p3, result is always int (signed)
7837330f729Sjoerg       break;
7847330f729Sjoerg     case tok::comma:
7857330f729Sjoerg       // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
7867330f729Sjoerg       // if not being evaluated.
7877330f729Sjoerg       if (!PP.getLangOpts().C99 || ValueLive)
7887330f729Sjoerg         PP.Diag(OpLoc, diag::ext_pp_comma_expr)
7897330f729Sjoerg           << LHS.getRange() << RHS.getRange();
7907330f729Sjoerg       Res = RHS.Val; // LHS = LHS,RHS -> RHS.
7917330f729Sjoerg       break;
7927330f729Sjoerg     case tok::question: {
7937330f729Sjoerg       // Parse the : part of the expression.
7947330f729Sjoerg       if (PeekTok.isNot(tok::colon)) {
7957330f729Sjoerg         PP.Diag(PeekTok.getLocation(), diag::err_expected)
7967330f729Sjoerg             << tok::colon << LHS.getRange() << RHS.getRange();
7977330f729Sjoerg         PP.Diag(OpLoc, diag::note_matching) << tok::question;
7987330f729Sjoerg         return true;
7997330f729Sjoerg       }
8007330f729Sjoerg       // Consume the :.
8017330f729Sjoerg       PP.LexNonComment(PeekTok);
8027330f729Sjoerg 
8037330f729Sjoerg       // Evaluate the value after the :.
8047330f729Sjoerg       bool AfterColonLive = ValueLive && LHS.Val == 0;
8057330f729Sjoerg       PPValue AfterColonVal(LHS.getBitWidth());
8067330f729Sjoerg       DefinedTracker DT;
8077330f729Sjoerg       if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
8087330f729Sjoerg         return true;
8097330f729Sjoerg 
8107330f729Sjoerg       // Parse anything after the : with the same precedence as ?.  We allow
8117330f729Sjoerg       // things of equal precedence because ?: is right associative.
8127330f729Sjoerg       if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
8137330f729Sjoerg                                    PeekTok, AfterColonLive,
8147330f729Sjoerg                                    IncludedUndefinedIds, PP))
8157330f729Sjoerg         return true;
8167330f729Sjoerg 
8177330f729Sjoerg       // Now that we have the condition, the LHS and the RHS of the :, evaluate.
8187330f729Sjoerg       Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
8197330f729Sjoerg       RHS.setEnd(AfterColonVal.getRange().getEnd());
8207330f729Sjoerg 
8217330f729Sjoerg       // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
8227330f729Sjoerg       // either operand is unsigned.
8237330f729Sjoerg       Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
8247330f729Sjoerg 
8257330f729Sjoerg       // Figure out the precedence of the token after the : part.
8267330f729Sjoerg       PeekPrec = getPrecedence(PeekTok.getKind());
8277330f729Sjoerg       break;
8287330f729Sjoerg     }
8297330f729Sjoerg     case tok::colon:
8307330f729Sjoerg       // Don't allow :'s to float around without being part of ?: exprs.
8317330f729Sjoerg       PP.Diag(OpLoc, diag::err_pp_colon_without_question)
8327330f729Sjoerg         << LHS.getRange() << RHS.getRange();
8337330f729Sjoerg       return true;
8347330f729Sjoerg     }
8357330f729Sjoerg 
8367330f729Sjoerg     // If this operator is live and overflowed, report the issue.
8377330f729Sjoerg     if (Overflow && ValueLive)
8387330f729Sjoerg       PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
8397330f729Sjoerg         << LHS.getRange() << RHS.getRange();
8407330f729Sjoerg 
8417330f729Sjoerg     // Put the result back into 'LHS' for our next iteration.
8427330f729Sjoerg     LHS.Val = Res;
8437330f729Sjoerg     LHS.setEnd(RHS.getRange().getEnd());
8447330f729Sjoerg     RHS.setIdentifier(nullptr);
8457330f729Sjoerg   }
8467330f729Sjoerg }
8477330f729Sjoerg 
8487330f729Sjoerg /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
8497330f729Sjoerg /// may occur after a #if or #elif directive.  If the expression is equivalent
8507330f729Sjoerg /// to "!defined(X)" return X in IfNDefMacro.
8517330f729Sjoerg Preprocessor::DirectiveEvalResult
EvaluateDirectiveExpression(IdentifierInfo * & IfNDefMacro)8527330f729Sjoerg Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
8537330f729Sjoerg   SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true);
8547330f729Sjoerg   // Save the current state of 'DisableMacroExpansion' and reset it to false. If
8557330f729Sjoerg   // 'DisableMacroExpansion' is true, then we must be in a macro argument list
8567330f729Sjoerg   // in which case a directive is undefined behavior.  We want macros to be able
8577330f729Sjoerg   // to recursively expand in order to get more gcc-list behavior, so we force
8587330f729Sjoerg   // DisableMacroExpansion to false and restore it when we're done parsing the
8597330f729Sjoerg   // expression.
8607330f729Sjoerg   bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
8617330f729Sjoerg   DisableMacroExpansion = false;
8627330f729Sjoerg 
8637330f729Sjoerg   // Peek ahead one token.
8647330f729Sjoerg   Token Tok;
8657330f729Sjoerg   LexNonComment(Tok);
8667330f729Sjoerg 
8677330f729Sjoerg   // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
8687330f729Sjoerg   unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
8697330f729Sjoerg 
8707330f729Sjoerg   PPValue ResVal(BitWidth);
8717330f729Sjoerg   DefinedTracker DT;
8727330f729Sjoerg   SourceLocation ExprStartLoc = SourceMgr.getExpansionLoc(Tok.getLocation());
8737330f729Sjoerg   if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
8747330f729Sjoerg     // Parse error, skip the rest of the macro line.
8757330f729Sjoerg     SourceRange ConditionRange = ExprStartLoc;
8767330f729Sjoerg     if (Tok.isNot(tok::eod))
8777330f729Sjoerg       ConditionRange = DiscardUntilEndOfDirective();
8787330f729Sjoerg 
8797330f729Sjoerg     // Restore 'DisableMacroExpansion'.
8807330f729Sjoerg     DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
8817330f729Sjoerg 
8827330f729Sjoerg     // We cannot trust the source range from the value because there was a
8837330f729Sjoerg     // parse error. Track the range manually -- the end of the directive is the
8847330f729Sjoerg     // end of the condition range.
8857330f729Sjoerg     return {false,
8867330f729Sjoerg             DT.IncludedUndefinedIds,
8877330f729Sjoerg             {ExprStartLoc, ConditionRange.getEnd()}};
8887330f729Sjoerg   }
8897330f729Sjoerg 
8907330f729Sjoerg   // If we are at the end of the expression after just parsing a value, there
8917330f729Sjoerg   // must be no (unparenthesized) binary operators involved, so we can exit
8927330f729Sjoerg   // directly.
8937330f729Sjoerg   if (Tok.is(tok::eod)) {
8947330f729Sjoerg     // If the expression we parsed was of the form !defined(macro), return the
8957330f729Sjoerg     // macro in IfNDefMacro.
8967330f729Sjoerg     if (DT.State == DefinedTracker::NotDefinedMacro)
8977330f729Sjoerg       IfNDefMacro = DT.TheMacro;
8987330f729Sjoerg 
8997330f729Sjoerg     // Restore 'DisableMacroExpansion'.
9007330f729Sjoerg     DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
9017330f729Sjoerg     return {ResVal.Val != 0, DT.IncludedUndefinedIds, ResVal.getRange()};
9027330f729Sjoerg   }
9037330f729Sjoerg 
9047330f729Sjoerg   // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
9057330f729Sjoerg   // operator and the stuff after it.
9067330f729Sjoerg   if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
9077330f729Sjoerg                                Tok, true, DT.IncludedUndefinedIds, *this)) {
9087330f729Sjoerg     // Parse error, skip the rest of the macro line.
9097330f729Sjoerg     if (Tok.isNot(tok::eod))
9107330f729Sjoerg       DiscardUntilEndOfDirective();
9117330f729Sjoerg 
9127330f729Sjoerg     // Restore 'DisableMacroExpansion'.
9137330f729Sjoerg     DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
9147330f729Sjoerg     return {false, DT.IncludedUndefinedIds, ResVal.getRange()};
9157330f729Sjoerg   }
9167330f729Sjoerg 
9177330f729Sjoerg   // If we aren't at the tok::eod token, something bad happened, like an extra
9187330f729Sjoerg   // ')' token.
9197330f729Sjoerg   if (Tok.isNot(tok::eod)) {
9207330f729Sjoerg     Diag(Tok, diag::err_pp_expected_eol);
9217330f729Sjoerg     DiscardUntilEndOfDirective();
9227330f729Sjoerg   }
9237330f729Sjoerg 
9247330f729Sjoerg   // Restore 'DisableMacroExpansion'.
9257330f729Sjoerg   DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
9267330f729Sjoerg   return {ResVal.Val != 0, DT.IncludedUndefinedIds, ResVal.getRange()};
9277330f729Sjoerg }
928