SemaExpr.cpp revision 7d5a8769842eb89ea3be4ebd4d8c4ee1cd01dec6
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 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 semantic analysis for expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "Sema.h" 15#include "SemaUtil.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclCXX.h" 18#include "clang/AST/Expr.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/AST/ExprObjC.h" 21#include "clang/Parse/DeclSpec.h" 22#include "clang/Lex/Preprocessor.h" 23#include "clang/Lex/LiteralSupport.h" 24#include "clang/Basic/SourceManager.h" 25#include "clang/Basic/TargetInfo.h" 26#include "llvm/ADT/OwningPtr.h" 27#include "llvm/ADT/SmallString.h" 28#include "llvm/ADT/StringExtras.h" 29using namespace clang; 30 31/// ActOnStringLiteral - The specified tokens were lexed as pasted string 32/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 33/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 34/// multiple tokens. However, the common case is that StringToks points to one 35/// string. 36/// 37Action::ExprResult 38Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 39 assert(NumStringToks && "Must have at least one string!"); 40 41 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target); 42 if (Literal.hadError) 43 return ExprResult(true); 44 45 llvm::SmallVector<SourceLocation, 4> StringTokLocs; 46 for (unsigned i = 0; i != NumStringToks; ++i) 47 StringTokLocs.push_back(StringToks[i].getLocation()); 48 49 // Verify that pascal strings aren't too large. 50 if (Literal.Pascal && Literal.GetStringLength() > 256) 51 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long, 52 SourceRange(StringToks[0].getLocation(), 53 StringToks[NumStringToks-1].getLocation())); 54 55 QualType StrTy = Context.CharTy; 56 if (Literal.AnyWide) StrTy = Context.getWcharType(); 57 if (Literal.Pascal) StrTy = Context.UnsignedCharTy; 58 59 // Get an array type for the string, according to C99 6.4.5. This includes 60 // the nul terminator character as well as the string length for pascal 61 // strings. 62 StrTy = Context.getConstantArrayType(StrTy, 63 llvm::APInt(32, Literal.GetStringLength()+1), 64 ArrayType::Normal, 0); 65 66 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 67 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(), 68 Literal.AnyWide, StrTy, 69 StringToks[0].getLocation(), 70 StringToks[NumStringToks-1].getLocation()); 71} 72 73 74/// ActOnIdentifierExpr - The parser read an identifier in expression context, 75/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this 76/// identifier is used in a function call context. 77Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc, 78 IdentifierInfo &II, 79 bool HasTrailingLParen) { 80 // Could be enum-constant, value decl, instance variable, etc. 81 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S); 82 83 // If this reference is in an Objective-C method, then ivar lookup happens as 84 // well. 85 if (getCurMethodDecl()) { 86 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D); 87 // There are two cases to handle here. 1) scoped lookup could have failed, 88 // in which case we should look for an ivar. 2) scoped lookup could have 89 // found a decl, but that decl is outside the current method (i.e. a global 90 // variable). In these two cases, we do a lookup for an ivar with this 91 // name, if the lookup suceeds, we replace it our current decl. 92 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) { 93 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 94 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) { 95 // FIXME: This should use a new expr for a direct reference, don't turn 96 // this into Self->ivar, just return a BareIVarExpr or something. 97 IdentifierInfo &II = Context.Idents.get("self"); 98 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false); 99 return new ObjCIvarRefExpr(IV, IV->getType(), Loc, 100 static_cast<Expr*>(SelfExpr.Val), true, true); 101 } 102 } 103 if (SD == 0 && !strcmp(II.getName(), "super")) { 104 QualType T = Context.getPointerType(Context.getObjCInterfaceType( 105 getCurMethodDecl()->getClassInterface())); 106 return new ObjCSuperRefExpr(T, Loc); 107 } 108 } 109 110 if (D == 0) { 111 // Otherwise, this could be an implicitly declared function reference (legal 112 // in C90, extension in C99). 113 if (HasTrailingLParen && 114 !getLangOptions().CPlusPlus) // Not in C++. 115 D = ImplicitlyDefineFunction(Loc, II, S); 116 else { 117 // If this name wasn't predeclared and if this is not a function call, 118 // diagnose the problem. 119 return Diag(Loc, diag::err_undeclared_var_use, II.getName()); 120 } 121 } 122 123 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 124 // check if referencing an identifier with __attribute__((deprecated)). 125 if (VD->getAttr<DeprecatedAttr>()) 126 Diag(Loc, diag::warn_deprecated, VD->getName()); 127 128 // Only create DeclRefExpr's for valid Decl's. 129 if (VD->isInvalidDecl()) 130 return true; 131 return new DeclRefExpr(VD, VD->getType(), Loc); 132 } 133 134 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) { 135 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 136 if (MD->isStatic()) 137 // "invalid use of member 'x' in static member function" 138 return Diag(Loc, diag::err_invalid_member_use_in_static_method, 139 FD->getName()); 140 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent()) 141 // "invalid use of nonstatic data member 'x'" 142 return Diag(Loc, diag::err_invalid_non_static_member_use, 143 FD->getName()); 144 145 if (FD->isInvalidDecl()) 146 return true; 147 148 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference. 149 ExprResult ThisExpr = ActOnCXXThis(SourceLocation()); 150 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val), 151 true, FD, Loc, FD->getType()); 152 } 153 154 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName()); 155 } 156 157 if (isa<TypedefDecl>(D)) 158 return Diag(Loc, diag::err_unexpected_typedef, II.getName()); 159 if (isa<ObjCInterfaceDecl>(D)) 160 return Diag(Loc, diag::err_unexpected_interface, II.getName()); 161 if (isa<NamespaceDecl>(D)) 162 return Diag(Loc, diag::err_unexpected_namespace, II.getName()); 163 164 assert(0 && "Invalid decl"); 165 abort(); 166} 167 168Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc, 169 tok::TokenKind Kind) { 170 PreDefinedExpr::IdentType IT; 171 172 switch (Kind) { 173 default: assert(0 && "Unknown simple primary expr!"); 174 case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2] 175 case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break; 176 case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break; 177 } 178 179 // Verify that this is in a function context. 180 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0) 181 return Diag(Loc, diag::err_predef_outside_function); 182 183 // Pre-defined identifiers are of type char[x], where x is the length of the 184 // string. 185 unsigned Length; 186 if (getCurFunctionDecl()) 187 Length = getCurFunctionDecl()->getIdentifier()->getLength(); 188 else 189 Length = getCurMethodDecl()->getSynthesizedMethodSize(); 190 191 llvm::APInt LengthI(32, Length + 1); 192 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const); 193 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 194 return new PreDefinedExpr(Loc, ResTy, IT); 195} 196 197Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 198 llvm::SmallString<16> CharBuffer; 199 CharBuffer.resize(Tok.getLength()); 200 const char *ThisTokBegin = &CharBuffer[0]; 201 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 202 203 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 204 Tok.getLocation(), PP); 205 if (Literal.hadError()) 206 return ExprResult(true); 207 208 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy; 209 210 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type, 211 Tok.getLocation()); 212} 213 214Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) { 215 // fast path for a single digit (which is quite common). A single digit 216 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 217 if (Tok.getLength() == 1) { 218 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation()); 219 220 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy)); 221 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'), 222 Context.IntTy, 223 Tok.getLocation())); 224 } 225 llvm::SmallString<512> IntegerBuffer; 226 IntegerBuffer.resize(Tok.getLength()); 227 const char *ThisTokBegin = &IntegerBuffer[0]; 228 229 // Get the spelling of the token, which eliminates trigraphs, etc. 230 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 231 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 232 Tok.getLocation(), PP); 233 if (Literal.hadError) 234 return ExprResult(true); 235 236 Expr *Res; 237 238 if (Literal.isFloatingLiteral()) { 239 QualType Ty; 240 if (Literal.isFloat) 241 Ty = Context.FloatTy; 242 else if (!Literal.isLong) 243 Ty = Context.DoubleTy; 244 else 245 Ty = Context.LongDoubleTy; 246 247 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 248 249 // isExact will be set by GetFloatValue(). 250 bool isExact = false; 251 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact, 252 Ty, Tok.getLocation()); 253 254 } else if (!Literal.isIntegerLiteral()) { 255 return ExprResult(true); 256 } else { 257 QualType Ty; 258 259 // long long is a C99 feature. 260 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 261 Literal.isLongLong) 262 Diag(Tok.getLocation(), diag::ext_longlong); 263 264 // Get the value in the widest-possible width. 265 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); 266 267 if (Literal.GetIntegerValue(ResultVal)) { 268 // If this value didn't fit into uintmax_t, warn and force to ull. 269 Diag(Tok.getLocation(), diag::warn_integer_too_large); 270 Ty = Context.UnsignedLongLongTy; 271 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 272 "long long is not intmax_t?"); 273 } else { 274 // If this value fits into a ULL, try to figure out what else it fits into 275 // according to the rules of C99 6.4.4.1p5. 276 277 // Octal, Hexadecimal, and integers with a U suffix are allowed to 278 // be an unsigned int. 279 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 280 281 // Check from smallest to largest, picking the smallest type we can. 282 unsigned Width = 0; 283 if (!Literal.isLong && !Literal.isLongLong) { 284 // Are int/unsigned possibilities? 285 unsigned IntSize = Context.Target.getIntWidth(); 286 287 // Does it fit in a unsigned int? 288 if (ResultVal.isIntN(IntSize)) { 289 // Does it fit in a signed int? 290 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 291 Ty = Context.IntTy; 292 else if (AllowUnsigned) 293 Ty = Context.UnsignedIntTy; 294 Width = IntSize; 295 } 296 } 297 298 // Are long/unsigned long possibilities? 299 if (Ty.isNull() && !Literal.isLongLong) { 300 unsigned LongSize = Context.Target.getLongWidth(); 301 302 // Does it fit in a unsigned long? 303 if (ResultVal.isIntN(LongSize)) { 304 // Does it fit in a signed long? 305 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 306 Ty = Context.LongTy; 307 else if (AllowUnsigned) 308 Ty = Context.UnsignedLongTy; 309 Width = LongSize; 310 } 311 } 312 313 // Finally, check long long if needed. 314 if (Ty.isNull()) { 315 unsigned LongLongSize = Context.Target.getLongLongWidth(); 316 317 // Does it fit in a unsigned long long? 318 if (ResultVal.isIntN(LongLongSize)) { 319 // Does it fit in a signed long long? 320 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0) 321 Ty = Context.LongLongTy; 322 else if (AllowUnsigned) 323 Ty = Context.UnsignedLongLongTy; 324 Width = LongLongSize; 325 } 326 } 327 328 // If we still couldn't decide a type, we probably have something that 329 // does not fit in a signed long long, but has no U suffix. 330 if (Ty.isNull()) { 331 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 332 Ty = Context.UnsignedLongLongTy; 333 Width = Context.Target.getLongLongWidth(); 334 } 335 336 if (ResultVal.getBitWidth() != Width) 337 ResultVal.trunc(Width); 338 } 339 340 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation()); 341 } 342 343 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 344 if (Literal.isImaginary) 345 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType())); 346 347 return Res; 348} 349 350Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, 351 ExprTy *Val) { 352 Expr *E = (Expr *)Val; 353 assert((E != 0) && "ActOnParenExpr() missing expr"); 354 return new ParenExpr(L, R, E); 355} 356 357/// The UsualUnaryConversions() function is *not* called by this routine. 358/// See C99 6.3.2.1p[2-4] for more details. 359QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType, 360 SourceLocation OpLoc, bool isSizeof) { 361 // C99 6.5.3.4p1: 362 if (isa<FunctionType>(exprType) && isSizeof) 363 // alignof(function) is allowed. 364 Diag(OpLoc, diag::ext_sizeof_function_type); 365 else if (exprType->isVoidType()) 366 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof"); 367 else if (exprType->isIncompleteType()) { 368 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type : 369 diag::err_alignof_incomplete_type, 370 exprType.getAsString()); 371 return QualType(); // error 372 } 373 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 374 return Context.getSizeType(); 375} 376 377Action::ExprResult Sema:: 378ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof, 379 SourceLocation LPLoc, TypeTy *Ty, 380 SourceLocation RPLoc) { 381 // If error parsing type, ignore. 382 if (Ty == 0) return true; 383 384 // Verify that this is a valid expression. 385 QualType ArgTy = QualType::getFromOpaquePtr(Ty); 386 387 QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof); 388 389 if (resultType.isNull()) 390 return true; 391 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc); 392} 393 394QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) { 395 DefaultFunctionArrayConversion(V); 396 397 // These operators return the element type of a complex type. 398 if (const ComplexType *CT = V->getType()->getAsComplexType()) 399 return CT->getElementType(); 400 401 // Otherwise they pass through real integer and floating point types here. 402 if (V->getType()->isArithmeticType()) 403 return V->getType(); 404 405 // Reject anything else. 406 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString()); 407 return QualType(); 408} 409 410 411 412Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc, 413 tok::TokenKind Kind, 414 ExprTy *Input) { 415 UnaryOperator::Opcode Opc; 416 switch (Kind) { 417 default: assert(0 && "Unknown unary op!"); 418 case tok::plusplus: Opc = UnaryOperator::PostInc; break; 419 case tok::minusminus: Opc = UnaryOperator::PostDec; break; 420 } 421 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc); 422 if (result.isNull()) 423 return true; 424 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc); 425} 426 427Action::ExprResult Sema:: 428ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc, 429 ExprTy *Idx, SourceLocation RLoc) { 430 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx); 431 432 // Perform default conversions. 433 DefaultFunctionArrayConversion(LHSExp); 434 DefaultFunctionArrayConversion(RHSExp); 435 436 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 437 438 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 439 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 440 // in the subscript position. As a result, we need to derive the array base 441 // and index from the expression types. 442 Expr *BaseExpr, *IndexExpr; 443 QualType ResultType; 444 if (const PointerType *PTy = LHSTy->getAsPointerType()) { 445 BaseExpr = LHSExp; 446 IndexExpr = RHSExp; 447 // FIXME: need to deal with const... 448 ResultType = PTy->getPointeeType(); 449 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) { 450 // Handle the uncommon case of "123[Ptr]". 451 BaseExpr = RHSExp; 452 IndexExpr = LHSExp; 453 // FIXME: need to deal with const... 454 ResultType = PTy->getPointeeType(); 455 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) { 456 BaseExpr = LHSExp; // vectors: V[123] 457 IndexExpr = RHSExp; 458 459 // Component access limited to variables (reject vec4.rg[1]). 460 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) && 461 !isa<ExtVectorElementExpr>(BaseExpr)) 462 return Diag(LLoc, diag::err_ext_vector_component_access, 463 SourceRange(LLoc, RLoc)); 464 // FIXME: need to deal with const... 465 ResultType = VTy->getElementType(); 466 } else { 467 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value, 468 RHSExp->getSourceRange()); 469 } 470 // C99 6.5.2.1p1 471 if (!IndexExpr->getType()->isIntegerType()) 472 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript, 473 IndexExpr->getSourceRange()); 474 475 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice, 476 // the following check catches trying to index a pointer to a function (e.g. 477 // void (*)(int)) and pointers to incomplete types. Functions are not 478 // objects in C99. 479 if (!ResultType->isObjectType()) 480 return Diag(BaseExpr->getLocStart(), 481 diag::err_typecheck_subscript_not_object, 482 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange()); 483 484 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc); 485} 486 487QualType Sema:: 488CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, 489 IdentifierInfo &CompName, SourceLocation CompLoc) { 490 const ExtVectorType *vecType = baseType->getAsExtVectorType(); 491 492 // This flag determines whether or not the component is to be treated as a 493 // special name, or a regular GLSL-style component access. 494 bool SpecialComponent = false; 495 496 // The vector accessor can't exceed the number of elements. 497 const char *compStr = CompName.getName(); 498 if (strlen(compStr) > vecType->getNumElements()) { 499 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length, 500 baseType.getAsString(), SourceRange(CompLoc)); 501 return QualType(); 502 } 503 504 // Check that we've found one of the special components, or that the component 505 // names must come from the same set. 506 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 507 !strcmp(compStr, "e") || !strcmp(compStr, "o")) { 508 SpecialComponent = true; 509 } else if (vecType->getPointAccessorIdx(*compStr) != -1) { 510 do 511 compStr++; 512 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); 513 } else if (vecType->getColorAccessorIdx(*compStr) != -1) { 514 do 515 compStr++; 516 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1); 517 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) { 518 do 519 compStr++; 520 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1); 521 } 522 523 if (!SpecialComponent && *compStr) { 524 // We didn't get to the end of the string. This means the component names 525 // didn't come from the same set *or* we encountered an illegal name. 526 Diag(OpLoc, diag::err_ext_vector_component_name_illegal, 527 std::string(compStr,compStr+1), SourceRange(CompLoc)); 528 return QualType(); 529 } 530 // Each component accessor can't exceed the vector type. 531 compStr = CompName.getName(); 532 while (*compStr) { 533 if (vecType->isAccessorWithinNumElements(*compStr)) 534 compStr++; 535 else 536 break; 537 } 538 if (!SpecialComponent && *compStr) { 539 // We didn't get to the end of the string. This means a component accessor 540 // exceeds the number of elements in the vector. 541 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length, 542 baseType.getAsString(), SourceRange(CompLoc)); 543 return QualType(); 544 } 545 546 // If we have a special component name, verify that the current vector length 547 // is an even number, since all special component names return exactly half 548 // the elements. 549 if (SpecialComponent && (vecType->getNumElements() & 1U)) { 550 return QualType(); 551 } 552 553 // The component accessor looks fine - now we need to compute the actual type. 554 // The vector type is implied by the component accessor. For example, 555 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 556 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 557 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2 558 : strlen(CompName.getName()); 559 if (CompSize == 1) 560 return vecType->getElementType(); 561 562 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); 563 // Now look up the TypeDefDecl from the vector type. Without this, 564 // diagostics look bad. We want extended vector types to appear built-in. 565 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { 566 if (ExtVectorDecls[i]->getUnderlyingType() == VT) 567 return Context.getTypedefType(ExtVectorDecls[i]); 568 } 569 return VT; // should never get here (a typedef type should always be found). 570} 571 572Action::ExprResult Sema:: 573ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc, 574 tok::TokenKind OpKind, SourceLocation MemberLoc, 575 IdentifierInfo &Member) { 576 Expr *BaseExpr = static_cast<Expr *>(Base); 577 assert(BaseExpr && "no record expression"); 578 579 // Perform default conversions. 580 DefaultFunctionArrayConversion(BaseExpr); 581 582 QualType BaseType = BaseExpr->getType(); 583 assert(!BaseType.isNull() && "no type for member expression"); 584 585 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 586 // must have pointer type, and the accessed type is the pointee. 587 if (OpKind == tok::arrow) { 588 if (const PointerType *PT = BaseType->getAsPointerType()) 589 BaseType = PT->getPointeeType(); 590 else 591 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow, 592 BaseType.getAsString(), BaseExpr->getSourceRange()); 593 } 594 595 // Handle field access to simple records. This also handles access to fields 596 // of the ObjC 'id' struct. 597 if (const RecordType *RTy = BaseType->getAsRecordType()) { 598 RecordDecl *RDecl = RTy->getDecl(); 599 if (RTy->isIncompleteType()) 600 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(), 601 BaseExpr->getSourceRange()); 602 // The record definition is complete, now make sure the member is valid. 603 FieldDecl *MemberDecl = RDecl->getMember(&Member); 604 if (!MemberDecl) 605 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(), 606 BaseExpr->getSourceRange()); 607 608 // Figure out the type of the member; see C99 6.5.2.3p3 609 // FIXME: Handle address space modifiers 610 QualType MemberType = MemberDecl->getType(); 611 unsigned combinedQualifiers = 612 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers(); 613 MemberType = MemberType.getQualifiedType(combinedQualifiers); 614 615 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl, 616 MemberLoc, MemberType); 617 } 618 619 // Handle access to Objective-C instance variables, such as "Obj->ivar" and 620 // (*Obj).ivar. 621 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) { 622 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) 623 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr, 624 OpKind == tok::arrow); 625 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar, 626 IFTy->getDecl()->getName(), Member.getName(), 627 BaseExpr->getSourceRange()); 628 } 629 630 // Handle Objective-C property access, which is "Obj.property" where Obj is a 631 // pointer to a (potentially qualified) interface type. 632 const PointerType *PTy; 633 const ObjCInterfaceType *IFTy; 634 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) && 635 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) { 636 ObjCInterfaceDecl *IFace = IFTy->getDecl(); 637 638 // Before we look for explicit property declarations, we check for 639 // nullary methods (which allow '.' notation). 640 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 641 642 if (ObjCMethodDecl *MD = IFace->lookupInstanceMethod(Sel)) 643 return new ObjCPropertyRefExpr(MD, MD->getResultType(), 644 MemberLoc, BaseExpr); 645 646 // FIXME: Need to deal with setter methods that take 1 argument. E.g.: 647 // @interface NSBundle : NSObject {} 648 // - (NSString *)bundlePath; 649 // - (void)setBundlePath:(NSString *)x; 650 // @end 651 // void someMethod() { frameworkBundle.bundlePath = 0; } 652 // 653 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) 654 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr); 655 656 // Lastly, check protocols on qualified interfaces. 657 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(), 658 E = IFTy->qual_end(); I != E; ++I) 659 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) 660 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr); 661 } 662 663 // Handle 'field access' to vectors, such as 'V.xx'. 664 if (BaseType->isExtVectorType() && OpKind == tok::period) { 665 // Component access limited to variables (reject vec4.rg.g). 666 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) && 667 !isa<ExtVectorElementExpr>(BaseExpr)) 668 return Diag(MemberLoc, diag::err_ext_vector_component_access, 669 BaseExpr->getSourceRange()); 670 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 671 if (ret.isNull()) 672 return true; 673 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc); 674 } 675 676 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union, 677 BaseType.getAsString(), BaseExpr->getSourceRange()); 678} 679 680/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 681/// This provides the location of the left/right parens and a list of comma 682/// locations. 683Action::ExprResult Sema:: 684ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc, 685 ExprTy **args, unsigned NumArgs, 686 SourceLocation *CommaLocs, SourceLocation RParenLoc) { 687 Expr *Fn = static_cast<Expr *>(fn); 688 Expr **Args = reinterpret_cast<Expr**>(args); 689 assert(Fn && "no function call expression"); 690 FunctionDecl *FDecl = NULL; 691 692 // Promote the function operand. 693 UsualUnaryConversions(Fn); 694 695 // If we're directly calling a function, get the declaration for 696 // that function. 697 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn)) 698 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr())) 699 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()); 700 701 // Make the call expr early, before semantic checks. This guarantees cleanup 702 // of arguments and function on error. 703 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs, 704 Context.BoolTy, RParenLoc)); 705 706 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have 707 // type pointer to function". 708 const PointerType *PT = Fn->getType()->getAsPointerType(); 709 if (PT == 0) 710 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function, 711 SourceRange(Fn->getLocStart(), RParenLoc)); 712 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType(); 713 if (FuncT == 0) 714 return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function, 715 SourceRange(Fn->getLocStart(), RParenLoc)); 716 717 // We know the result type of the call, set it. 718 TheCall->setType(FuncT->getResultType()); 719 720 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) { 721 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 722 // assignment, to the types of the corresponding parameter, ... 723 unsigned NumArgsInProto = Proto->getNumArgs(); 724 unsigned NumArgsToCheck = NumArgs; 725 726 // If too few arguments are available (and we don't have default 727 // arguments for the remaining parameters), don't make the call. 728 if (NumArgs < NumArgsInProto) { 729 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) { 730 // Use default arguments for missing arguments 731 NumArgsToCheck = NumArgsInProto; 732 TheCall->setNumArgs(NumArgsInProto); 733 } else 734 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args, 735 Fn->getSourceRange()); 736 } 737 738 // If too many are passed and not variadic, error on the extras and drop 739 // them. 740 if (NumArgs > NumArgsInProto) { 741 if (!Proto->isVariadic()) { 742 Diag(Args[NumArgsInProto]->getLocStart(), 743 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(), 744 SourceRange(Args[NumArgsInProto]->getLocStart(), 745 Args[NumArgs-1]->getLocEnd())); 746 // This deletes the extra arguments. 747 TheCall->setNumArgs(NumArgsInProto); 748 } 749 NumArgsToCheck = NumArgsInProto; 750 } 751 752 // Continue to check argument types (even if we have too few/many args). 753 for (unsigned i = 0; i != NumArgsToCheck; i++) { 754 QualType ProtoArgType = Proto->getArgType(i); 755 756 Expr *Arg; 757 if (i < NumArgs) 758 Arg = Args[i]; 759 else 760 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i)); 761 QualType ArgType = Arg->getType(); 762 763 // Compute implicit casts from the operand to the formal argument type. 764 AssignConvertType ConvTy = 765 CheckSingleAssignmentConstraints(ProtoArgType, Arg); 766 TheCall->setArg(i, Arg); 767 768 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType, 769 ArgType, Arg, "passing")) 770 return true; 771 } 772 773 // If this is a variadic call, handle args passed through "...". 774 if (Proto->isVariadic()) { 775 // Promote the arguments (C99 6.5.2.2p7). 776 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 777 Expr *Arg = Args[i]; 778 DefaultArgumentPromotion(Arg); 779 TheCall->setArg(i, Arg); 780 } 781 } 782 } else { 783 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!"); 784 785 // Promote the arguments (C99 6.5.2.2p6). 786 for (unsigned i = 0; i != NumArgs; i++) { 787 Expr *Arg = Args[i]; 788 DefaultArgumentPromotion(Arg); 789 TheCall->setArg(i, Arg); 790 } 791 } 792 793 // Do special checking on direct calls to functions. 794 if (FDecl) 795 return CheckFunctionCall(FDecl, TheCall.take()); 796 797 return TheCall.take(); 798} 799 800Action::ExprResult Sema:: 801ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty, 802 SourceLocation RParenLoc, ExprTy *InitExpr) { 803 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 804 QualType literalType = QualType::getFromOpaquePtr(Ty); 805 // FIXME: put back this assert when initializers are worked out. 806 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 807 Expr *literalExpr = static_cast<Expr*>(InitExpr); 808 809 if (literalType->isArrayType()) { 810 if (literalType->getAsVariableArrayType()) 811 return Diag(LParenLoc, 812 diag::err_variable_object_no_init, 813 SourceRange(LParenLoc, 814 literalExpr->getSourceRange().getEnd())); 815 } else if (literalType->isIncompleteType()) { 816 return Diag(LParenLoc, 817 diag::err_typecheck_decl_incomplete_type, 818 literalType.getAsString(), 819 SourceRange(LParenLoc, 820 literalExpr->getSourceRange().getEnd())); 821 } 822 823 if (CheckInitializerTypes(literalExpr, literalType)) 824 return true; 825 826 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl(); 827 if (isFileScope) { // 6.5.2.5p3 828 if (CheckForConstantInitializer(literalExpr, literalType)) 829 return true; 830 } 831 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope); 832} 833 834Action::ExprResult Sema:: 835ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit, 836 SourceLocation RBraceLoc) { 837 Expr **InitList = reinterpret_cast<Expr**>(initlist); 838 839 // Semantic analysis for initializers is done by ActOnDeclarator() and 840 // CheckInitializer() - it requires knowledge of the object being intialized. 841 842 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc); 843 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 844 return E; 845} 846 847bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) { 848 assert(VectorTy->isVectorType() && "Not a vector type!"); 849 850 if (Ty->isVectorType() || Ty->isIntegerType()) { 851 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 852 return Diag(R.getBegin(), 853 Ty->isVectorType() ? 854 diag::err_invalid_conversion_between_vectors : 855 diag::err_invalid_conversion_between_vector_and_integer, 856 VectorTy.getAsString().c_str(), 857 Ty.getAsString().c_str(), R); 858 } else 859 return Diag(R.getBegin(), 860 diag::err_invalid_conversion_between_vector_and_scalar, 861 VectorTy.getAsString().c_str(), 862 Ty.getAsString().c_str(), R); 863 864 return false; 865} 866 867Action::ExprResult Sema:: 868ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty, 869 SourceLocation RParenLoc, ExprTy *Op) { 870 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr"); 871 872 Expr *castExpr = static_cast<Expr*>(Op); 873 QualType castType = QualType::getFromOpaquePtr(Ty); 874 875 UsualUnaryConversions(castExpr); 876 877 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 878 // type needs to be scalar. 879 if (!castType->isVoidType()) { // Cast to void allows any expr type. 880 if (!castType->isScalarType() && !castType->isVectorType()) { 881 // GCC struct/union extension. 882 if (castType == castExpr->getType() && 883 castType->isStructureType() || castType->isUnionType()) { 884 Diag(LParenLoc, diag::ext_typecheck_cast_nonscalar, 885 SourceRange(LParenLoc, RParenLoc)); 886 return new CastExpr(castType, castExpr, LParenLoc); 887 } else 888 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar, 889 castType.getAsString(), SourceRange(LParenLoc, RParenLoc)); 890 } 891 if (!castExpr->getType()->isScalarType() && 892 !castExpr->getType()->isVectorType()) 893 return Diag(castExpr->getLocStart(), 894 diag::err_typecheck_expect_scalar_operand, 895 castExpr->getType().getAsString(),castExpr->getSourceRange()); 896 897 if (castExpr->getType()->isVectorType()) { 898 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc), 899 castExpr->getType(), castType)) 900 return true; 901 } else if (castType->isVectorType()) { 902 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc), 903 castType, castExpr->getType())) 904 return true; 905 } 906 } 907 return new CastExpr(castType, castExpr, LParenLoc); 908} 909 910/// Note that lex is not null here, even if this is the gnu "x ?: y" extension. 911/// In that case, lex = cond. 912inline QualType Sema::CheckConditionalOperands( // C99 6.5.15 913 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) { 914 UsualUnaryConversions(cond); 915 UsualUnaryConversions(lex); 916 UsualUnaryConversions(rex); 917 QualType condT = cond->getType(); 918 QualType lexT = lex->getType(); 919 QualType rexT = rex->getType(); 920 921 // first, check the condition. 922 if (!condT->isScalarType()) { // C99 6.5.15p2 923 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar, 924 condT.getAsString()); 925 return QualType(); 926 } 927 928 // Now check the two expressions. 929 930 // If both operands have arithmetic type, do the usual arithmetic conversions 931 // to find a common type: C99 6.5.15p3,5. 932 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { 933 UsualArithmeticConversions(lex, rex); 934 return lex->getType(); 935 } 936 937 // If both operands are the same structure or union type, the result is that 938 // type. 939 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3 940 if (const RecordType *RHSRT = rexT->getAsRecordType()) 941 if (LHSRT->getDecl() == RHSRT->getDecl()) 942 // "If both the operands have structure or union type, the result has 943 // that type." This implies that CV qualifiers are dropped. 944 return lexT.getUnqualifiedType(); 945 } 946 947 // C99 6.5.15p5: "If both operands have void type, the result has void type." 948 // The following || allows only one side to be void (a GCC-ism). 949 if (lexT->isVoidType() || rexT->isVoidType()) { 950 if (!lexT->isVoidType()) 951 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void, 952 rex->getSourceRange()); 953 if (!rexT->isVoidType()) 954 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void, 955 lex->getSourceRange()); 956 ImpCastExprToType(lex, Context.VoidTy); 957 ImpCastExprToType(rex, Context.VoidTy); 958 return Context.VoidTy; 959 } 960 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 961 // the type of the other operand." 962 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) { 963 ImpCastExprToType(rex, lexT); // promote the null to a pointer. 964 return lexT; 965 } 966 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) { 967 ImpCastExprToType(lex, rexT); // promote the null to a pointer. 968 return rexT; 969 } 970 // Handle the case where both operands are pointers before we handle null 971 // pointer constants in case both operands are null pointer constants. 972 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6 973 if (const PointerType *RHSPT = rexT->getAsPointerType()) { 974 // get the "pointed to" types 975 QualType lhptee = LHSPT->getPointeeType(); 976 QualType rhptee = RHSPT->getPointeeType(); 977 978 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 979 if (lhptee->isVoidType() && 980 rhptee->isIncompleteOrObjectType()) { 981 // Figure out necessary qualifiers (C99 6.5.15p6) 982 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers()); 983 QualType destType = Context.getPointerType(destPointee); 984 ImpCastExprToType(lex, destType); // add qualifiers if necessary 985 ImpCastExprToType(rex, destType); // promote to void* 986 return destType; 987 } 988 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 989 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers()); 990 QualType destType = Context.getPointerType(destPointee); 991 ImpCastExprToType(lex, destType); // add qualifiers if necessary 992 ImpCastExprToType(rex, destType); // promote to void* 993 return destType; 994 } 995 996 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 997 rhptee.getUnqualifiedType())) { 998 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers, 999 lexT.getAsString(), rexT.getAsString(), 1000 lex->getSourceRange(), rex->getSourceRange()); 1001 // In this situation, we assume void* type. No especially good 1002 // reason, but this is what gcc does, and we do have to pick 1003 // to get a consistent AST. 1004 QualType voidPtrTy = Context.getPointerType(Context.VoidTy); 1005 ImpCastExprToType(lex, voidPtrTy); 1006 ImpCastExprToType(rex, voidPtrTy); 1007 return voidPtrTy; 1008 } 1009 // The pointer types are compatible. 1010 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 1011 // differently qualified versions of compatible types, the result type is 1012 // a pointer to an appropriately qualified version of the *composite* 1013 // type. 1014 // FIXME: Need to calculate the composite type. 1015 // FIXME: Need to add qualifiers 1016 QualType compositeType = lexT; 1017 ImpCastExprToType(lex, compositeType); 1018 ImpCastExprToType(rex, compositeType); 1019 return compositeType; 1020 } 1021 } 1022 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type 1023 // evaluates to "struct objc_object *" (and is handled above when comparing 1024 // id with statically typed objects). FIXME: Do we need an ImpCastExprToType? 1025 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) { 1026 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true)) 1027 return Context.getObjCIdType(); 1028 } 1029 // Otherwise, the operands are not compatible. 1030 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands, 1031 lexT.getAsString(), rexT.getAsString(), 1032 lex->getSourceRange(), rex->getSourceRange()); 1033 return QualType(); 1034} 1035 1036/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 1037/// in the case of a the GNU conditional expr extension. 1038Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 1039 SourceLocation ColonLoc, 1040 ExprTy *Cond, ExprTy *LHS, 1041 ExprTy *RHS) { 1042 Expr *CondExpr = (Expr *) Cond; 1043 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS; 1044 1045 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 1046 // was the condition. 1047 bool isLHSNull = LHSExpr == 0; 1048 if (isLHSNull) 1049 LHSExpr = CondExpr; 1050 1051 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 1052 RHSExpr, QuestionLoc); 1053 if (result.isNull()) 1054 return true; 1055 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr, 1056 RHSExpr, result); 1057} 1058 1059/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 1060/// do not have a prototype. Arguments that have type float are promoted to 1061/// double. All other argument types are converted by UsualUnaryConversions(). 1062void Sema::DefaultArgumentPromotion(Expr *&Expr) { 1063 QualType Ty = Expr->getType(); 1064 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 1065 1066 // If this is a 'float' (CVR qualified or typedef) promote to double. 1067 if (const BuiltinType *BT = Ty->getAsBuiltinType()) 1068 if (BT->getKind() == BuiltinType::Float) 1069 return ImpCastExprToType(Expr, Context.DoubleTy); 1070 1071 UsualUnaryConversions(Expr); 1072} 1073 1074/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 1075void Sema::DefaultFunctionArrayConversion(Expr *&E) { 1076 QualType Ty = E->getType(); 1077 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 1078 1079 if (const ReferenceType *ref = Ty->getAsReferenceType()) { 1080 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr] 1081 Ty = E->getType(); 1082 } 1083 if (Ty->isFunctionType()) 1084 ImpCastExprToType(E, Context.getPointerType(Ty)); 1085 else if (Ty->isArrayType()) 1086 ImpCastExprToType(E, Context.getArrayDecayedType(Ty)); 1087} 1088 1089/// UsualUnaryConversions - Performs various conversions that are common to most 1090/// operators (C99 6.3). The conversions of array and function types are 1091/// sometimes surpressed. For example, the array->pointer conversion doesn't 1092/// apply if the array is an argument to the sizeof or address (&) operators. 1093/// In these instances, this routine should *not* be called. 1094Expr *Sema::UsualUnaryConversions(Expr *&Expr) { 1095 QualType Ty = Expr->getType(); 1096 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 1097 1098 if (const ReferenceType *Ref = Ty->getAsReferenceType()) { 1099 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr] 1100 Ty = Expr->getType(); 1101 } 1102 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2 1103 ImpCastExprToType(Expr, Context.IntTy); 1104 else 1105 DefaultFunctionArrayConversion(Expr); 1106 1107 return Expr; 1108} 1109 1110/// UsualArithmeticConversions - Performs various conversions that are common to 1111/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1112/// routine returns the first non-arithmetic type found. The client is 1113/// responsible for emitting appropriate error diagnostics. 1114/// FIXME: verify the conversion rules for "complex int" are consistent with 1115/// GCC. 1116QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, 1117 bool isCompAssign) { 1118 if (!isCompAssign) { 1119 UsualUnaryConversions(lhsExpr); 1120 UsualUnaryConversions(rhsExpr); 1121 } 1122 // For conversion purposes, we ignore any qualifiers. 1123 // For example, "const float" and "float" are equivalent. 1124 QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType(); 1125 QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType(); 1126 1127 // If both types are identical, no conversion is needed. 1128 if (lhs == rhs) 1129 return lhs; 1130 1131 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1132 // The caller can deal with this (e.g. pointer + int). 1133 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 1134 return lhs; 1135 1136 // At this point, we have two different arithmetic types. 1137 1138 // Handle complex types first (C99 6.3.1.8p1). 1139 if (lhs->isComplexType() || rhs->isComplexType()) { 1140 // if we have an integer operand, the result is the complex type. 1141 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 1142 // convert the rhs to the lhs complex type. 1143 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 1144 return lhs; 1145 } 1146 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 1147 // convert the lhs to the rhs complex type. 1148 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); 1149 return rhs; 1150 } 1151 // This handles complex/complex, complex/float, or float/complex. 1152 // When both operands are complex, the shorter operand is converted to the 1153 // type of the longer, and that is the type of the result. This corresponds 1154 // to what is done when combining two real floating-point operands. 1155 // The fun begins when size promotion occur across type domains. 1156 // From H&S 6.3.4: When one operand is complex and the other is a real 1157 // floating-point type, the less precise type is converted, within it's 1158 // real or complex domain, to the precision of the other type. For example, 1159 // when combining a "long double" with a "double _Complex", the 1160 // "double _Complex" is promoted to "long double _Complex". 1161 int result = Context.getFloatingTypeOrder(lhs, rhs); 1162 1163 if (result > 0) { // The left side is bigger, convert rhs. 1164 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs); 1165 if (!isCompAssign) 1166 ImpCastExprToType(rhsExpr, rhs); 1167 } else if (result < 0) { // The right side is bigger, convert lhs. 1168 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs); 1169 if (!isCompAssign) 1170 ImpCastExprToType(lhsExpr, lhs); 1171 } 1172 // At this point, lhs and rhs have the same rank/size. Now, make sure the 1173 // domains match. This is a requirement for our implementation, C99 1174 // does not require this promotion. 1175 if (lhs != rhs) { // Domains don't match, we have complex/float mix. 1176 if (lhs->isRealFloatingType()) { // handle "double, _Complex double". 1177 if (!isCompAssign) 1178 ImpCastExprToType(lhsExpr, rhs); 1179 return rhs; 1180 } else { // handle "_Complex double, double". 1181 if (!isCompAssign) 1182 ImpCastExprToType(rhsExpr, lhs); 1183 return lhs; 1184 } 1185 } 1186 return lhs; // The domain/size match exactly. 1187 } 1188 // Now handle "real" floating types (i.e. float, double, long double). 1189 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) { 1190 // if we have an integer operand, the result is the real floating type. 1191 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 1192 // convert rhs to the lhs floating point type. 1193 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 1194 return lhs; 1195 } 1196 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 1197 // convert lhs to the rhs floating point type. 1198 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); 1199 return rhs; 1200 } 1201 // We have two real floating types, float/complex combos were handled above. 1202 // Convert the smaller operand to the bigger result. 1203 int result = Context.getFloatingTypeOrder(lhs, rhs); 1204 1205 if (result > 0) { // convert the rhs 1206 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 1207 return lhs; 1208 } 1209 if (result < 0) { // convert the lhs 1210 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs 1211 return rhs; 1212 } 1213 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison"); 1214 } 1215 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) { 1216 // Handle GCC complex int extension. 1217 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType(); 1218 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType(); 1219 1220 if (lhsComplexInt && rhsComplexInt) { 1221 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(), 1222 rhsComplexInt->getElementType()) >= 0) { 1223 // convert the rhs 1224 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 1225 return lhs; 1226 } 1227 if (!isCompAssign) 1228 ImpCastExprToType(lhsExpr, rhs); // convert the lhs 1229 return rhs; 1230 } else if (lhsComplexInt && rhs->isIntegerType()) { 1231 // convert the rhs to the lhs complex type. 1232 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 1233 return lhs; 1234 } else if (rhsComplexInt && lhs->isIntegerType()) { 1235 // convert the lhs to the rhs complex type. 1236 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); 1237 return rhs; 1238 } 1239 } 1240 // Finally, we have two differing integer types. 1241 // The rules for this case are in C99 6.3.1.8 1242 int compare = Context.getIntegerTypeOrder(lhs, rhs); 1243 bool lhsSigned = lhs->isSignedIntegerType(), 1244 rhsSigned = rhs->isSignedIntegerType(); 1245 QualType destType; 1246 if (lhsSigned == rhsSigned) { 1247 // Same signedness; use the higher-ranked type 1248 destType = compare >= 0 ? lhs : rhs; 1249 } else if (compare != (lhsSigned ? 1 : -1)) { 1250 // The unsigned type has greater than or equal rank to the 1251 // signed type, so use the unsigned type 1252 destType = lhsSigned ? rhs : lhs; 1253 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) { 1254 // The two types are different widths; if we are here, that 1255 // means the signed type is larger than the unsigned type, so 1256 // use the signed type. 1257 destType = lhsSigned ? lhs : rhs; 1258 } else { 1259 // The signed type is higher-ranked than the unsigned type, 1260 // but isn't actually any bigger (like unsigned int and long 1261 // on most 32-bit systems). Use the unsigned type corresponding 1262 // to the signed type. 1263 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs); 1264 } 1265 if (!isCompAssign) { 1266 ImpCastExprToType(lhsExpr, destType); 1267 ImpCastExprToType(rhsExpr, destType); 1268 } 1269 return destType; 1270} 1271 1272// CheckPointerTypesForAssignment - This is a very tricky routine (despite 1273// being closely modeled after the C99 spec:-). The odd characteristic of this 1274// routine is it effectively iqnores the qualifiers on the top level pointee. 1275// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 1276// FIXME: add a couple examples in this comment. 1277Sema::AssignConvertType 1278Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 1279 QualType lhptee, rhptee; 1280 1281 // get the "pointed to" type (ignoring qualifiers at the top level) 1282 lhptee = lhsType->getAsPointerType()->getPointeeType(); 1283 rhptee = rhsType->getAsPointerType()->getPointeeType(); 1284 1285 // make sure we operate on the canonical type 1286 lhptee = lhptee.getCanonicalType(); 1287 rhptee = rhptee.getCanonicalType(); 1288 1289 AssignConvertType ConvTy = Compatible; 1290 1291 // C99 6.5.16.1p1: This following citation is common to constraints 1292 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 1293 // qualifiers of the type *pointed to* by the right; 1294 // FIXME: Handle ASQualType 1295 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) != 1296 rhptee.getCVRQualifiers()) 1297 ConvTy = CompatiblePointerDiscardsQualifiers; 1298 1299 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 1300 // incomplete type and the other is a pointer to a qualified or unqualified 1301 // version of void... 1302 if (lhptee->isVoidType()) { 1303 if (rhptee->isIncompleteOrObjectType()) 1304 return ConvTy; 1305 1306 // As an extension, we allow cast to/from void* to function pointer. 1307 assert(rhptee->isFunctionType()); 1308 return FunctionVoidPointer; 1309 } 1310 1311 if (rhptee->isVoidType()) { 1312 if (lhptee->isIncompleteOrObjectType()) 1313 return ConvTy; 1314 1315 // As an extension, we allow cast to/from void* to function pointer. 1316 assert(lhptee->isFunctionType()); 1317 return FunctionVoidPointer; 1318 } 1319 1320 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 1321 // unqualified versions of compatible types, ... 1322 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 1323 rhptee.getUnqualifiedType())) 1324 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers 1325 return ConvTy; 1326} 1327 1328/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 1329/// has code to accommodate several GCC extensions when type checking 1330/// pointers. Here are some objectionable examples that GCC considers warnings: 1331/// 1332/// int a, *pint; 1333/// short *pshort; 1334/// struct foo *pfoo; 1335/// 1336/// pint = pshort; // warning: assignment from incompatible pointer type 1337/// a = pint; // warning: assignment makes integer from pointer without a cast 1338/// pint = a; // warning: assignment makes pointer from integer without a cast 1339/// pint = pfoo; // warning: assignment from incompatible pointer type 1340/// 1341/// As a result, the code for dealing with pointers is more complex than the 1342/// C99 spec dictates. 1343/// 1344Sema::AssignConvertType 1345Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 1346 // Get canonical types. We're not formatting these types, just comparing 1347 // them. 1348 lhsType = lhsType.getCanonicalType().getUnqualifiedType(); 1349 rhsType = rhsType.getCanonicalType().getUnqualifiedType(); 1350 1351 if (lhsType == rhsType) 1352 return Compatible; // Common case: fast path an exact match. 1353 1354 if (lhsType->isReferenceType() || rhsType->isReferenceType()) { 1355 if (Context.typesAreCompatible(lhsType, rhsType)) 1356 return Compatible; 1357 return Incompatible; 1358 } 1359 1360 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) { 1361 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false)) 1362 return Compatible; 1363 // Relax integer conversions like we do for pointers below. 1364 if (rhsType->isIntegerType()) 1365 return IntToPointer; 1366 if (lhsType->isIntegerType()) 1367 return PointerToInt; 1368 return Incompatible; 1369 } 1370 1371 if (lhsType->isVectorType() || rhsType->isVectorType()) { 1372 // For ExtVector, allow vector splats; float -> <n x float> 1373 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) 1374 if (LV->getElementType() == rhsType) 1375 return Compatible; 1376 1377 // If we are allowing lax vector conversions, and LHS and RHS are both 1378 // vectors, the total size only needs to be the same. This is a bitcast; 1379 // no bits are changed but the result type is different. 1380 if (getLangOptions().LaxVectorConversions && 1381 lhsType->isVectorType() && rhsType->isVectorType()) { 1382 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) 1383 return Compatible; 1384 } 1385 return Incompatible; 1386 } 1387 1388 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) 1389 return Compatible; 1390 1391 if (isa<PointerType>(lhsType)) { 1392 if (rhsType->isIntegerType()) 1393 return IntToPointer; 1394 1395 if (isa<PointerType>(rhsType)) 1396 return CheckPointerTypesForAssignment(lhsType, rhsType); 1397 return Incompatible; 1398 } 1399 1400 if (isa<PointerType>(rhsType)) { 1401 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 1402 if (lhsType == Context.BoolTy) 1403 return Compatible; 1404 1405 if (lhsType->isIntegerType()) 1406 return PointerToInt; 1407 1408 if (isa<PointerType>(lhsType)) 1409 return CheckPointerTypesForAssignment(lhsType, rhsType); 1410 return Incompatible; 1411 } 1412 1413 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 1414 if (Context.typesAreCompatible(lhsType, rhsType)) 1415 return Compatible; 1416 } 1417 return Incompatible; 1418} 1419 1420Sema::AssignConvertType 1421Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 1422 // C99 6.5.16.1p1: the left operand is a pointer and the right is 1423 // a null pointer constant. 1424 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType()) 1425 && rExpr->isNullPointerConstant(Context)) { 1426 ImpCastExprToType(rExpr, lhsType); 1427 return Compatible; 1428 } 1429 // This check seems unnatural, however it is necessary to ensure the proper 1430 // conversion of functions/arrays. If the conversion were done for all 1431 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary 1432 // expressions that surpress this implicit conversion (&, sizeof). 1433 // 1434 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references 1435 // are better understood. 1436 if (!lhsType->isReferenceType()) 1437 DefaultFunctionArrayConversion(rExpr); 1438 1439 Sema::AssignConvertType result = 1440 CheckAssignmentConstraints(lhsType, rExpr->getType()); 1441 1442 // C99 6.5.16.1p2: The value of the right operand is converted to the 1443 // type of the assignment expression. 1444 if (rExpr->getType() != lhsType) 1445 ImpCastExprToType(rExpr, lhsType); 1446 return result; 1447} 1448 1449Sema::AssignConvertType 1450Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) { 1451 return CheckAssignmentConstraints(lhsType, rhsType); 1452} 1453 1454QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) { 1455 Diag(loc, diag::err_typecheck_invalid_operands, 1456 lex->getType().getAsString(), rex->getType().getAsString(), 1457 lex->getSourceRange(), rex->getSourceRange()); 1458 return QualType(); 1459} 1460 1461inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex, 1462 Expr *&rex) { 1463 // For conversion purposes, we ignore any qualifiers. 1464 // For example, "const float" and "float" are equivalent. 1465 QualType lhsType = lex->getType().getCanonicalType().getUnqualifiedType(); 1466 QualType rhsType = rex->getType().getCanonicalType().getUnqualifiedType(); 1467 1468 // If the vector types are identical, return. 1469 if (lhsType == rhsType) 1470 return lhsType; 1471 1472 // Handle the case of a vector & extvector type of the same size and element 1473 // type. It would be nice if we only had one vector type someday. 1474 if (getLangOptions().LaxVectorConversions) 1475 if (const VectorType *LV = lhsType->getAsVectorType()) 1476 if (const VectorType *RV = rhsType->getAsVectorType()) 1477 if (LV->getElementType() == RV->getElementType() && 1478 LV->getNumElements() == RV->getNumElements()) 1479 return lhsType->isExtVectorType() ? lhsType : rhsType; 1480 1481 // If the lhs is an extended vector and the rhs is a scalar of the same type 1482 // or a literal, promote the rhs to the vector type. 1483 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) { 1484 QualType eltType = V->getElementType(); 1485 1486 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) || 1487 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) || 1488 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) { 1489 ImpCastExprToType(rex, lhsType); 1490 return lhsType; 1491 } 1492 } 1493 1494 // If the rhs is an extended vector and the lhs is a scalar of the same type, 1495 // promote the lhs to the vector type. 1496 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) { 1497 QualType eltType = V->getElementType(); 1498 1499 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) || 1500 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) || 1501 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) { 1502 ImpCastExprToType(lex, rhsType); 1503 return rhsType; 1504 } 1505 } 1506 1507 // You cannot convert between vector values of different size. 1508 Diag(loc, diag::err_typecheck_vector_not_convertable, 1509 lex->getType().getAsString(), rex->getType().getAsString(), 1510 lex->getSourceRange(), rex->getSourceRange()); 1511 return QualType(); 1512} 1513 1514inline QualType Sema::CheckMultiplyDivideOperands( 1515 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1516{ 1517 QualType lhsType = lex->getType(), rhsType = rex->getType(); 1518 1519 if (lhsType->isVectorType() || rhsType->isVectorType()) 1520 return CheckVectorOperands(loc, lex, rex); 1521 1522 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1523 1524 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1525 return compType; 1526 return InvalidOperands(loc, lex, rex); 1527} 1528 1529inline QualType Sema::CheckRemainderOperands( 1530 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1531{ 1532 QualType lhsType = lex->getType(), rhsType = rex->getType(); 1533 1534 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1535 1536 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 1537 return compType; 1538 return InvalidOperands(loc, lex, rex); 1539} 1540 1541inline QualType Sema::CheckAdditionOperands( // C99 6.5.6 1542 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1543{ 1544 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1545 return CheckVectorOperands(loc, lex, rex); 1546 1547 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1548 1549 // handle the common case first (both operands are arithmetic). 1550 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1551 return compType; 1552 1553 // Put any potential pointer into PExp 1554 Expr* PExp = lex, *IExp = rex; 1555 if (IExp->getType()->isPointerType()) 1556 std::swap(PExp, IExp); 1557 1558 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) { 1559 if (IExp->getType()->isIntegerType()) { 1560 // Check for arithmetic on pointers to incomplete types 1561 if (!PTy->getPointeeType()->isObjectType()) { 1562 if (PTy->getPointeeType()->isVoidType()) { 1563 Diag(loc, diag::ext_gnu_void_ptr, 1564 lex->getSourceRange(), rex->getSourceRange()); 1565 } else { 1566 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type, 1567 lex->getType().getAsString(), lex->getSourceRange()); 1568 return QualType(); 1569 } 1570 } 1571 return PExp->getType(); 1572 } 1573 } 1574 1575 return InvalidOperands(loc, lex, rex); 1576} 1577 1578// C99 6.5.6 1579QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 1580 SourceLocation loc, bool isCompAssign) { 1581 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1582 return CheckVectorOperands(loc, lex, rex); 1583 1584 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1585 1586 // Enforce type constraints: C99 6.5.6p3. 1587 1588 // Handle the common case first (both operands are arithmetic). 1589 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1590 return compType; 1591 1592 // Either ptr - int or ptr - ptr. 1593 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) { 1594 QualType lpointee = LHSPTy->getPointeeType(); 1595 1596 // The LHS must be an object type, not incomplete, function, etc. 1597 if (!lpointee->isObjectType()) { 1598 // Handle the GNU void* extension. 1599 if (lpointee->isVoidType()) { 1600 Diag(loc, diag::ext_gnu_void_ptr, 1601 lex->getSourceRange(), rex->getSourceRange()); 1602 } else { 1603 Diag(loc, diag::err_typecheck_sub_ptr_object, 1604 lex->getType().getAsString(), lex->getSourceRange()); 1605 return QualType(); 1606 } 1607 } 1608 1609 // The result type of a pointer-int computation is the pointer type. 1610 if (rex->getType()->isIntegerType()) 1611 return lex->getType(); 1612 1613 // Handle pointer-pointer subtractions. 1614 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) { 1615 QualType rpointee = RHSPTy->getPointeeType(); 1616 1617 // RHS must be an object type, unless void (GNU). 1618 if (!rpointee->isObjectType()) { 1619 // Handle the GNU void* extension. 1620 if (rpointee->isVoidType()) { 1621 if (!lpointee->isVoidType()) 1622 Diag(loc, diag::ext_gnu_void_ptr, 1623 lex->getSourceRange(), rex->getSourceRange()); 1624 } else { 1625 Diag(loc, diag::err_typecheck_sub_ptr_object, 1626 rex->getType().getAsString(), rex->getSourceRange()); 1627 return QualType(); 1628 } 1629 } 1630 1631 // Pointee types must be compatible. 1632 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(), 1633 rpointee.getUnqualifiedType())) { 1634 Diag(loc, diag::err_typecheck_sub_ptr_compatible, 1635 lex->getType().getAsString(), rex->getType().getAsString(), 1636 lex->getSourceRange(), rex->getSourceRange()); 1637 return QualType(); 1638 } 1639 1640 return Context.getPointerDiffType(); 1641 } 1642 } 1643 1644 return InvalidOperands(loc, lex, rex); 1645} 1646 1647// C99 6.5.7 1648QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc, 1649 bool isCompAssign) { 1650 // C99 6.5.7p2: Each of the operands shall have integer type. 1651 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 1652 return InvalidOperands(loc, lex, rex); 1653 1654 // Shifts don't perform usual arithmetic conversions, they just do integer 1655 // promotions on each operand. C99 6.5.7p3 1656 if (!isCompAssign) 1657 UsualUnaryConversions(lex); 1658 UsualUnaryConversions(rex); 1659 1660 // "The type of the result is that of the promoted left operand." 1661 return lex->getType(); 1662} 1663 1664// C99 6.5.8 1665QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc, 1666 bool isRelational) { 1667 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1668 return CheckVectorCompareOperands(lex, rex, loc, isRelational); 1669 1670 // C99 6.5.8p3 / C99 6.5.9p4 1671 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1672 UsualArithmeticConversions(lex, rex); 1673 else { 1674 UsualUnaryConversions(lex); 1675 UsualUnaryConversions(rex); 1676 } 1677 QualType lType = lex->getType(); 1678 QualType rType = rex->getType(); 1679 1680 // For non-floating point types, check for self-comparisons of the form 1681 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 1682 // often indicate logic errors in the program. 1683 if (!lType->isFloatingType()) { 1684 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 1685 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 1686 if (DRL->getDecl() == DRR->getDecl()) 1687 Diag(loc, diag::warn_selfcomparison); 1688 } 1689 1690 if (isRelational) { 1691 if (lType->isRealType() && rType->isRealType()) 1692 return Context.IntTy; 1693 } else { 1694 // Check for comparisons of floating point operands using != and ==. 1695 if (lType->isFloatingType()) { 1696 assert (rType->isFloatingType()); 1697 CheckFloatComparison(loc,lex,rex); 1698 } 1699 1700 if (lType->isArithmeticType() && rType->isArithmeticType()) 1701 return Context.IntTy; 1702 } 1703 1704 bool LHSIsNull = lex->isNullPointerConstant(Context); 1705 bool RHSIsNull = rex->isNullPointerConstant(Context); 1706 1707 // All of the following pointer related warnings are GCC extensions, except 1708 // when handling null pointer constants. One day, we can consider making them 1709 // errors (when -pedantic-errors is enabled). 1710 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 1711 QualType LCanPointeeTy = 1712 lType->getAsPointerType()->getPointeeType().getCanonicalType(); 1713 QualType RCanPointeeTy = 1714 rType->getAsPointerType()->getPointeeType().getCanonicalType(); 1715 1716 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2 1717 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() && 1718 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 1719 RCanPointeeTy.getUnqualifiedType())) { 1720 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers, 1721 lType.getAsString(), rType.getAsString(), 1722 lex->getSourceRange(), rex->getSourceRange()); 1723 } 1724 ImpCastExprToType(rex, lType); // promote the pointer to pointer 1725 return Context.IntTy; 1726 } 1727 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) { 1728 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) { 1729 ImpCastExprToType(rex, lType); 1730 return Context.IntTy; 1731 } 1732 } 1733 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) && 1734 rType->isIntegerType()) { 1735 if (!RHSIsNull) 1736 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer, 1737 lType.getAsString(), rType.getAsString(), 1738 lex->getSourceRange(), rex->getSourceRange()); 1739 ImpCastExprToType(rex, lType); // promote the integer to pointer 1740 return Context.IntTy; 1741 } 1742 if (lType->isIntegerType() && 1743 (rType->isPointerType() || rType->isObjCQualifiedIdType())) { 1744 if (!LHSIsNull) 1745 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer, 1746 lType.getAsString(), rType.getAsString(), 1747 lex->getSourceRange(), rex->getSourceRange()); 1748 ImpCastExprToType(lex, rType); // promote the integer to pointer 1749 return Context.IntTy; 1750 } 1751 return InvalidOperands(loc, lex, rex); 1752} 1753 1754/// CheckVectorCompareOperands - vector comparisons are a clang extension that 1755/// operates on extended vector types. Instead of producing an IntTy result, 1756/// like a scalar comparison, a vector comparison produces a vector of integer 1757/// types. 1758QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 1759 SourceLocation loc, 1760 bool isRelational) { 1761 // Check to make sure we're operating on vectors of the same type and width, 1762 // Allowing one side to be a scalar of element type. 1763 QualType vType = CheckVectorOperands(loc, lex, rex); 1764 if (vType.isNull()) 1765 return vType; 1766 1767 QualType lType = lex->getType(); 1768 QualType rType = rex->getType(); 1769 1770 // For non-floating point types, check for self-comparisons of the form 1771 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 1772 // often indicate logic errors in the program. 1773 if (!lType->isFloatingType()) { 1774 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 1775 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 1776 if (DRL->getDecl() == DRR->getDecl()) 1777 Diag(loc, diag::warn_selfcomparison); 1778 } 1779 1780 // Check for comparisons of floating point operands using != and ==. 1781 if (!isRelational && lType->isFloatingType()) { 1782 assert (rType->isFloatingType()); 1783 CheckFloatComparison(loc,lex,rex); 1784 } 1785 1786 // Return the type for the comparison, which is the same as vector type for 1787 // integer vectors, or an integer type of identical size and number of 1788 // elements for floating point vectors. 1789 if (lType->isIntegerType()) 1790 return lType; 1791 1792 const VectorType *VTy = lType->getAsVectorType(); 1793 1794 // FIXME: need to deal with non-32b int / non-64b long long 1795 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 1796 if (TypeSize == 32) { 1797 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 1798 } 1799 assert(TypeSize == 64 && "Unhandled vector element size in vector compare"); 1800 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 1801} 1802 1803inline QualType Sema::CheckBitwiseOperands( 1804 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1805{ 1806 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1807 return CheckVectorOperands(loc, lex, rex); 1808 1809 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1810 1811 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 1812 return compType; 1813 return InvalidOperands(loc, lex, rex); 1814} 1815 1816inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 1817 Expr *&lex, Expr *&rex, SourceLocation loc) 1818{ 1819 UsualUnaryConversions(lex); 1820 UsualUnaryConversions(rex); 1821 1822 if (lex->getType()->isScalarType() && rex->getType()->isScalarType()) 1823 return Context.IntTy; 1824 return InvalidOperands(loc, lex, rex); 1825} 1826 1827inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1 1828 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType) 1829{ 1830 QualType lhsType = lex->getType(); 1831 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType; 1832 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(); 1833 1834 switch (mlval) { // C99 6.5.16p2 1835 case Expr::MLV_Valid: 1836 break; 1837 case Expr::MLV_ConstQualified: 1838 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange()); 1839 return QualType(); 1840 case Expr::MLV_ArrayType: 1841 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue, 1842 lhsType.getAsString(), lex->getSourceRange()); 1843 return QualType(); 1844 case Expr::MLV_NotObjectType: 1845 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue, 1846 lhsType.getAsString(), lex->getSourceRange()); 1847 return QualType(); 1848 case Expr::MLV_InvalidExpression: 1849 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue, 1850 lex->getSourceRange()); 1851 return QualType(); 1852 case Expr::MLV_IncompleteType: 1853 case Expr::MLV_IncompleteVoidType: 1854 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue, 1855 lhsType.getAsString(), lex->getSourceRange()); 1856 return QualType(); 1857 case Expr::MLV_DuplicateVectorComponents: 1858 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue, 1859 lex->getSourceRange()); 1860 return QualType(); 1861 } 1862 1863 AssignConvertType ConvTy; 1864 if (compoundType.isNull()) 1865 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex); 1866 else 1867 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType); 1868 1869 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType, 1870 rex, "assigning")) 1871 return QualType(); 1872 1873 // C99 6.5.16p3: The type of an assignment expression is the type of the 1874 // left operand unless the left operand has qualified type, in which case 1875 // it is the unqualified version of the type of the left operand. 1876 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 1877 // is converted to the type of the assignment expression (above). 1878 // C++ 5.17p1: the type of the assignment expression is that of its left 1879 // oprdu. 1880 return lhsType.getUnqualifiedType(); 1881} 1882 1883inline QualType Sema::CheckCommaOperands( // C99 6.5.17 1884 Expr *&lex, Expr *&rex, SourceLocation loc) { 1885 UsualUnaryConversions(rex); 1886 return rex->getType(); 1887} 1888 1889/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 1890/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 1891QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) { 1892 QualType resType = op->getType(); 1893 assert(!resType.isNull() && "no type for increment/decrement expression"); 1894 1895 // C99 6.5.2.4p1: We allow complex as a GCC extension. 1896 if (const PointerType *pt = resType->getAsPointerType()) { 1897 if (pt->getPointeeType()->isVoidType()) { 1898 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange()); 1899 } else if (!pt->getPointeeType()->isObjectType()) { 1900 // C99 6.5.2.4p2, 6.5.6p2 1901 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type, 1902 resType.getAsString(), op->getSourceRange()); 1903 return QualType(); 1904 } 1905 } else if (!resType->isRealType()) { 1906 if (resType->isComplexType()) 1907 // C99 does not support ++/-- on complex types. 1908 Diag(OpLoc, diag::ext_integer_increment_complex, 1909 resType.getAsString(), op->getSourceRange()); 1910 else { 1911 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement, 1912 resType.getAsString(), op->getSourceRange()); 1913 return QualType(); 1914 } 1915 } 1916 // At this point, we know we have a real, complex or pointer type. 1917 // Now make sure the operand is a modifiable lvalue. 1918 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(); 1919 if (mlval != Expr::MLV_Valid) { 1920 // FIXME: emit a more precise diagnostic... 1921 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr, 1922 op->getSourceRange()); 1923 return QualType(); 1924 } 1925 return resType; 1926} 1927 1928/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 1929/// This routine allows us to typecheck complex/recursive expressions 1930/// where the declaration is needed for type checking. Here are some 1931/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2]. 1932static ValueDecl *getPrimaryDecl(Expr *E) { 1933 switch (E->getStmtClass()) { 1934 case Stmt::DeclRefExprClass: 1935 return cast<DeclRefExpr>(E)->getDecl(); 1936 case Stmt::MemberExprClass: 1937 // Fields cannot be declared with a 'register' storage class. 1938 // &X->f is always ok, even if X is declared register. 1939 if (cast<MemberExpr>(E)->isArrow()) 1940 return 0; 1941 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 1942 case Stmt::ArraySubscriptExprClass: { 1943 // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer. 1944 1945 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase()); 1946 if (!VD || VD->getType()->isPointerType()) 1947 return 0; 1948 else 1949 return VD; 1950 } 1951 case Stmt::UnaryOperatorClass: 1952 return getPrimaryDecl(cast<UnaryOperator>(E)->getSubExpr()); 1953 case Stmt::ParenExprClass: 1954 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 1955 case Stmt::ImplicitCastExprClass: 1956 // &X[4] when X is an array, has an implicit cast from array to pointer. 1957 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 1958 default: 1959 return 0; 1960 } 1961} 1962 1963/// CheckAddressOfOperand - The operand of & must be either a function 1964/// designator or an lvalue designating an object. If it is an lvalue, the 1965/// object cannot be declared with storage class register or be a bit field. 1966/// Note: The usual conversions are *not* applied to the operand of the & 1967/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 1968QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { 1969 if (getLangOptions().C99) { 1970 // Implement C99-only parts of addressof rules. 1971 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 1972 if (uOp->getOpcode() == UnaryOperator::Deref) 1973 // Per C99 6.5.3.2, the address of a deref always returns a valid result 1974 // (assuming the deref expression is valid). 1975 return uOp->getSubExpr()->getType(); 1976 } 1977 // Technically, there should be a check for array subscript 1978 // expressions here, but the result of one is always an lvalue anyway. 1979 } 1980 ValueDecl *dcl = getPrimaryDecl(op); 1981 Expr::isLvalueResult lval = op->isLvalue(); 1982 1983 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1 1984 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators 1985 // FIXME: emit more specific diag... 1986 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof, 1987 op->getSourceRange()); 1988 return QualType(); 1989 } 1990 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1 1991 if (MemExpr->getMemberDecl()->isBitField()) { 1992 Diag(OpLoc, diag::err_typecheck_address_of, 1993 std::string("bit-field"), op->getSourceRange()); 1994 return QualType(); 1995 } 1996 // Check for Apple extension for accessing vector components. 1997 } else if (isa<ArraySubscriptExpr>(op) && 1998 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) { 1999 Diag(OpLoc, diag::err_typecheck_address_of, 2000 std::string("vector"), op->getSourceRange()); 2001 return QualType(); 2002 } else if (dcl) { // C99 6.5.3.2p1 2003 // We have an lvalue with a decl. Make sure the decl is not declared 2004 // with the register storage-class specifier. 2005 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 2006 if (vd->getStorageClass() == VarDecl::Register) { 2007 Diag(OpLoc, diag::err_typecheck_address_of, 2008 std::string("register variable"), op->getSourceRange()); 2009 return QualType(); 2010 } 2011 } else 2012 assert(0 && "Unknown/unexpected decl type"); 2013 } 2014 // If the operand has type "type", the result has type "pointer to type". 2015 return Context.getPointerType(op->getType()); 2016} 2017 2018QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) { 2019 UsualUnaryConversions(op); 2020 QualType qType = op->getType(); 2021 2022 if (const PointerType *PT = qType->getAsPointerType()) { 2023 // Note that per both C89 and C99, this is always legal, even 2024 // if ptype is an incomplete type or void. 2025 // It would be possible to warn about dereferencing a 2026 // void pointer, but it's completely well-defined, 2027 // and such a warning is unlikely to catch any mistakes. 2028 return PT->getPointeeType(); 2029 } 2030 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer, 2031 qType.getAsString(), op->getSourceRange()); 2032 return QualType(); 2033} 2034 2035static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( 2036 tok::TokenKind Kind) { 2037 BinaryOperator::Opcode Opc; 2038 switch (Kind) { 2039 default: assert(0 && "Unknown binop!"); 2040 case tok::star: Opc = BinaryOperator::Mul; break; 2041 case tok::slash: Opc = BinaryOperator::Div; break; 2042 case tok::percent: Opc = BinaryOperator::Rem; break; 2043 case tok::plus: Opc = BinaryOperator::Add; break; 2044 case tok::minus: Opc = BinaryOperator::Sub; break; 2045 case tok::lessless: Opc = BinaryOperator::Shl; break; 2046 case tok::greatergreater: Opc = BinaryOperator::Shr; break; 2047 case tok::lessequal: Opc = BinaryOperator::LE; break; 2048 case tok::less: Opc = BinaryOperator::LT; break; 2049 case tok::greaterequal: Opc = BinaryOperator::GE; break; 2050 case tok::greater: Opc = BinaryOperator::GT; break; 2051 case tok::exclaimequal: Opc = BinaryOperator::NE; break; 2052 case tok::equalequal: Opc = BinaryOperator::EQ; break; 2053 case tok::amp: Opc = BinaryOperator::And; break; 2054 case tok::caret: Opc = BinaryOperator::Xor; break; 2055 case tok::pipe: Opc = BinaryOperator::Or; break; 2056 case tok::ampamp: Opc = BinaryOperator::LAnd; break; 2057 case tok::pipepipe: Opc = BinaryOperator::LOr; break; 2058 case tok::equal: Opc = BinaryOperator::Assign; break; 2059 case tok::starequal: Opc = BinaryOperator::MulAssign; break; 2060 case tok::slashequal: Opc = BinaryOperator::DivAssign; break; 2061 case tok::percentequal: Opc = BinaryOperator::RemAssign; break; 2062 case tok::plusequal: Opc = BinaryOperator::AddAssign; break; 2063 case tok::minusequal: Opc = BinaryOperator::SubAssign; break; 2064 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; 2065 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; 2066 case tok::ampequal: Opc = BinaryOperator::AndAssign; break; 2067 case tok::caretequal: Opc = BinaryOperator::XorAssign; break; 2068 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; 2069 case tok::comma: Opc = BinaryOperator::Comma; break; 2070 } 2071 return Opc; 2072} 2073 2074static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( 2075 tok::TokenKind Kind) { 2076 UnaryOperator::Opcode Opc; 2077 switch (Kind) { 2078 default: assert(0 && "Unknown unary op!"); 2079 case tok::plusplus: Opc = UnaryOperator::PreInc; break; 2080 case tok::minusminus: Opc = UnaryOperator::PreDec; break; 2081 case tok::amp: Opc = UnaryOperator::AddrOf; break; 2082 case tok::star: Opc = UnaryOperator::Deref; break; 2083 case tok::plus: Opc = UnaryOperator::Plus; break; 2084 case tok::minus: Opc = UnaryOperator::Minus; break; 2085 case tok::tilde: Opc = UnaryOperator::Not; break; 2086 case tok::exclaim: Opc = UnaryOperator::LNot; break; 2087 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break; 2088 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break; 2089 case tok::kw___real: Opc = UnaryOperator::Real; break; 2090 case tok::kw___imag: Opc = UnaryOperator::Imag; break; 2091 case tok::kw___extension__: Opc = UnaryOperator::Extension; break; 2092 } 2093 return Opc; 2094} 2095 2096// Binary Operators. 'Tok' is the token for the operator. 2097Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind, 2098 ExprTy *LHS, ExprTy *RHS) { 2099 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); 2100 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS; 2101 2102 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 2103 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 2104 2105 QualType ResultTy; // Result type of the binary operator. 2106 QualType CompTy; // Computation type for compound assignments (e.g. '+=') 2107 2108 switch (Opc) { 2109 default: 2110 assert(0 && "Unknown binary expr!"); 2111 case BinaryOperator::Assign: 2112 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType()); 2113 break; 2114 case BinaryOperator::Mul: 2115 case BinaryOperator::Div: 2116 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc); 2117 break; 2118 case BinaryOperator::Rem: 2119 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc); 2120 break; 2121 case BinaryOperator::Add: 2122 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc); 2123 break; 2124 case BinaryOperator::Sub: 2125 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc); 2126 break; 2127 case BinaryOperator::Shl: 2128 case BinaryOperator::Shr: 2129 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc); 2130 break; 2131 case BinaryOperator::LE: 2132 case BinaryOperator::LT: 2133 case BinaryOperator::GE: 2134 case BinaryOperator::GT: 2135 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true); 2136 break; 2137 case BinaryOperator::EQ: 2138 case BinaryOperator::NE: 2139 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false); 2140 break; 2141 case BinaryOperator::And: 2142 case BinaryOperator::Xor: 2143 case BinaryOperator::Or: 2144 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc); 2145 break; 2146 case BinaryOperator::LAnd: 2147 case BinaryOperator::LOr: 2148 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc); 2149 break; 2150 case BinaryOperator::MulAssign: 2151 case BinaryOperator::DivAssign: 2152 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true); 2153 if (!CompTy.isNull()) 2154 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2155 break; 2156 case BinaryOperator::RemAssign: 2157 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true); 2158 if (!CompTy.isNull()) 2159 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2160 break; 2161 case BinaryOperator::AddAssign: 2162 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true); 2163 if (!CompTy.isNull()) 2164 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2165 break; 2166 case BinaryOperator::SubAssign: 2167 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true); 2168 if (!CompTy.isNull()) 2169 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2170 break; 2171 case BinaryOperator::ShlAssign: 2172 case BinaryOperator::ShrAssign: 2173 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true); 2174 if (!CompTy.isNull()) 2175 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2176 break; 2177 case BinaryOperator::AndAssign: 2178 case BinaryOperator::XorAssign: 2179 case BinaryOperator::OrAssign: 2180 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true); 2181 if (!CompTy.isNull()) 2182 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2183 break; 2184 case BinaryOperator::Comma: 2185 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc); 2186 break; 2187 } 2188 if (ResultTy.isNull()) 2189 return true; 2190 if (CompTy.isNull()) 2191 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc); 2192 else 2193 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc); 2194} 2195 2196// Unary Operators. 'Tok' is the token for the operator. 2197Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op, 2198 ExprTy *input) { 2199 Expr *Input = (Expr*)input; 2200 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op); 2201 QualType resultType; 2202 switch (Opc) { 2203 default: 2204 assert(0 && "Unimplemented unary expr!"); 2205 case UnaryOperator::PreInc: 2206 case UnaryOperator::PreDec: 2207 resultType = CheckIncrementDecrementOperand(Input, OpLoc); 2208 break; 2209 case UnaryOperator::AddrOf: 2210 resultType = CheckAddressOfOperand(Input, OpLoc); 2211 break; 2212 case UnaryOperator::Deref: 2213 DefaultFunctionArrayConversion(Input); 2214 resultType = CheckIndirectionOperand(Input, OpLoc); 2215 break; 2216 case UnaryOperator::Plus: 2217 case UnaryOperator::Minus: 2218 UsualUnaryConversions(Input); 2219 resultType = Input->getType(); 2220 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1 2221 return Diag(OpLoc, diag::err_typecheck_unary_expr, 2222 resultType.getAsString()); 2223 break; 2224 case UnaryOperator::Not: // bitwise complement 2225 UsualUnaryConversions(Input); 2226 resultType = Input->getType(); 2227 // C99 6.5.3.3p1. We allow complex as a GCC extension. 2228 if (!resultType->isIntegerType()) { 2229 if (resultType->isComplexType()) 2230 // C99 does not support '~' for complex conjugation. 2231 Diag(OpLoc, diag::ext_integer_complement_complex, 2232 resultType.getAsString()); 2233 else 2234 return Diag(OpLoc, diag::err_typecheck_unary_expr, 2235 resultType.getAsString()); 2236 } 2237 break; 2238 case UnaryOperator::LNot: // logical negation 2239 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 2240 DefaultFunctionArrayConversion(Input); 2241 resultType = Input->getType(); 2242 if (!resultType->isScalarType()) // C99 6.5.3.3p1 2243 return Diag(OpLoc, diag::err_typecheck_unary_expr, 2244 resultType.getAsString()); 2245 // LNot always has type int. C99 6.5.3.3p5. 2246 resultType = Context.IntTy; 2247 break; 2248 case UnaryOperator::SizeOf: 2249 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true); 2250 break; 2251 case UnaryOperator::AlignOf: 2252 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false); 2253 break; 2254 case UnaryOperator::Real: 2255 case UnaryOperator::Imag: 2256 resultType = CheckRealImagOperand(Input, OpLoc); 2257 break; 2258 case UnaryOperator::Extension: 2259 resultType = Input->getType(); 2260 break; 2261 } 2262 if (resultType.isNull()) 2263 return true; 2264 return new UnaryOperator(Input, Opc, resultType, OpLoc); 2265} 2266 2267/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 2268Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 2269 SourceLocation LabLoc, 2270 IdentifierInfo *LabelII) { 2271 // Look up the record for this label identifier. 2272 LabelStmt *&LabelDecl = LabelMap[LabelII]; 2273 2274 // If we haven't seen this label yet, create a forward reference. 2275 if (LabelDecl == 0) 2276 LabelDecl = new LabelStmt(LabLoc, LabelII, 0); 2277 2278 // Create the AST node. The address of a label always has type 'void*'. 2279 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 2280 Context.getPointerType(Context.VoidTy)); 2281} 2282 2283Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt, 2284 SourceLocation RPLoc) { // "({..})" 2285 Stmt *SubStmt = static_cast<Stmt*>(substmt); 2286 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 2287 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 2288 2289 // FIXME: there are a variety of strange constraints to enforce here, for 2290 // example, it is not possible to goto into a stmt expression apparently. 2291 // More semantic analysis is needed. 2292 2293 // FIXME: the last statement in the compount stmt has its value used. We 2294 // should not warn about it being unused. 2295 2296 // If there are sub stmts in the compound stmt, take the type of the last one 2297 // as the type of the stmtexpr. 2298 QualType Ty = Context.VoidTy; 2299 2300 if (!Compound->body_empty()) 2301 if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back())) 2302 Ty = LastExpr->getType(); 2303 2304 return new StmtExpr(Compound, Ty, LPLoc, RPLoc); 2305} 2306 2307Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc, 2308 SourceLocation TypeLoc, 2309 TypeTy *argty, 2310 OffsetOfComponent *CompPtr, 2311 unsigned NumComponents, 2312 SourceLocation RPLoc) { 2313 QualType ArgTy = QualType::getFromOpaquePtr(argty); 2314 assert(!ArgTy.isNull() && "Missing type argument!"); 2315 2316 // We must have at least one component that refers to the type, and the first 2317 // one is known to be a field designator. Verify that the ArgTy represents 2318 // a struct/union/class. 2319 if (!ArgTy->isRecordType()) 2320 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString()); 2321 2322 // Otherwise, create a compound literal expression as the base, and 2323 // iteratively process the offsetof designators. 2324 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false); 2325 2326 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 2327 // GCC extension, diagnose them. 2328 if (NumComponents != 1) 2329 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator, 2330 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd)); 2331 2332 for (unsigned i = 0; i != NumComponents; ++i) { 2333 const OffsetOfComponent &OC = CompPtr[i]; 2334 if (OC.isBrackets) { 2335 // Offset of an array sub-field. TODO: Should we allow vector elements? 2336 const ArrayType *AT = Res->getType()->getAsArrayType(); 2337 if (!AT) { 2338 delete Res; 2339 return Diag(OC.LocEnd, diag::err_offsetof_array_type, 2340 Res->getType().getAsString()); 2341 } 2342 2343 // FIXME: C++: Verify that operator[] isn't overloaded. 2344 2345 // C99 6.5.2.1p1 2346 Expr *Idx = static_cast<Expr*>(OC.U.E); 2347 if (!Idx->getType()->isIntegerType()) 2348 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript, 2349 Idx->getSourceRange()); 2350 2351 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd); 2352 continue; 2353 } 2354 2355 const RecordType *RC = Res->getType()->getAsRecordType(); 2356 if (!RC) { 2357 delete Res; 2358 return Diag(OC.LocEnd, diag::err_offsetof_record_type, 2359 Res->getType().getAsString()); 2360 } 2361 2362 // Get the decl corresponding to this. 2363 RecordDecl *RD = RC->getDecl(); 2364 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo); 2365 if (!MemberDecl) 2366 return Diag(BuiltinLoc, diag::err_typecheck_no_member, 2367 OC.U.IdentInfo->getName(), 2368 SourceRange(OC.LocStart, OC.LocEnd)); 2369 2370 // FIXME: C++: Verify that MemberDecl isn't a static field. 2371 // FIXME: Verify that MemberDecl isn't a bitfield. 2372 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't 2373 // matter here. 2374 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType()); 2375 } 2376 2377 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(), 2378 BuiltinLoc); 2379} 2380 2381 2382Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 2383 TypeTy *arg1, TypeTy *arg2, 2384 SourceLocation RPLoc) { 2385 QualType argT1 = QualType::getFromOpaquePtr(arg1); 2386 QualType argT2 = QualType::getFromOpaquePtr(arg2); 2387 2388 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 2389 2390 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc); 2391} 2392 2393Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond, 2394 ExprTy *expr1, ExprTy *expr2, 2395 SourceLocation RPLoc) { 2396 Expr *CondExpr = static_cast<Expr*>(cond); 2397 Expr *LHSExpr = static_cast<Expr*>(expr1); 2398 Expr *RHSExpr = static_cast<Expr*>(expr2); 2399 2400 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 2401 2402 // The conditional expression is required to be a constant expression. 2403 llvm::APSInt condEval(32); 2404 SourceLocation ExpLoc; 2405 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 2406 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant, 2407 CondExpr->getSourceRange()); 2408 2409 // If the condition is > zero, then the AST type is the same as the LSHExpr. 2410 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() : 2411 RHSExpr->getType(); 2412 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc); 2413} 2414 2415/// ExprsMatchFnType - return true if the Exprs in array Args have 2416/// QualTypes that match the QualTypes of the arguments of the FnType. 2417/// The number of arguments has already been validated to match the number of 2418/// arguments in FnType. 2419static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) { 2420 unsigned NumParams = FnType->getNumArgs(); 2421 for (unsigned i = 0; i != NumParams; ++i) { 2422 QualType ExprTy = Args[i]->getType().getCanonicalType(); 2423 QualType ParmTy = FnType->getArgType(i).getCanonicalType(); 2424 2425 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType()) 2426 return false; 2427 } 2428 return true; 2429} 2430 2431Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs, 2432 SourceLocation *CommaLocs, 2433 SourceLocation BuiltinLoc, 2434 SourceLocation RParenLoc) { 2435 // __builtin_overload requires at least 2 arguments 2436 if (NumArgs < 2) 2437 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args, 2438 SourceRange(BuiltinLoc, RParenLoc)); 2439 2440 // The first argument is required to be a constant expression. It tells us 2441 // the number of arguments to pass to each of the functions to be overloaded. 2442 Expr **Args = reinterpret_cast<Expr**>(args); 2443 Expr *NParamsExpr = Args[0]; 2444 llvm::APSInt constEval(32); 2445 SourceLocation ExpLoc; 2446 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc)) 2447 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant, 2448 NParamsExpr->getSourceRange()); 2449 2450 // Verify that the number of parameters is > 0 2451 unsigned NumParams = constEval.getZExtValue(); 2452 if (NumParams == 0) 2453 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant, 2454 NParamsExpr->getSourceRange()); 2455 // Verify that we have at least 1 + NumParams arguments to the builtin. 2456 if ((NumParams + 1) > NumArgs) 2457 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args, 2458 SourceRange(BuiltinLoc, RParenLoc)); 2459 2460 // Figure out the return type, by matching the args to one of the functions 2461 // listed after the parameters. 2462 OverloadExpr *OE = 0; 2463 for (unsigned i = NumParams + 1; i < NumArgs; ++i) { 2464 // UsualUnaryConversions will convert the function DeclRefExpr into a 2465 // pointer to function. 2466 Expr *Fn = UsualUnaryConversions(Args[i]); 2467 FunctionTypeProto *FnType = 0; 2468 if (const PointerType *PT = Fn->getType()->getAsPointerType()) { 2469 QualType PointeeType = PT->getPointeeType().getCanonicalType(); 2470 FnType = dyn_cast<FunctionTypeProto>(PointeeType); 2471 } 2472 2473 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no 2474 // parameters, and the number of parameters must match the value passed to 2475 // the builtin. 2476 if (!FnType || (FnType->getNumArgs() != NumParams)) 2477 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype, 2478 Fn->getSourceRange()); 2479 2480 // Scan the parameter list for the FunctionType, checking the QualType of 2481 // each parameter against the QualTypes of the arguments to the builtin. 2482 // If they match, return a new OverloadExpr. 2483 if (ExprsMatchFnType(Args+1, FnType)) { 2484 if (OE) 2485 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match, 2486 OE->getFn()->getSourceRange()); 2487 // Remember our match, and continue processing the remaining arguments 2488 // to catch any errors. 2489 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(), 2490 BuiltinLoc, RParenLoc); 2491 } 2492 } 2493 // Return the newly created OverloadExpr node, if we succeded in matching 2494 // exactly one of the candidate functions. 2495 if (OE) 2496 return OE; 2497 2498 // If we didn't find a matching function Expr in the __builtin_overload list 2499 // the return an error. 2500 std::string typeNames; 2501 for (unsigned i = 0; i != NumParams; ++i) { 2502 if (i != 0) typeNames += ", "; 2503 typeNames += Args[i+1]->getType().getAsString(); 2504 } 2505 2506 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames, 2507 SourceRange(BuiltinLoc, RParenLoc)); 2508} 2509 2510Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 2511 ExprTy *expr, TypeTy *type, 2512 SourceLocation RPLoc) { 2513 Expr *E = static_cast<Expr*>(expr); 2514 QualType T = QualType::getFromOpaquePtr(type); 2515 2516 InitBuiltinVaListType(); 2517 2518 if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType()) 2519 != Compatible) 2520 return Diag(E->getLocStart(), 2521 diag::err_first_argument_to_va_arg_not_of_type_va_list, 2522 E->getType().getAsString(), 2523 E->getSourceRange()); 2524 2525 // FIXME: Warn if a non-POD type is passed in. 2526 2527 return new VAArgExpr(BuiltinLoc, E, T, RPLoc); 2528} 2529 2530bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 2531 SourceLocation Loc, 2532 QualType DstType, QualType SrcType, 2533 Expr *SrcExpr, const char *Flavor) { 2534 // Decode the result (notice that AST's are still created for extensions). 2535 bool isInvalid = false; 2536 unsigned DiagKind; 2537 switch (ConvTy) { 2538 default: assert(0 && "Unknown conversion type"); 2539 case Compatible: return false; 2540 case PointerToInt: 2541 DiagKind = diag::ext_typecheck_convert_pointer_int; 2542 break; 2543 case IntToPointer: 2544 DiagKind = diag::ext_typecheck_convert_int_pointer; 2545 break; 2546 case IncompatiblePointer: 2547 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 2548 break; 2549 case FunctionVoidPointer: 2550 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 2551 break; 2552 case CompatiblePointerDiscardsQualifiers: 2553 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 2554 break; 2555 case Incompatible: 2556 DiagKind = diag::err_typecheck_convert_incompatible; 2557 isInvalid = true; 2558 break; 2559 } 2560 2561 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor, 2562 SrcExpr->getSourceRange()); 2563 return isInvalid; 2564} 2565