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