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