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