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