1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// 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 type-related semantic analysis. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "Sema.h" 15 #include "SemaInherit.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/DeclTemplate.h" 19 #include "clang/AST/Expr.h" 20 #include "clang/Parse/DeclSpec.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 using namespace clang; 23 24 /// \brief Perform adjustment on the parameter type of a function. 25 /// 26 /// This routine adjusts the given parameter type @p T to the actual 27 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8], 28 /// C++ [dcl.fct]p3). The adjusted parameter type is returned. 29 QualType Sema::adjustParameterType(QualType T) { 30 // C99 6.7.5.3p7: 31 if (T->isArrayType()) { 32 // C99 6.7.5.3p7: 33 // A declaration of a parameter as "array of type" shall be 34 // adjusted to "qualified pointer to type", where the type 35 // qualifiers (if any) are those specified within the [ and ] of 36 // the array type derivation. 37 return Context.getArrayDecayedType(T); 38 } else if (T->isFunctionType()) 39 // C99 6.7.5.3p8: 40 // A declaration of a parameter as "function returning type" 41 // shall be adjusted to "pointer to function returning type", as 42 // in 6.3.2.1. 43 return Context.getPointerType(T); 44 45 return T; 46 } 47 48 /// \brief Convert the specified declspec to the appropriate type 49 /// object. 50 /// \param DS the declaration specifiers 51 /// \param DeclLoc The location of the declarator identifier or invalid if none. 52 /// \returns The type described by the declaration specifiers. This function 53 /// never returns null. 54 QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS, 55 SourceLocation DeclLoc, 56 bool &isInvalid) { 57 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 58 // checking. 59 QualType Result; 60 61 switch (DS.getTypeSpecType()) { 62 case DeclSpec::TST_void: 63 Result = Context.VoidTy; 64 break; 65 case DeclSpec::TST_char: 66 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 67 Result = Context.CharTy; 68 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 69 Result = Context.SignedCharTy; 70 else { 71 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 72 "Unknown TSS value"); 73 Result = Context.UnsignedCharTy; 74 } 75 break; 76 case DeclSpec::TST_wchar: 77 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 78 Result = Context.WCharTy; 79 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 80 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 81 << DS.getSpecifierName(DS.getTypeSpecType()); 82 Result = Context.getSignedWCharType(); 83 } else { 84 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 85 "Unknown TSS value"); 86 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 87 << DS.getSpecifierName(DS.getTypeSpecType()); 88 Result = Context.getUnsignedWCharType(); 89 } 90 break; 91 case DeclSpec::TST_unspecified: 92 // "<proto1,proto2>" is an objc qualified ID with a missing id. 93 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 94 Result = Context.getObjCObjectPointerType(0, (ObjCProtocolDecl**)PQ, 95 DS.getNumProtocolQualifiers()); 96 break; 97 } 98 99 // Unspecified typespec defaults to int in C90. However, the C90 grammar 100 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 101 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 102 // Note that the one exception to this is function definitions, which are 103 // allowed to be completely missing a declspec. This is handled in the 104 // parser already though by it pretending to have seen an 'int' in this 105 // case. 106 if (getLangOptions().ImplicitInt) { 107 // In C89 mode, we only warn if there is a completely missing declspec 108 // when one is not allowed. 109 if (DS.isEmpty()) { 110 if (DeclLoc.isInvalid()) 111 DeclLoc = DS.getSourceRange().getBegin(); 112 Diag(DeclLoc, diag::ext_missing_declspec) 113 << DS.getSourceRange() 114 << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(), 115 "int"); 116 } 117 } else if (!DS.hasTypeSpecifier()) { 118 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 119 // "At least one type specifier shall be given in the declaration 120 // specifiers in each declaration, and in the specifier-qualifier list in 121 // each struct declaration and type name." 122 // FIXME: Does Microsoft really have the implicit int extension in C++? 123 if (DeclLoc.isInvalid()) 124 DeclLoc = DS.getSourceRange().getBegin(); 125 126 if (getLangOptions().CPlusPlus && !getLangOptions().Microsoft) { 127 Diag(DeclLoc, diag::err_missing_type_specifier) 128 << DS.getSourceRange(); 129 130 // When this occurs in C++ code, often something is very broken with the 131 // value being declared, poison it as invalid so we don't get chains of 132 // errors. 133 isInvalid = true; 134 } else { 135 Diag(DeclLoc, diag::ext_missing_type_specifier) 136 << DS.getSourceRange(); 137 } 138 } 139 140 // FALL THROUGH. 141 case DeclSpec::TST_int: { 142 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 143 switch (DS.getTypeSpecWidth()) { 144 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 145 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 146 case DeclSpec::TSW_long: Result = Context.LongTy; break; 147 case DeclSpec::TSW_longlong: Result = Context.LongLongTy; break; 148 } 149 } else { 150 switch (DS.getTypeSpecWidth()) { 151 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 152 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 153 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 154 case DeclSpec::TSW_longlong: Result =Context.UnsignedLongLongTy; break; 155 } 156 } 157 break; 158 } 159 case DeclSpec::TST_float: Result = Context.FloatTy; break; 160 case DeclSpec::TST_double: 161 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 162 Result = Context.LongDoubleTy; 163 else 164 Result = Context.DoubleTy; 165 break; 166 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 167 case DeclSpec::TST_decimal32: // _Decimal32 168 case DeclSpec::TST_decimal64: // _Decimal64 169 case DeclSpec::TST_decimal128: // _Decimal128 170 Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 171 Result = Context.IntTy; 172 isInvalid = true; 173 break; 174 case DeclSpec::TST_class: 175 case DeclSpec::TST_enum: 176 case DeclSpec::TST_union: 177 case DeclSpec::TST_struct: { 178 Decl *D = static_cast<Decl *>(DS.getTypeRep()); 179 assert(D && "Didn't get a decl for a class/enum/union/struct?"); 180 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 181 DS.getTypeSpecSign() == 0 && 182 "Can't handle qualifiers on typedef names yet!"); 183 // TypeQuals handled by caller. 184 Result = Context.getTypeDeclType(cast<TypeDecl>(D)); 185 186 if (D->isInvalidDecl()) 187 isInvalid = true; 188 break; 189 } 190 case DeclSpec::TST_typename: { 191 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 192 DS.getTypeSpecSign() == 0 && 193 "Can't handle qualifiers on typedef names yet!"); 194 Result = QualType::getFromOpaquePtr(DS.getTypeRep()); 195 196 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 197 // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so we have 198 // this "hack" for now... 199 if (const ObjCInterfaceType *Interface = Result->getAsObjCInterfaceType()) 200 Result = Context.getObjCQualifiedInterfaceType(Interface->getDecl(), 201 (ObjCProtocolDecl**)PQ, 202 DS.getNumProtocolQualifiers()); 203 else if (Result == Context.getObjCIdType()) 204 // id<protocol-list> 205 Result = Context.getObjCObjectPointerType(0, (ObjCProtocolDecl**)PQ, 206 DS.getNumProtocolQualifiers()); 207 else if (Result == Context.getObjCClassType()) { 208 if (DeclLoc.isInvalid()) 209 DeclLoc = DS.getSourceRange().getBegin(); 210 // Class<protocol-list> 211 Diag(DeclLoc, diag::err_qualified_class_unsupported) 212 << DS.getSourceRange(); 213 } else { 214 if (DeclLoc.isInvalid()) 215 DeclLoc = DS.getSourceRange().getBegin(); 216 Diag(DeclLoc, diag::err_invalid_protocol_qualifiers) 217 << DS.getSourceRange(); 218 isInvalid = true; 219 } 220 } 221 222 // If this is a reference to an invalid typedef, propagate the invalidity. 223 if (TypedefType *TDT = dyn_cast<TypedefType>(Result)) 224 if (TDT->getDecl()->isInvalidDecl()) 225 isInvalid = true; 226 227 // TypeQuals handled by caller. 228 break; 229 } 230 case DeclSpec::TST_typeofType: 231 Result = QualType::getFromOpaquePtr(DS.getTypeRep()); 232 assert(!Result.isNull() && "Didn't get a type for typeof?"); 233 // TypeQuals handled by caller. 234 Result = Context.getTypeOfType(Result); 235 break; 236 case DeclSpec::TST_typeofExpr: { 237 Expr *E = static_cast<Expr *>(DS.getTypeRep()); 238 assert(E && "Didn't get an expression for typeof?"); 239 // TypeQuals handled by caller. 240 Result = Context.getTypeOfExprType(E); 241 break; 242 } 243 case DeclSpec::TST_decltype: { 244 Expr *E = static_cast<Expr *>(DS.getTypeRep()); 245 assert(E && "Didn't get an expression for decltype?"); 246 // TypeQuals handled by caller. 247 Result = BuildDecltypeType(E); 248 if (Result.isNull()) { 249 Result = Context.IntTy; 250 isInvalid = true; 251 } 252 break; 253 } 254 case DeclSpec::TST_auto: { 255 // TypeQuals handled by caller. 256 Result = Context.UndeducedAutoTy; 257 break; 258 } 259 260 case DeclSpec::TST_error: 261 Result = Context.IntTy; 262 isInvalid = true; 263 break; 264 } 265 266 // Handle complex types. 267 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 268 if (getLangOptions().Freestanding) 269 Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 270 Result = Context.getComplexType(Result); 271 } 272 273 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary && 274 "FIXME: imaginary types not supported yet!"); 275 276 // See if there are any attributes on the declspec that apply to the type (as 277 // opposed to the decl). 278 if (const AttributeList *AL = DS.getAttributes()) 279 ProcessTypeAttributeList(Result, AL); 280 281 // Apply const/volatile/restrict qualifiers to T. 282 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 283 284 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 285 // or incomplete types shall not be restrict-qualified." C++ also allows 286 // restrict-qualified references. 287 if (TypeQuals & QualType::Restrict) { 288 if (Result->isPointerType() || Result->isReferenceType()) { 289 QualType EltTy = Result->isPointerType() ? 290 Result->getAsPointerType()->getPointeeType() : 291 Result->getAsReferenceType()->getPointeeType(); 292 293 // If we have a pointer or reference, the pointee must have an object 294 // incomplete type. 295 if (!EltTy->isIncompleteOrObjectType()) { 296 Diag(DS.getRestrictSpecLoc(), 297 diag::err_typecheck_invalid_restrict_invalid_pointee) 298 << EltTy << DS.getSourceRange(); 299 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier. 300 } 301 } else { 302 Diag(DS.getRestrictSpecLoc(), 303 diag::err_typecheck_invalid_restrict_not_pointer) 304 << Result << DS.getSourceRange(); 305 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier. 306 } 307 } 308 309 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification 310 // of a function type includes any type qualifiers, the behavior is 311 // undefined." 312 if (Result->isFunctionType() && TypeQuals) { 313 // Get some location to point at, either the C or V location. 314 SourceLocation Loc; 315 if (TypeQuals & QualType::Const) 316 Loc = DS.getConstSpecLoc(); 317 else { 318 assert((TypeQuals & QualType::Volatile) && 319 "Has CV quals but not C or V?"); 320 Loc = DS.getVolatileSpecLoc(); 321 } 322 Diag(Loc, diag::warn_typecheck_function_qualifiers) 323 << Result << DS.getSourceRange(); 324 } 325 326 // C++ [dcl.ref]p1: 327 // Cv-qualified references are ill-formed except when the 328 // cv-qualifiers are introduced through the use of a typedef 329 // (7.1.3) or of a template type argument (14.3), in which 330 // case the cv-qualifiers are ignored. 331 // FIXME: Shouldn't we be checking SCS_typedef here? 332 if (DS.getTypeSpecType() == DeclSpec::TST_typename && 333 TypeQuals && Result->isReferenceType()) { 334 TypeQuals &= ~QualType::Const; 335 TypeQuals &= ~QualType::Volatile; 336 } 337 338 Result = Result.getQualifiedType(TypeQuals); 339 } 340 return Result; 341 } 342 343 static std::string getPrintableNameForEntity(DeclarationName Entity) { 344 if (Entity) 345 return Entity.getAsString(); 346 347 return "type name"; 348 } 349 350 /// \brief Build a pointer type. 351 /// 352 /// \param T The type to which we'll be building a pointer. 353 /// 354 /// \param Quals The cvr-qualifiers to be applied to the pointer type. 355 /// 356 /// \param Loc The location of the entity whose type involves this 357 /// pointer type or, if there is no such entity, the location of the 358 /// type that will have pointer type. 359 /// 360 /// \param Entity The name of the entity that involves the pointer 361 /// type, if known. 362 /// 363 /// \returns A suitable pointer type, if there are no 364 /// errors. Otherwise, returns a NULL type. 365 QualType Sema::BuildPointerType(QualType T, unsigned Quals, 366 SourceLocation Loc, DeclarationName Entity) { 367 if (T->isReferenceType()) { 368 // C++ 8.3.2p4: There shall be no ... pointers to references ... 369 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 370 << getPrintableNameForEntity(Entity); 371 return QualType(); 372 } 373 374 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 375 // object or incomplete types shall not be restrict-qualified." 376 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) { 377 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 378 << T; 379 Quals &= ~QualType::Restrict; 380 } 381 382 // Build the pointer type. 383 return Context.getPointerType(T).getQualifiedType(Quals); 384 } 385 386 /// \brief Build a reference type. 387 /// 388 /// \param T The type to which we'll be building a reference. 389 /// 390 /// \param Quals The cvr-qualifiers to be applied to the reference type. 391 /// 392 /// \param Loc The location of the entity whose type involves this 393 /// reference type or, if there is no such entity, the location of the 394 /// type that will have reference type. 395 /// 396 /// \param Entity The name of the entity that involves the reference 397 /// type, if known. 398 /// 399 /// \returns A suitable reference type, if there are no 400 /// errors. Otherwise, returns a NULL type. 401 QualType Sema::BuildReferenceType(QualType T, bool LValueRef, unsigned Quals, 402 SourceLocation Loc, DeclarationName Entity) { 403 if (LValueRef) { 404 if (const RValueReferenceType *R = T->getAsRValueReferenceType()) { 405 // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a 406 // reference to a type T, and attempt to create the type "lvalue 407 // reference to cv TD" creates the type "lvalue reference to T". 408 // We use the qualifiers (restrict or none) of the original reference, 409 // not the new ones. This is consistent with GCC. 410 return Context.getLValueReferenceType(R->getPointeeType()). 411 getQualifiedType(T.getCVRQualifiers()); 412 } 413 } 414 if (T->isReferenceType()) { 415 // C++ [dcl.ref]p4: There shall be no references to references. 416 // 417 // According to C++ DR 106, references to references are only 418 // diagnosed when they are written directly (e.g., "int & &"), 419 // but not when they happen via a typedef: 420 // 421 // typedef int& intref; 422 // typedef intref& intref2; 423 // 424 // Parser::ParserDeclaratorInternal diagnoses the case where 425 // references are written directly; here, we handle the 426 // collapsing of references-to-references as described in C++ 427 // DR 106 and amended by C++ DR 540. 428 return T; 429 } 430 431 // C++ [dcl.ref]p1: 432 // A declarator that specifies the type “reference to cv void” 433 // is ill-formed. 434 if (T->isVoidType()) { 435 Diag(Loc, diag::err_reference_to_void); 436 return QualType(); 437 } 438 439 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 440 // object or incomplete types shall not be restrict-qualified." 441 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) { 442 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 443 << T; 444 Quals &= ~QualType::Restrict; 445 } 446 447 // C++ [dcl.ref]p1: 448 // [...] Cv-qualified references are ill-formed except when the 449 // cv-qualifiers are introduced through the use of a typedef 450 // (7.1.3) or of a template type argument (14.3), in which case 451 // the cv-qualifiers are ignored. 452 // 453 // We diagnose extraneous cv-qualifiers for the non-typedef, 454 // non-template type argument case within the parser. Here, we just 455 // ignore any extraneous cv-qualifiers. 456 Quals &= ~QualType::Const; 457 Quals &= ~QualType::Volatile; 458 459 // Handle restrict on references. 460 if (LValueRef) 461 return Context.getLValueReferenceType(T).getQualifiedType(Quals); 462 return Context.getRValueReferenceType(T).getQualifiedType(Quals); 463 } 464 465 /// \brief Build an array type. 466 /// 467 /// \param T The type of each element in the array. 468 /// 469 /// \param ASM C99 array size modifier (e.g., '*', 'static'). 470 /// 471 /// \param ArraySize Expression describing the size of the array. 472 /// 473 /// \param Quals The cvr-qualifiers to be applied to the array's 474 /// element type. 475 /// 476 /// \param Loc The location of the entity whose type involves this 477 /// array type or, if there is no such entity, the location of the 478 /// type that will have array type. 479 /// 480 /// \param Entity The name of the entity that involves the array 481 /// type, if known. 482 /// 483 /// \returns A suitable array type, if there are no errors. Otherwise, 484 /// returns a NULL type. 485 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 486 Expr *ArraySize, unsigned Quals, 487 SourceRange Brackets, DeclarationName Entity) { 488 SourceLocation Loc = Brackets.getBegin(); 489 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 490 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 491 if (RequireCompleteType(Loc, T, 492 diag::err_illegal_decl_array_incomplete_type)) 493 return QualType(); 494 495 if (T->isFunctionType()) { 496 Diag(Loc, diag::err_illegal_decl_array_of_functions) 497 << getPrintableNameForEntity(Entity); 498 return QualType(); 499 } 500 501 // C++ 8.3.2p4: There shall be no ... arrays of references ... 502 if (T->isReferenceType()) { 503 Diag(Loc, diag::err_illegal_decl_array_of_references) 504 << getPrintableNameForEntity(Entity); 505 return QualType(); 506 } 507 508 if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) { 509 Diag(Loc, diag::err_illegal_decl_array_of_auto) 510 << getPrintableNameForEntity(Entity); 511 return QualType(); 512 } 513 514 if (const RecordType *EltTy = T->getAsRecordType()) { 515 // If the element type is a struct or union that contains a variadic 516 // array, accept it as a GNU extension: C99 6.7.2.1p2. 517 if (EltTy->getDecl()->hasFlexibleArrayMember()) 518 Diag(Loc, diag::ext_flexible_array_in_array) << T; 519 } else if (T->isObjCInterfaceType()) { 520 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 521 return QualType(); 522 } 523 524 // C99 6.7.5.2p1: The size expression shall have integer type. 525 if (ArraySize && !ArraySize->isTypeDependent() && 526 !ArraySize->getType()->isIntegerType()) { 527 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 528 << ArraySize->getType() << ArraySize->getSourceRange(); 529 ArraySize->Destroy(Context); 530 return QualType(); 531 } 532 llvm::APSInt ConstVal(32); 533 if (!ArraySize) { 534 if (ASM == ArrayType::Star) 535 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets); 536 else 537 T = Context.getIncompleteArrayType(T, ASM, Quals); 538 } else if (ArraySize->isValueDependent()) { 539 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 540 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) || 541 (!T->isDependentType() && !T->isConstantSizeType())) { 542 // Per C99, a variable array is an array with either a non-constant 543 // size or an element type that has a non-constant-size 544 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 545 } else { 546 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 547 // have a value greater than zero. 548 if (ConstVal.isSigned()) { 549 if (ConstVal.isNegative()) { 550 Diag(ArraySize->getLocStart(), 551 diag::err_typecheck_negative_array_size) 552 << ArraySize->getSourceRange(); 553 return QualType(); 554 } else if (ConstVal == 0) { 555 // GCC accepts zero sized static arrays. 556 Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size) 557 << ArraySize->getSourceRange(); 558 } 559 } 560 T = Context.getConstantArrayWithExprType(T, ConstVal, ArraySize, 561 ASM, Quals, Brackets); 562 } 563 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 564 if (!getLangOptions().C99) { 565 if (ArraySize && !ArraySize->isTypeDependent() && 566 !ArraySize->isValueDependent() && 567 !ArraySize->isIntegerConstantExpr(Context)) 568 Diag(Loc, diag::ext_vla); 569 else if (ASM != ArrayType::Normal || Quals != 0) 570 Diag(Loc, diag::ext_c99_array_usage); 571 } 572 573 return T; 574 } 575 576 /// \brief Build an ext-vector type. 577 /// 578 /// Run the required checks for the extended vector type. 579 QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize, 580 SourceLocation AttrLoc) { 581 582 Expr *Arg = (Expr *)ArraySize.get(); 583 584 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 585 // in conjunction with complex types (pointers, arrays, functions, etc.). 586 if (!T->isDependentType() && 587 !T->isIntegerType() && !T->isRealFloatingType()) { 588 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 589 return QualType(); 590 } 591 592 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 593 llvm::APSInt vecSize(32); 594 if (!Arg->isIntegerConstantExpr(vecSize, Context)) { 595 Diag(AttrLoc, diag::err_attribute_argument_not_int) 596 << "ext_vector_type" << Arg->getSourceRange(); 597 return QualType(); 598 } 599 600 // unlike gcc's vector_size attribute, the size is specified as the 601 // number of elements, not the number of bytes. 602 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 603 604 if (vectorSize == 0) { 605 Diag(AttrLoc, diag::err_attribute_zero_size) 606 << Arg->getSourceRange(); 607 return QualType(); 608 } 609 610 if (!T->isDependentType()) 611 return Context.getExtVectorType(T, vectorSize); 612 } 613 614 return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(), 615 AttrLoc); 616 } 617 618 /// \brief Build a function type. 619 /// 620 /// This routine checks the function type according to C++ rules and 621 /// under the assumption that the result type and parameter types have 622 /// just been instantiated from a template. It therefore duplicates 623 /// some of the behavior of GetTypeForDeclarator, but in a much 624 /// simpler form that is only suitable for this narrow use case. 625 /// 626 /// \param T The return type of the function. 627 /// 628 /// \param ParamTypes The parameter types of the function. This array 629 /// will be modified to account for adjustments to the types of the 630 /// function parameters. 631 /// 632 /// \param NumParamTypes The number of parameter types in ParamTypes. 633 /// 634 /// \param Variadic Whether this is a variadic function type. 635 /// 636 /// \param Quals The cvr-qualifiers to be applied to the function type. 637 /// 638 /// \param Loc The location of the entity whose type involves this 639 /// function type or, if there is no such entity, the location of the 640 /// type that will have function type. 641 /// 642 /// \param Entity The name of the entity that involves the function 643 /// type, if known. 644 /// 645 /// \returns A suitable function type, if there are no 646 /// errors. Otherwise, returns a NULL type. 647 QualType Sema::BuildFunctionType(QualType T, 648 QualType *ParamTypes, 649 unsigned NumParamTypes, 650 bool Variadic, unsigned Quals, 651 SourceLocation Loc, DeclarationName Entity) { 652 if (T->isArrayType() || T->isFunctionType()) { 653 Diag(Loc, diag::err_func_returning_array_function) << T; 654 return QualType(); 655 } 656 657 bool Invalid = false; 658 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) { 659 QualType ParamType = adjustParameterType(ParamTypes[Idx]); 660 if (ParamType->isVoidType()) { 661 Diag(Loc, diag::err_param_with_void_type); 662 Invalid = true; 663 } 664 665 ParamTypes[Idx] = ParamType; 666 } 667 668 if (Invalid) 669 return QualType(); 670 671 return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic, 672 Quals); 673 } 674 675 /// \brief Build a member pointer type \c T Class::*. 676 /// 677 /// \param T the type to which the member pointer refers. 678 /// \param Class the class type into which the member pointer points. 679 /// \param Quals Qualifiers applied to the member pointer type 680 /// \param Loc the location where this type begins 681 /// \param Entity the name of the entity that will have this member pointer type 682 /// 683 /// \returns a member pointer type, if successful, or a NULL type if there was 684 /// an error. 685 QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 686 unsigned Quals, SourceLocation Loc, 687 DeclarationName Entity) { 688 // Verify that we're not building a pointer to pointer to function with 689 // exception specification. 690 if (CheckDistantExceptionSpec(T)) { 691 Diag(Loc, diag::err_distant_exception_spec); 692 693 // FIXME: If we're doing this as part of template instantiation, 694 // we should return immediately. 695 696 // Build the type anyway, but use the canonical type so that the 697 // exception specifiers are stripped off. 698 T = Context.getCanonicalType(T); 699 } 700 701 // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member 702 // with reference type, or "cv void." 703 if (T->isReferenceType()) { 704 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 705 << (Entity? Entity.getAsString() : "type name"); 706 return QualType(); 707 } 708 709 if (T->isVoidType()) { 710 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 711 << (Entity? Entity.getAsString() : "type name"); 712 return QualType(); 713 } 714 715 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 716 // object or incomplete types shall not be restrict-qualified." 717 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) { 718 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 719 << T; 720 721 // FIXME: If we're doing this as part of template instantiation, 722 // we should return immediately. 723 Quals &= ~QualType::Restrict; 724 } 725 726 if (!Class->isDependentType() && !Class->isRecordType()) { 727 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 728 return QualType(); 729 } 730 731 return Context.getMemberPointerType(T, Class.getTypePtr()) 732 .getQualifiedType(Quals); 733 } 734 735 /// \brief Build a block pointer type. 736 /// 737 /// \param T The type to which we'll be building a block pointer. 738 /// 739 /// \param Quals The cvr-qualifiers to be applied to the block pointer type. 740 /// 741 /// \param Loc The location of the entity whose type involves this 742 /// block pointer type or, if there is no such entity, the location of the 743 /// type that will have block pointer type. 744 /// 745 /// \param Entity The name of the entity that involves the block pointer 746 /// type, if known. 747 /// 748 /// \returns A suitable block pointer type, if there are no 749 /// errors. Otherwise, returns a NULL type. 750 QualType Sema::BuildBlockPointerType(QualType T, unsigned Quals, 751 SourceLocation Loc, 752 DeclarationName Entity) { 753 if (!T.getTypePtr()->isFunctionType()) { 754 Diag(Loc, diag::err_nonfunction_block_type); 755 return QualType(); 756 } 757 758 return Context.getBlockPointerType(T).getQualifiedType(Quals); 759 } 760 761 /// GetTypeForDeclarator - Convert the type for the specified 762 /// declarator to Type instances. Skip the outermost Skip type 763 /// objects. 764 /// 765 /// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq 766 /// owns the declaration of a type (e.g., the definition of a struct 767 /// type), then *OwnedDecl will receive the owned declaration. 768 QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip, 769 TagDecl **OwnedDecl) { 770 bool OmittedReturnType = false; 771 772 if (D.getContext() == Declarator::BlockLiteralContext 773 && Skip == 0 774 && !D.getDeclSpec().hasTypeSpecifier() 775 && (D.getNumTypeObjects() == 0 776 || (D.getNumTypeObjects() == 1 777 && D.getTypeObject(0).Kind == DeclaratorChunk::Function))) 778 OmittedReturnType = true; 779 780 // long long is a C99 feature. 781 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 782 D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong) 783 Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong); 784 785 // Determine the type of the declarator. Not all forms of declarator 786 // have a type. 787 QualType T; 788 switch (D.getKind()) { 789 case Declarator::DK_Abstract: 790 case Declarator::DK_Normal: 791 case Declarator::DK_Operator: { 792 const DeclSpec &DS = D.getDeclSpec(); 793 if (OmittedReturnType) { 794 // We default to a dependent type initially. Can be modified by 795 // the first return statement. 796 T = Context.DependentTy; 797 } else { 798 bool isInvalid = false; 799 T = ConvertDeclSpecToType(DS, D.getIdentifierLoc(), isInvalid); 800 if (isInvalid) 801 D.setInvalidType(true); 802 else if (OwnedDecl && DS.isTypeSpecOwned()) 803 *OwnedDecl = cast<TagDecl>((Decl *)DS.getTypeRep()); 804 } 805 break; 806 } 807 808 case Declarator::DK_Constructor: 809 case Declarator::DK_Destructor: 810 case Declarator::DK_Conversion: 811 // Constructors and destructors don't have return types. Use 812 // "void" instead. Conversion operators will check their return 813 // types separately. 814 T = Context.VoidTy; 815 break; 816 } 817 818 if (T == Context.UndeducedAutoTy) { 819 int Error = -1; 820 821 switch (D.getContext()) { 822 case Declarator::KNRTypeListContext: 823 assert(0 && "K&R type lists aren't allowed in C++"); 824 break; 825 case Declarator::PrototypeContext: 826 Error = 0; // Function prototype 827 break; 828 case Declarator::MemberContext: 829 switch (cast<TagDecl>(CurContext)->getTagKind()) { 830 case TagDecl::TK_enum: assert(0 && "unhandled tag kind"); break; 831 case TagDecl::TK_struct: Error = 1; /* Struct member */ break; 832 case TagDecl::TK_union: Error = 2; /* Union member */ break; 833 case TagDecl::TK_class: Error = 3; /* Class member */ break; 834 } 835 break; 836 case Declarator::CXXCatchContext: 837 Error = 4; // Exception declaration 838 break; 839 case Declarator::TemplateParamContext: 840 Error = 5; // Template parameter 841 break; 842 case Declarator::BlockLiteralContext: 843 Error = 6; // Block literal 844 break; 845 case Declarator::FileContext: 846 case Declarator::BlockContext: 847 case Declarator::ForContext: 848 case Declarator::ConditionContext: 849 case Declarator::TypeNameContext: 850 break; 851 } 852 853 if (Error != -1) { 854 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed) 855 << Error; 856 T = Context.IntTy; 857 D.setInvalidType(true); 858 } 859 } 860 861 // The name we're declaring, if any. 862 DeclarationName Name; 863 if (D.getIdentifier()) 864 Name = D.getIdentifier(); 865 866 // Walk the DeclTypeInfo, building the recursive type as we go. 867 // DeclTypeInfos are ordered from the identifier out, which is 868 // opposite of what we want :). 869 for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) { 870 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip); 871 switch (DeclType.Kind) { 872 default: assert(0 && "Unknown decltype!"); 873 case DeclaratorChunk::BlockPointer: 874 // If blocks are disabled, emit an error. 875 if (!LangOpts.Blocks) 876 Diag(DeclType.Loc, diag::err_blocks_disable); 877 878 T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(), 879 Name); 880 break; 881 case DeclaratorChunk::Pointer: 882 // Verify that we're not building a pointer to pointer to function with 883 // exception specification. 884 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 885 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 886 D.setInvalidType(true); 887 // Build the type anyway. 888 } 889 T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name); 890 break; 891 case DeclaratorChunk::Reference: 892 // Verify that we're not building a reference to pointer to function with 893 // exception specification. 894 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 895 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 896 D.setInvalidType(true); 897 // Build the type anyway. 898 } 899 T = BuildReferenceType(T, DeclType.Ref.LValueRef, 900 DeclType.Ref.HasRestrict ? QualType::Restrict : 0, 901 DeclType.Loc, Name); 902 break; 903 case DeclaratorChunk::Array: { 904 // Verify that we're not building an array of pointers to function with 905 // exception specification. 906 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 907 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 908 D.setInvalidType(true); 909 // Build the type anyway. 910 } 911 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 912 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 913 ArrayType::ArraySizeModifier ASM; 914 if (ATI.isStar) 915 ASM = ArrayType::Star; 916 else if (ATI.hasStatic) 917 ASM = ArrayType::Static; 918 else 919 ASM = ArrayType::Normal; 920 if (ASM == ArrayType::Star && 921 D.getContext() != Declarator::PrototypeContext) { 922 // FIXME: This check isn't quite right: it allows star in prototypes 923 // for function definitions, and disallows some edge cases detailed 924 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 925 Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 926 ASM = ArrayType::Normal; 927 D.setInvalidType(true); 928 } 929 T = BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 930 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 931 break; 932 } 933 case DeclaratorChunk::Function: { 934 // If the function declarator has a prototype (i.e. it is not () and 935 // does not have a K&R-style identifier list), then the arguments are part 936 // of the type, otherwise the argument list is (). 937 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 938 939 // C99 6.7.5.3p1: The return type may not be a function or array type. 940 if (T->isArrayType() || T->isFunctionType()) { 941 Diag(DeclType.Loc, diag::err_func_returning_array_function) << T; 942 T = Context.IntTy; 943 D.setInvalidType(true); 944 } 945 946 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) { 947 // C++ [dcl.fct]p6: 948 // Types shall not be defined in return or parameter types. 949 TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep()); 950 if (Tag->isDefinition()) 951 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 952 << Context.getTypeDeclType(Tag); 953 } 954 955 // Exception specs are not allowed in typedefs. Complain, but add it 956 // anyway. 957 if (FTI.hasExceptionSpec && 958 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 959 Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef); 960 961 if (FTI.NumArgs == 0) { 962 if (getLangOptions().CPlusPlus) { 963 // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the 964 // function takes no arguments. 965 llvm::SmallVector<QualType, 4> Exceptions; 966 Exceptions.reserve(FTI.NumExceptions); 967 for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) { 968 QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty); 969 // Check that the type is valid for an exception spec, and drop it 970 // if not. 971 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range)) 972 Exceptions.push_back(ET); 973 } 974 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals, 975 FTI.hasExceptionSpec, 976 FTI.hasAnyExceptionSpec, 977 Exceptions.size(), Exceptions.data()); 978 } else if (FTI.isVariadic) { 979 // We allow a zero-parameter variadic function in C if the 980 // function is marked with the "overloadable" 981 // attribute. Scan for this attribute now. 982 bool Overloadable = false; 983 for (const AttributeList *Attrs = D.getAttributes(); 984 Attrs; Attrs = Attrs->getNext()) { 985 if (Attrs->getKind() == AttributeList::AT_overloadable) { 986 Overloadable = true; 987 break; 988 } 989 } 990 991 if (!Overloadable) 992 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); 993 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0); 994 } else { 995 // Simple void foo(), where the incoming T is the result type. 996 T = Context.getFunctionNoProtoType(T); 997 } 998 } else if (FTI.ArgInfo[0].Param == 0) { 999 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition. 1000 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 1001 } else { 1002 // Otherwise, we have a function with an argument list that is 1003 // potentially variadic. 1004 llvm::SmallVector<QualType, 16> ArgTys; 1005 1006 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 1007 ParmVarDecl *Param = 1008 cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>()); 1009 QualType ArgTy = Param->getType(); 1010 assert(!ArgTy.isNull() && "Couldn't parse type?"); 1011 1012 // Adjust the parameter type. 1013 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?"); 1014 1015 // Look for 'void'. void is allowed only as a single argument to a 1016 // function with no other parameters (C99 6.7.5.3p10). We record 1017 // int(void) as a FunctionProtoType with an empty argument list. 1018 if (ArgTy->isVoidType()) { 1019 // If this is something like 'float(int, void)', reject it. 'void' 1020 // is an incomplete type (C99 6.2.5p19) and function decls cannot 1021 // have arguments of incomplete type. 1022 if (FTI.NumArgs != 1 || FTI.isVariadic) { 1023 Diag(DeclType.Loc, diag::err_void_only_param); 1024 ArgTy = Context.IntTy; 1025 Param->setType(ArgTy); 1026 } else if (FTI.ArgInfo[i].Ident) { 1027 // Reject, but continue to parse 'int(void abc)'. 1028 Diag(FTI.ArgInfo[i].IdentLoc, 1029 diag::err_param_with_void_type); 1030 ArgTy = Context.IntTy; 1031 Param->setType(ArgTy); 1032 } else { 1033 // Reject, but continue to parse 'float(const void)'. 1034 if (ArgTy.getCVRQualifiers()) 1035 Diag(DeclType.Loc, diag::err_void_param_qualified); 1036 1037 // Do not add 'void' to the ArgTys list. 1038 break; 1039 } 1040 } else if (!FTI.hasPrototype) { 1041 if (ArgTy->isPromotableIntegerType()) { 1042 ArgTy = Context.IntTy; 1043 } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) { 1044 if (BTy->getKind() == BuiltinType::Float) 1045 ArgTy = Context.DoubleTy; 1046 } 1047 } 1048 1049 ArgTys.push_back(ArgTy); 1050 } 1051 1052 llvm::SmallVector<QualType, 4> Exceptions; 1053 Exceptions.reserve(FTI.NumExceptions); 1054 for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) { 1055 QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty); 1056 // Check that the type is valid for an exception spec, and drop it if 1057 // not. 1058 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range)) 1059 Exceptions.push_back(ET); 1060 } 1061 1062 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), 1063 FTI.isVariadic, FTI.TypeQuals, 1064 FTI.hasExceptionSpec, 1065 FTI.hasAnyExceptionSpec, 1066 Exceptions.size(), Exceptions.data()); 1067 } 1068 break; 1069 } 1070 case DeclaratorChunk::MemberPointer: 1071 // Verify that we're not building a pointer to pointer to function with 1072 // exception specification. 1073 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1074 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1075 D.setInvalidType(true); 1076 // Build the type anyway. 1077 } 1078 // The scope spec must refer to a class, or be dependent. 1079 QualType ClsType; 1080 if (isDependentScopeSpecifier(DeclType.Mem.Scope())) { 1081 NestedNameSpecifier *NNS 1082 = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep(); 1083 assert(NNS->getAsType() && "Nested-name-specifier must name a type"); 1084 ClsType = QualType(NNS->getAsType(), 0); 1085 } else if (CXXRecordDecl *RD 1086 = dyn_cast_or_null<CXXRecordDecl>( 1087 computeDeclContext(DeclType.Mem.Scope()))) { 1088 ClsType = Context.getTagDeclType(RD); 1089 } else { 1090 Diag(DeclType.Mem.Scope().getBeginLoc(), 1091 diag::err_illegal_decl_mempointer_in_nonclass) 1092 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 1093 << DeclType.Mem.Scope().getRange(); 1094 D.setInvalidType(true); 1095 } 1096 1097 if (!ClsType.isNull()) 1098 T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals, 1099 DeclType.Loc, D.getIdentifier()); 1100 if (T.isNull()) { 1101 T = Context.IntTy; 1102 D.setInvalidType(true); 1103 } 1104 break; 1105 } 1106 1107 if (T.isNull()) { 1108 D.setInvalidType(true); 1109 T = Context.IntTy; 1110 } 1111 1112 // See if there are any attributes on this declarator chunk. 1113 if (const AttributeList *AL = DeclType.getAttrs()) 1114 ProcessTypeAttributeList(T, AL); 1115 } 1116 1117 if (getLangOptions().CPlusPlus && T->isFunctionType()) { 1118 const FunctionProtoType *FnTy = T->getAsFunctionProtoType(); 1119 assert(FnTy && "Why oh why is there not a FunctionProtoType here ?"); 1120 1121 // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type 1122 // for a nonstatic member function, the function type to which a pointer 1123 // to member refers, or the top-level function type of a function typedef 1124 // declaration. 1125 if (FnTy->getTypeQuals() != 0 && 1126 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 1127 ((D.getContext() != Declarator::MemberContext && 1128 (!D.getCXXScopeSpec().isSet() || 1129 !computeDeclContext(D.getCXXScopeSpec())->isRecord())) || 1130 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) { 1131 if (D.isFunctionDeclarator()) 1132 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type); 1133 else 1134 Diag(D.getIdentifierLoc(), 1135 diag::err_invalid_qualified_typedef_function_type_use); 1136 1137 // Strip the cv-quals from the type. 1138 T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(), 1139 FnTy->getNumArgs(), FnTy->isVariadic(), 0); 1140 } 1141 } 1142 1143 // If there were any type attributes applied to the decl itself (not the 1144 // type, apply the type attribute to the type!) 1145 if (const AttributeList *Attrs = D.getAttributes()) 1146 ProcessTypeAttributeList(T, Attrs); 1147 1148 return T; 1149 } 1150 1151 /// CheckSpecifiedExceptionType - Check if the given type is valid in an 1152 /// exception specification. Incomplete types, or pointers to incomplete types 1153 /// other than void are not allowed. 1154 bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) { 1155 // FIXME: This may not correctly work with the fix for core issue 437, 1156 // where a class's own type is considered complete within its body. 1157 1158 // C++ 15.4p2: A type denoted in an exception-specification shall not denote 1159 // an incomplete type. 1160 if (T->isIncompleteType()) 1161 return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec) 1162 << Range << T << /*direct*/0; 1163 1164 // C++ 15.4p2: A type denoted in an exception-specification shall not denote 1165 // an incomplete type a pointer or reference to an incomplete type, other 1166 // than (cv) void*. 1167 int kind; 1168 if (const PointerType* IT = T->getAsPointerType()) { 1169 T = IT->getPointeeType(); 1170 kind = 1; 1171 } else if (const ReferenceType* IT = T->getAsReferenceType()) { 1172 T = IT->getPointeeType(); 1173 kind = 2; 1174 } else 1175 return false; 1176 1177 if (T->isIncompleteType() && !T->isVoidType()) 1178 return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec) 1179 << Range << T << /*indirect*/kind; 1180 1181 return false; 1182 } 1183 1184 /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer 1185 /// to member to a function with an exception specification. This means that 1186 /// it is invalid to add another level of indirection. 1187 bool Sema::CheckDistantExceptionSpec(QualType T) { 1188 if (const PointerType *PT = T->getAsPointerType()) 1189 T = PT->getPointeeType(); 1190 else if (const MemberPointerType *PT = T->getAsMemberPointerType()) 1191 T = PT->getPointeeType(); 1192 else 1193 return false; 1194 1195 const FunctionProtoType *FnT = T->getAsFunctionProtoType(); 1196 if (!FnT) 1197 return false; 1198 1199 return FnT->hasExceptionSpec(); 1200 } 1201 1202 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent 1203 /// exception specifications. Exception specifications are equivalent if 1204 /// they allow exactly the same set of exception types. It does not matter how 1205 /// that is achieved. See C++ [except.spec]p2. 1206 bool Sema::CheckEquivalentExceptionSpec( 1207 const FunctionProtoType *Old, SourceLocation OldLoc, 1208 const FunctionProtoType *New, SourceLocation NewLoc) { 1209 bool OldAny = !Old->hasExceptionSpec() || Old->hasAnyExceptionSpec(); 1210 bool NewAny = !New->hasExceptionSpec() || New->hasAnyExceptionSpec(); 1211 if (OldAny && NewAny) 1212 return false; 1213 if (OldAny || NewAny) { 1214 Diag(NewLoc, diag::err_mismatched_exception_spec); 1215 Diag(OldLoc, diag::note_previous_declaration); 1216 return true; 1217 } 1218 1219 bool Success = true; 1220 // Both have a definite exception spec. Collect the first set, then compare 1221 // to the second. 1222 llvm::SmallPtrSet<const Type*, 8> Types; 1223 for (FunctionProtoType::exception_iterator I = Old->exception_begin(), 1224 E = Old->exception_end(); I != E; ++I) 1225 Types.insert(Context.getCanonicalType(*I).getTypePtr()); 1226 1227 for (FunctionProtoType::exception_iterator I = New->exception_begin(), 1228 E = New->exception_end(); I != E && Success; ++I) 1229 Success = Types.erase(Context.getCanonicalType(*I).getTypePtr()); 1230 1231 Success = Success && Types.empty(); 1232 1233 if (Success) { 1234 return false; 1235 } 1236 Diag(NewLoc, diag::err_mismatched_exception_spec); 1237 Diag(OldLoc, diag::note_previous_declaration); 1238 return true; 1239 } 1240 1241 /// CheckExceptionSpecSubset - Check whether the second function type's 1242 /// exception specification is a subset (or equivalent) of the first function 1243 /// type. This is used by override and pointer assignment checks. 1244 bool Sema::CheckExceptionSpecSubset(unsigned DiagID, unsigned NoteID, 1245 const FunctionProtoType *Superset, SourceLocation SuperLoc, 1246 const FunctionProtoType *Subset, SourceLocation SubLoc) 1247 { 1248 // FIXME: As usual, we could be more specific in our error messages, but 1249 // that better waits until we've got types with source locations. 1250 1251 // If superset contains everything, we're done. 1252 if (!Superset->hasExceptionSpec() || Superset->hasAnyExceptionSpec()) 1253 return false; 1254 1255 // It does not. If the subset contains everything, we've failed. 1256 if (!Subset->hasExceptionSpec() || Subset->hasAnyExceptionSpec()) { 1257 Diag(SubLoc, DiagID); 1258 Diag(SuperLoc, NoteID); 1259 return true; 1260 } 1261 1262 // Neither contains everything. Do a proper comparison. 1263 for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(), 1264 SubE = Subset->exception_end(); SubI != SubE; ++SubI) { 1265 // Take one type from the subset. 1266 QualType CanonicalSubT = Context.getCanonicalType(*SubI); 1267 bool SubIsPointer = false; 1268 if (const ReferenceType *RefTy = CanonicalSubT->getAsReferenceType()) 1269 CanonicalSubT = RefTy->getPointeeType(); 1270 if (const PointerType *PtrTy = CanonicalSubT->getAsPointerType()) { 1271 CanonicalSubT = PtrTy->getPointeeType(); 1272 SubIsPointer = true; 1273 } 1274 bool SubIsClass = CanonicalSubT->isRecordType(); 1275 CanonicalSubT.setCVRQualifiers(0); 1276 1277 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 1278 /*DetectVirtual=*/false); 1279 1280 bool Contained = false; 1281 // Make sure it's in the superset. 1282 for (FunctionProtoType::exception_iterator SuperI = 1283 Superset->exception_begin(), SuperE = Superset->exception_end(); 1284 SuperI != SuperE; ++SuperI) { 1285 QualType CanonicalSuperT = Context.getCanonicalType(*SuperI); 1286 // SubT must be SuperT or derived from it, or pointer or reference to 1287 // such types. 1288 if (const ReferenceType *RefTy = CanonicalSuperT->getAsReferenceType()) 1289 CanonicalSuperT = RefTy->getPointeeType(); 1290 if (SubIsPointer) { 1291 if (const PointerType *PtrTy = CanonicalSuperT->getAsPointerType()) 1292 CanonicalSuperT = PtrTy->getPointeeType(); 1293 else { 1294 continue; 1295 } 1296 } 1297 CanonicalSuperT.setCVRQualifiers(0); 1298 // If the types are the same, move on to the next type in the subset. 1299 if (CanonicalSubT == CanonicalSuperT) { 1300 Contained = true; 1301 break; 1302 } 1303 1304 // Otherwise we need to check the inheritance. 1305 if (!SubIsClass || !CanonicalSuperT->isRecordType()) 1306 continue; 1307 1308 Paths.clear(); 1309 if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths)) 1310 continue; 1311 1312 if (Paths.isAmbiguous(CanonicalSuperT)) 1313 continue; 1314 1315 // FIXME: Check base access. Don't forget to enable path recording. 1316 1317 Contained = true; 1318 break; 1319 } 1320 if (!Contained) { 1321 Diag(SubLoc, DiagID); 1322 Diag(SuperLoc, NoteID); 1323 return true; 1324 } 1325 } 1326 // We've run the gauntlet. 1327 return false; 1328 } 1329 1330 /// ObjCGetTypeForMethodDefinition - Builds the type for a method definition 1331 /// declarator 1332 QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) { 1333 ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>()); 1334 QualType T = MDecl->getResultType(); 1335 llvm::SmallVector<QualType, 16> ArgTys; 1336 1337 // Add the first two invisible argument types for self and _cmd. 1338 if (MDecl->isInstanceMethod()) { 1339 QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface()); 1340 selfTy = Context.getPointerType(selfTy); 1341 ArgTys.push_back(selfTy); 1342 } else 1343 ArgTys.push_back(Context.getObjCIdType()); 1344 ArgTys.push_back(Context.getObjCSelType()); 1345 1346 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(), 1347 E = MDecl->param_end(); PI != E; ++PI) { 1348 QualType ArgTy = (*PI)->getType(); 1349 assert(!ArgTy.isNull() && "Couldn't parse type?"); 1350 ArgTy = adjustParameterType(ArgTy); 1351 ArgTys.push_back(ArgTy); 1352 } 1353 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(), 1354 MDecl->isVariadic(), 0); 1355 return T; 1356 } 1357 1358 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 1359 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that 1360 /// they point to and return true. If T1 and T2 aren't pointer types 1361 /// or pointer-to-member types, or if they are not similar at this 1362 /// level, returns false and leaves T1 and T2 unchanged. Top-level 1363 /// qualifiers on T1 and T2 are ignored. This function will typically 1364 /// be called in a loop that successively "unwraps" pointer and 1365 /// pointer-to-member types to compare them at each level. 1366 bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) { 1367 const PointerType *T1PtrType = T1->getAsPointerType(), 1368 *T2PtrType = T2->getAsPointerType(); 1369 if (T1PtrType && T2PtrType) { 1370 T1 = T1PtrType->getPointeeType(); 1371 T2 = T2PtrType->getPointeeType(); 1372 return true; 1373 } 1374 1375 const MemberPointerType *T1MPType = T1->getAsMemberPointerType(), 1376 *T2MPType = T2->getAsMemberPointerType(); 1377 if (T1MPType && T2MPType && 1378 Context.getCanonicalType(T1MPType->getClass()) == 1379 Context.getCanonicalType(T2MPType->getClass())) { 1380 T1 = T1MPType->getPointeeType(); 1381 T2 = T2MPType->getPointeeType(); 1382 return true; 1383 } 1384 return false; 1385 } 1386 1387 Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 1388 // C99 6.7.6: Type names have no identifier. This is already validated by 1389 // the parser. 1390 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 1391 1392 TagDecl *OwnedTag = 0; 1393 QualType T = GetTypeForDeclarator(D, S, /*Skip=*/0, &OwnedTag); 1394 if (D.isInvalidType()) 1395 return true; 1396 1397 if (getLangOptions().CPlusPlus) { 1398 // Check that there are no default arguments (C++ only). 1399 CheckExtraCXXDefaultArguments(D); 1400 1401 // C++0x [dcl.type]p3: 1402 // A type-specifier-seq shall not define a class or enumeration 1403 // unless it appears in the type-id of an alias-declaration 1404 // (7.1.3). 1405 if (OwnedTag && OwnedTag->isDefinition()) 1406 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier) 1407 << Context.getTypeDeclType(OwnedTag); 1408 } 1409 1410 return T.getAsOpaquePtr(); 1411 } 1412 1413 1414 1415 //===----------------------------------------------------------------------===// 1416 // Type Attribute Processing 1417 //===----------------------------------------------------------------------===// 1418 1419 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 1420 /// specified type. The attribute contains 1 argument, the id of the address 1421 /// space for the type. 1422 static void HandleAddressSpaceTypeAttribute(QualType &Type, 1423 const AttributeList &Attr, Sema &S){ 1424 // If this type is already address space qualified, reject it. 1425 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers 1426 // for two or more different address spaces." 1427 if (Type.getAddressSpace()) { 1428 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 1429 return; 1430 } 1431 1432 // Check the attribute arguments. 1433 if (Attr.getNumArgs() != 1) { 1434 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1435 return; 1436 } 1437 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 1438 llvm::APSInt addrSpace(32); 1439 if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 1440 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) 1441 << ASArgExpr->getSourceRange(); 1442 return; 1443 } 1444 1445 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 1446 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 1447 } 1448 1449 /// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the 1450 /// specified type. The attribute contains 1 argument, weak or strong. 1451 static void HandleObjCGCTypeAttribute(QualType &Type, 1452 const AttributeList &Attr, Sema &S) { 1453 if (Type.getObjCGCAttr() != QualType::GCNone) { 1454 S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc); 1455 return; 1456 } 1457 1458 // Check the attribute arguments. 1459 if (!Attr.getParameterName()) { 1460 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string) 1461 << "objc_gc" << 1; 1462 return; 1463 } 1464 QualType::GCAttrTypes GCAttr; 1465 if (Attr.getNumArgs() != 0) { 1466 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1467 return; 1468 } 1469 if (Attr.getParameterName()->isStr("weak")) 1470 GCAttr = QualType::Weak; 1471 else if (Attr.getParameterName()->isStr("strong")) 1472 GCAttr = QualType::Strong; 1473 else { 1474 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 1475 << "objc_gc" << Attr.getParameterName(); 1476 return; 1477 } 1478 1479 Type = S.Context.getObjCGCQualType(Type, GCAttr); 1480 } 1481 1482 void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) { 1483 // Scan through and apply attributes to this type where it makes sense. Some 1484 // attributes (such as __address_space__, __vector_size__, etc) apply to the 1485 // type, but others can be present in the type specifiers even though they 1486 // apply to the decl. Here we apply type attributes and ignore the rest. 1487 for (; AL; AL = AL->getNext()) { 1488 // If this is an attribute we can handle, do so now, otherwise, add it to 1489 // the LeftOverAttrs list for rechaining. 1490 switch (AL->getKind()) { 1491 default: break; 1492 case AttributeList::AT_address_space: 1493 HandleAddressSpaceTypeAttribute(Result, *AL, *this); 1494 break; 1495 case AttributeList::AT_objc_gc: 1496 HandleObjCGCTypeAttribute(Result, *AL, *this); 1497 break; 1498 } 1499 } 1500 } 1501 1502 /// @brief Ensure that the type T is a complete type. 1503 /// 1504 /// This routine checks whether the type @p T is complete in any 1505 /// context where a complete type is required. If @p T is a complete 1506 /// type, returns false. If @p T is a class template specialization, 1507 /// this routine then attempts to perform class template 1508 /// instantiation. If instantiation fails, or if @p T is incomplete 1509 /// and cannot be completed, issues the diagnostic @p diag (giving it 1510 /// the type @p T) and returns true. 1511 /// 1512 /// @param Loc The location in the source that the incomplete type 1513 /// diagnostic should refer to. 1514 /// 1515 /// @param T The type that this routine is examining for completeness. 1516 /// 1517 /// @param diag The diagnostic value (e.g., 1518 /// @c diag::err_typecheck_decl_incomplete_type) that will be used 1519 /// for the error message if @p T is incomplete. 1520 /// 1521 /// @param Range1 An optional range in the source code that will be a 1522 /// part of the "incomplete type" error message. 1523 /// 1524 /// @param Range2 An optional range in the source code that will be a 1525 /// part of the "incomplete type" error message. 1526 /// 1527 /// @param PrintType If non-NULL, the type that should be printed 1528 /// instead of @p T. This parameter should be used when the type that 1529 /// we're checking for incompleteness isn't the type that should be 1530 /// displayed to the user, e.g., when T is a type and PrintType is a 1531 /// pointer to T. 1532 /// 1533 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 1534 /// @c false otherwise. 1535 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, unsigned diag, 1536 SourceRange Range1, SourceRange Range2, 1537 QualType PrintType) { 1538 // FIXME: Add this assertion to help us flush out problems with 1539 // checking for dependent types and type-dependent expressions. 1540 // 1541 // assert(!T->isDependentType() && 1542 // "Can't ask whether a dependent type is complete"); 1543 1544 // If we have a complete type, we're done. 1545 if (!T->isIncompleteType()) 1546 return false; 1547 1548 // If we have a class template specialization or a class member of a 1549 // class template specialization, try to instantiate it. 1550 if (const RecordType *Record = T->getAsRecordType()) { 1551 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 1552 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 1553 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1554 // Update the class template specialization's location to 1555 // refer to the point of instantiation. 1556 if (Loc.isValid()) 1557 ClassTemplateSpec->setLocation(Loc); 1558 return InstantiateClassTemplateSpecialization(ClassTemplateSpec, 1559 /*ExplicitInstantiation=*/false); 1560 } 1561 } else if (CXXRecordDecl *Rec 1562 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 1563 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) { 1564 // Find the class template specialization that surrounds this 1565 // member class. 1566 ClassTemplateSpecializationDecl *Spec = 0; 1567 for (DeclContext *Parent = Rec->getDeclContext(); 1568 Parent && !Spec; Parent = Parent->getParent()) 1569 Spec = dyn_cast<ClassTemplateSpecializationDecl>(Parent); 1570 assert(Spec && "Not a member of a class template specialization?"); 1571 return InstantiateClass(Loc, Rec, Pattern, Spec->getTemplateArgs(), 1572 /*ExplicitInstantiation=*/false); 1573 } 1574 } 1575 } 1576 1577 if (PrintType.isNull()) 1578 PrintType = T; 1579 1580 // We have an incomplete type. Produce a diagnostic. 1581 Diag(Loc, diag) << PrintType << Range1 << Range2; 1582 1583 // If the type was a forward declaration of a class/struct/union 1584 // type, produce 1585 const TagType *Tag = 0; 1586 if (const RecordType *Record = T->getAsRecordType()) 1587 Tag = Record; 1588 else if (const EnumType *Enum = T->getAsEnumType()) 1589 Tag = Enum; 1590 1591 if (Tag && !Tag->getDecl()->isInvalidDecl()) 1592 Diag(Tag->getDecl()->getLocation(), 1593 Tag->isBeingDefined() ? diag::note_type_being_defined 1594 : diag::note_forward_declaration) 1595 << QualType(Tag, 0); 1596 1597 return true; 1598 } 1599 1600 /// \brief Retrieve a version of the type 'T' that is qualified by the 1601 /// nested-name-specifier contained in SS. 1602 QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) { 1603 if (!SS.isSet() || SS.isInvalid() || T.isNull()) 1604 return T; 1605 1606 NestedNameSpecifier *NNS 1607 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 1608 return Context.getQualifiedNameType(NNS, T); 1609 } 1610 1611 QualType Sema::BuildTypeofExprType(Expr *E) { 1612 return Context.getTypeOfExprType(E); 1613 } 1614 1615 QualType Sema::BuildDecltypeType(Expr *E) { 1616 if (E->getType() == Context.OverloadTy) { 1617 Diag(E->getLocStart(), 1618 diag::err_cannot_determine_declared_type_of_overloaded_function); 1619 return QualType(); 1620 } 1621 return Context.getDecltypeType(E); 1622 } 1623