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