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