SemaType.cpp revision ab452ba8323d1985e08bade2bced588cddf2cc28
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 "clang/AST/ASTContext.h" 16#include "clang/AST/DeclObjC.h" 17#include "clang/AST/DeclTemplate.h" 18#include "clang/AST/Expr.h" 19#include "clang/Parse/DeclSpec.h" 20using namespace clang; 21 22/// \brief Perform adjustment on the parameter type of a function. 23/// 24/// This routine adjusts the given parameter type @p T to the actual 25/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8], 26/// C++ [dcl.fct]p3). The adjusted parameter type is returned. 27QualType Sema::adjustParameterType(QualType T) { 28 // C99 6.7.5.3p7: 29 if (T->isArrayType()) { 30 // C99 6.7.5.3p7: 31 // A declaration of a parameter as "array of type" shall be 32 // adjusted to "qualified pointer to type", where the type 33 // qualifiers (if any) are those specified within the [ and ] of 34 // the array type derivation. 35 return Context.getArrayDecayedType(T); 36 } else if (T->isFunctionType()) 37 // C99 6.7.5.3p8: 38 // A declaration of a parameter as "function returning type" 39 // shall be adjusted to "pointer to function returning type", as 40 // in 6.3.2.1. 41 return Context.getPointerType(T); 42 43 return T; 44} 45 46/// \brief Convert the specified declspec to the appropriate type 47/// object. 48/// \param DS the declaration specifiers 49/// \returns The type described by the declaration specifiers, or NULL 50/// if there was an error. 51QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS) { 52 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 53 // checking. 54 QualType Result; 55 56 switch (DS.getTypeSpecType()) { 57 case DeclSpec::TST_void: 58 Result = Context.VoidTy; 59 break; 60 case DeclSpec::TST_char: 61 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 62 Result = Context.CharTy; 63 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 64 Result = Context.SignedCharTy; 65 else { 66 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 67 "Unknown TSS value"); 68 Result = Context.UnsignedCharTy; 69 } 70 break; 71 case DeclSpec::TST_wchar: 72 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 73 Result = Context.WCharTy; 74 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 75 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 76 << DS.getSpecifierName(DS.getTypeSpecType()); 77 Result = Context.getSignedWCharType(); 78 } else { 79 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 80 "Unknown TSS value"); 81 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 82 << DS.getSpecifierName(DS.getTypeSpecType()); 83 Result = Context.getUnsignedWCharType(); 84 } 85 break; 86 case DeclSpec::TST_unspecified: 87 // "<proto1,proto2>" is an objc qualified ID with a missing id. 88 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 89 Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ, 90 DS.getNumProtocolQualifiers()); 91 break; 92 } 93 94 // Unspecified typespec defaults to int in C90. However, the C90 grammar 95 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 96 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 97 // Note that the one exception to this is function definitions, which are 98 // allowed to be completely missing a declspec. This is handled in the 99 // parser already though by it pretending to have seen an 'int' in this 100 // case. 101 if (getLangOptions().ImplicitInt) { 102 // In C89 mode, we only warn if there is a completely missing declspec 103 // when one is not allowed. 104 if (DS.isEmpty()) 105 Diag(DS.getSourceRange().getBegin(), diag::warn_missing_declspec) 106 << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(), 107 "int"); 108 } else if (!DS.hasTypeSpecifier()) { 109 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 110 // "At least one type specifier shall be given in the declaration 111 // specifiers in each declaration, and in the specifier-qualifier list in 112 // each struct declaration and type name." 113 // FIXME: Does Microsoft really have the implicit int extension in C++? 114 unsigned DK = getLangOptions().CPlusPlus && !getLangOptions().Microsoft? 115 diag::err_missing_type_specifier 116 : diag::warn_missing_type_specifier; 117 Diag(DS.getSourceRange().getBegin(), DK) 118 << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(), 119 "int"); 120 } 121 122 // FALL THROUGH. 123 case DeclSpec::TST_int: { 124 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 125 switch (DS.getTypeSpecWidth()) { 126 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 127 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 128 case DeclSpec::TSW_long: Result = Context.LongTy; break; 129 case DeclSpec::TSW_longlong: Result = Context.LongLongTy; break; 130 } 131 } else { 132 switch (DS.getTypeSpecWidth()) { 133 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 134 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 135 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 136 case DeclSpec::TSW_longlong: Result =Context.UnsignedLongLongTy; break; 137 } 138 } 139 break; 140 } 141 case DeclSpec::TST_float: Result = Context.FloatTy; break; 142 case DeclSpec::TST_double: 143 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 144 Result = Context.LongDoubleTy; 145 else 146 Result = Context.DoubleTy; 147 break; 148 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 149 case DeclSpec::TST_decimal32: // _Decimal32 150 case DeclSpec::TST_decimal64: // _Decimal64 151 case DeclSpec::TST_decimal128: // _Decimal128 152 assert(0 && "FIXME: GNU decimal extensions not supported yet!"); 153 case DeclSpec::TST_class: 154 case DeclSpec::TST_enum: 155 case DeclSpec::TST_union: 156 case DeclSpec::TST_struct: { 157 Decl *D = static_cast<Decl *>(DS.getTypeRep()); 158 assert(D && "Didn't get a decl for a class/enum/union/struct?"); 159 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 160 DS.getTypeSpecSign() == 0 && 161 "Can't handle qualifiers on typedef names yet!"); 162 // TypeQuals handled by caller. 163 Result = Context.getTypeDeclType(cast<TypeDecl>(D)); 164 break; 165 } 166 case DeclSpec::TST_typename: { 167 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 168 DS.getTypeSpecSign() == 0 && 169 "Can't handle qualifiers on typedef names yet!"); 170 Result = QualType::getFromOpaquePtr(DS.getTypeRep()); 171 172 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 173 // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so 174 // we have this "hack" for now... 175 if (const ObjCInterfaceType *Interface = Result->getAsObjCInterfaceType()) 176 Result = Context.getObjCQualifiedInterfaceType(Interface->getDecl(), 177 (ObjCProtocolDecl**)PQ, 178 DS.getNumProtocolQualifiers()); 179 else if (Result == Context.getObjCIdType()) 180 // id<protocol-list> 181 Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ, 182 DS.getNumProtocolQualifiers()); 183 else if (Result == Context.getObjCClassType()) 184 // Class<protocol-list> 185 Diag(DS.getSourceRange().getBegin(), 186 diag::err_qualified_class_unsupported) << DS.getSourceRange(); 187 else 188 Diag(DS.getSourceRange().getBegin(), 189 diag::err_invalid_protocol_qualifiers) << DS.getSourceRange(); 190 } 191 // TypeQuals handled by caller. 192 break; 193 } 194 case DeclSpec::TST_typeofType: 195 Result = QualType::getFromOpaquePtr(DS.getTypeRep()); 196 assert(!Result.isNull() && "Didn't get a type for typeof?"); 197 // TypeQuals handled by caller. 198 Result = Context.getTypeOfType(Result); 199 break; 200 case DeclSpec::TST_typeofExpr: { 201 Expr *E = static_cast<Expr *>(DS.getTypeRep()); 202 assert(E && "Didn't get an expression for typeof?"); 203 // TypeQuals handled by caller. 204 Result = Context.getTypeOfExprType(E); 205 break; 206 } 207 case DeclSpec::TST_error: 208 return QualType(); 209 } 210 211 // Handle complex types. 212 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 213 if (getLangOptions().Freestanding) 214 Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 215 Result = Context.getComplexType(Result); 216 } 217 218 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary && 219 "FIXME: imaginary types not supported yet!"); 220 221 // See if there are any attributes on the declspec that apply to the type (as 222 // opposed to the decl). 223 if (const AttributeList *AL = DS.getAttributes()) 224 ProcessTypeAttributeList(Result, AL); 225 226 // Apply const/volatile/restrict qualifiers to T. 227 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 228 229 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 230 // or incomplete types shall not be restrict-qualified." C++ also allows 231 // restrict-qualified references. 232 if (TypeQuals & QualType::Restrict) { 233 if (Result->isPointerType() || Result->isReferenceType()) { 234 QualType EltTy = Result->isPointerType() ? 235 Result->getAsPointerType()->getPointeeType() : 236 Result->getAsReferenceType()->getPointeeType(); 237 238 // If we have a pointer or reference, the pointee must have an object 239 // incomplete type. 240 if (!EltTy->isIncompleteOrObjectType()) { 241 Diag(DS.getRestrictSpecLoc(), 242 diag::err_typecheck_invalid_restrict_invalid_pointee) 243 << EltTy << DS.getSourceRange(); 244 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier. 245 } 246 } else { 247 Diag(DS.getRestrictSpecLoc(), 248 diag::err_typecheck_invalid_restrict_not_pointer) 249 << Result << DS.getSourceRange(); 250 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier. 251 } 252 } 253 254 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification 255 // of a function type includes any type qualifiers, the behavior is 256 // undefined." 257 if (Result->isFunctionType() && TypeQuals) { 258 // Get some location to point at, either the C or V location. 259 SourceLocation Loc; 260 if (TypeQuals & QualType::Const) 261 Loc = DS.getConstSpecLoc(); 262 else { 263 assert((TypeQuals & QualType::Volatile) && 264 "Has CV quals but not C or V?"); 265 Loc = DS.getVolatileSpecLoc(); 266 } 267 Diag(Loc, diag::warn_typecheck_function_qualifiers) 268 << Result << DS.getSourceRange(); 269 } 270 271 // C++ [dcl.ref]p1: 272 // Cv-qualified references are ill-formed except when the 273 // cv-qualifiers are introduced through the use of a typedef 274 // (7.1.3) or of a template type argument (14.3), in which 275 // case the cv-qualifiers are ignored. 276 // FIXME: Shouldn't we be checking SCS_typedef here? 277 if (DS.getTypeSpecType() == DeclSpec::TST_typename && 278 TypeQuals && Result->isReferenceType()) { 279 TypeQuals &= ~QualType::Const; 280 TypeQuals &= ~QualType::Volatile; 281 } 282 283 Result = Result.getQualifiedType(TypeQuals); 284 } 285 return Result; 286} 287 288static std::string getPrintableNameForEntity(DeclarationName Entity) { 289 if (Entity) 290 return Entity.getAsString(); 291 292 return "type name"; 293} 294 295/// \brief Build a pointer type. 296/// 297/// \param T The type to which we'll be building a pointer. 298/// 299/// \param Quals The cvr-qualifiers to be applied to the pointer type. 300/// 301/// \param Loc The location of the entity whose type involves this 302/// pointer type or, if there is no such entity, the location of the 303/// type that will have pointer type. 304/// 305/// \param Entity The name of the entity that involves the pointer 306/// type, if known. 307/// 308/// \returns A suitable pointer type, if there are no 309/// errors. Otherwise, returns a NULL type. 310QualType Sema::BuildPointerType(QualType T, unsigned Quals, 311 SourceLocation Loc, DeclarationName Entity) { 312 if (T->isReferenceType()) { 313 // C++ 8.3.2p4: There shall be no ... pointers to references ... 314 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 315 << getPrintableNameForEntity(Entity); 316 return QualType(); 317 } 318 319 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 320 // object or incomplete types shall not be restrict-qualified." 321 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) { 322 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 323 << T; 324 Quals &= ~QualType::Restrict; 325 } 326 327 // Build the pointer type. 328 return Context.getPointerType(T).getQualifiedType(Quals); 329} 330 331/// \brief Build a reference type. 332/// 333/// \param T The type to which we'll be building a reference. 334/// 335/// \param Quals The cvr-qualifiers to be applied to the reference type. 336/// 337/// \param Loc The location of the entity whose type involves this 338/// reference type or, if there is no such entity, the location of the 339/// type that will have reference type. 340/// 341/// \param Entity The name of the entity that involves the reference 342/// type, if known. 343/// 344/// \returns A suitable reference type, if there are no 345/// errors. Otherwise, returns a NULL type. 346QualType Sema::BuildReferenceType(QualType T, bool LValueRef, unsigned Quals, 347 SourceLocation Loc, DeclarationName Entity) { 348 if (LValueRef) { 349 if (const RValueReferenceType *R = T->getAsRValueReferenceType()) { 350 // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a 351 // reference to a type T, and attempt to create the type "lvalue 352 // reference to cv TD" creates the type "lvalue reference to T". 353 // We use the qualifiers (restrict or none) of the original reference, 354 // not the new ones. This is consistent with GCC. 355 return Context.getLValueReferenceType(R->getPointeeType()). 356 getQualifiedType(T.getCVRQualifiers()); 357 } 358 } 359 if (T->isReferenceType()) { 360 // C++ [dcl.ref]p4: There shall be no references to references. 361 // 362 // According to C++ DR 106, references to references are only 363 // diagnosed when they are written directly (e.g., "int & &"), 364 // but not when they happen via a typedef: 365 // 366 // typedef int& intref; 367 // typedef intref& intref2; 368 // 369 // Parser::ParserDeclaratorInternal diagnoses the case where 370 // references are written directly; here, we handle the 371 // collapsing of references-to-references as described in C++ 372 // DR 106 and amended by C++ DR 540. 373 return T; 374 } 375 376 // C++ [dcl.ref]p1: 377 // A declarator that specifies the type “reference to cv void” 378 // is ill-formed. 379 if (T->isVoidType()) { 380 Diag(Loc, diag::err_reference_to_void); 381 return QualType(); 382 } 383 384 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 385 // object or incomplete types shall not be restrict-qualified." 386 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) { 387 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 388 << T; 389 Quals &= ~QualType::Restrict; 390 } 391 392 // C++ [dcl.ref]p1: 393 // [...] Cv-qualified references are ill-formed except when the 394 // cv-qualifiers are introduced through the use of a typedef 395 // (7.1.3) or of a template type argument (14.3), in which case 396 // the cv-qualifiers are ignored. 397 // 398 // We diagnose extraneous cv-qualifiers for the non-typedef, 399 // non-template type argument case within the parser. Here, we just 400 // ignore any extraneous cv-qualifiers. 401 Quals &= ~QualType::Const; 402 Quals &= ~QualType::Volatile; 403 404 // Handle restrict on references. 405 if (LValueRef) 406 return Context.getLValueReferenceType(T).getQualifiedType(Quals); 407 return Context.getRValueReferenceType(T).getQualifiedType(Quals); 408} 409 410/// \brief Build an array type. 411/// 412/// \param T The type of each element in the array. 413/// 414/// \param ASM C99 array size modifier (e.g., '*', 'static'). 415/// 416/// \param ArraySize Expression describing the size of the array. 417/// 418/// \param Quals The cvr-qualifiers to be applied to the array's 419/// element type. 420/// 421/// \param Loc The location of the entity whose type involves this 422/// array type or, if there is no such entity, the location of the 423/// type that will have array type. 424/// 425/// \param Entity The name of the entity that involves the array 426/// type, if known. 427/// 428/// \returns A suitable array type, if there are no errors. Otherwise, 429/// returns a NULL type. 430QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 431 Expr *ArraySize, unsigned Quals, 432 SourceLocation Loc, DeclarationName Entity) { 433 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 434 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 435 if (RequireCompleteType(Loc, T, 436 diag::err_illegal_decl_array_incomplete_type)) 437 return QualType(); 438 439 if (T->isFunctionType()) { 440 Diag(Loc, diag::err_illegal_decl_array_of_functions) 441 << getPrintableNameForEntity(Entity); 442 return QualType(); 443 } 444 445 // C++ 8.3.2p4: There shall be no ... arrays of references ... 446 if (T->isReferenceType()) { 447 Diag(Loc, diag::err_illegal_decl_array_of_references) 448 << getPrintableNameForEntity(Entity); 449 return QualType(); 450 } 451 452 if (const RecordType *EltTy = T->getAsRecordType()) { 453 // If the element type is a struct or union that contains a variadic 454 // array, accept it as a GNU extension: C99 6.7.2.1p2. 455 if (EltTy->getDecl()->hasFlexibleArrayMember()) 456 Diag(Loc, diag::ext_flexible_array_in_array) << T; 457 } else if (T->isObjCInterfaceType()) { 458 Diag(Loc, diag::warn_objc_array_of_interfaces) << T; 459 } 460 461 // C99 6.7.5.2p1: The size expression shall have integer type. 462 if (ArraySize && !ArraySize->isTypeDependent() && 463 !ArraySize->getType()->isIntegerType()) { 464 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 465 << ArraySize->getType() << ArraySize->getSourceRange(); 466 ArraySize->Destroy(Context); 467 return QualType(); 468 } 469 llvm::APSInt ConstVal(32); 470 if (!ArraySize) { 471 T = Context.getIncompleteArrayType(T, ASM, Quals); 472 } else if (ArraySize->isValueDependent()) { 473 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals); 474 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) || 475 (!T->isDependentType() && !T->isConstantSizeType())) { 476 // Per C99, a variable array is an array with either a non-constant 477 // size or an element type that has a non-constant-size 478 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals); 479 } else { 480 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 481 // have a value greater than zero. 482 if (ConstVal.isSigned()) { 483 if (ConstVal.isNegative()) { 484 Diag(ArraySize->getLocStart(), 485 diag::err_typecheck_negative_array_size) 486 << ArraySize->getSourceRange(); 487 return QualType(); 488 } else if (ConstVal == 0) { 489 // GCC accepts zero sized static arrays. 490 Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size) 491 << ArraySize->getSourceRange(); 492 } 493 } 494 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); 495 } 496 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 497 if (!getLangOptions().C99) { 498 if (ArraySize && !ArraySize->isTypeDependent() && 499 !ArraySize->isValueDependent() && 500 !ArraySize->isIntegerConstantExpr(Context)) 501 Diag(Loc, diag::ext_vla); 502 else if (ASM != ArrayType::Normal || Quals != 0) 503 Diag(Loc, diag::ext_c99_array_usage); 504 } 505 506 return T; 507} 508 509/// \brief Build a function type. 510/// 511/// This routine checks the function type according to C++ rules and 512/// under the assumption that the result type and parameter types have 513/// just been instantiated from a template. It therefore duplicates 514/// some of the behavior of GetTypeForDeclarator, but in a much 515/// simpler form that is only suitable for this narrow use case. 516/// 517/// \param T The return type of the function. 518/// 519/// \param ParamTypes The parameter types of the function. This array 520/// will be modified to account for adjustments to the types of the 521/// function parameters. 522/// 523/// \param NumParamTypes The number of parameter types in ParamTypes. 524/// 525/// \param Variadic Whether this is a variadic function type. 526/// 527/// \param Quals The cvr-qualifiers to be applied to the function type. 528/// 529/// \param Loc The location of the entity whose type involves this 530/// function type or, if there is no such entity, the location of the 531/// type that will have function type. 532/// 533/// \param Entity The name of the entity that involves the function 534/// type, if known. 535/// 536/// \returns A suitable function type, if there are no 537/// errors. Otherwise, returns a NULL type. 538QualType Sema::BuildFunctionType(QualType T, 539 QualType *ParamTypes, 540 unsigned NumParamTypes, 541 bool Variadic, unsigned Quals, 542 SourceLocation Loc, DeclarationName Entity) { 543 if (T->isArrayType() || T->isFunctionType()) { 544 Diag(Loc, diag::err_func_returning_array_function) << T; 545 return QualType(); 546 } 547 548 bool Invalid = false; 549 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) { 550 QualType ParamType = adjustParameterType(ParamTypes[Idx]); 551 if (ParamType->isVoidType()) { 552 Diag(Loc, diag::err_param_with_void_type); 553 Invalid = true; 554 } 555 556 ParamTypes[Idx] = ParamType; 557 } 558 559 if (Invalid) 560 return QualType(); 561 562 return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic, 563 Quals); 564} 565 566/// GetTypeForDeclarator - Convert the type for the specified 567/// declarator to Type instances. Skip the outermost Skip type 568/// objects. 569QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip) { 570 bool OmittedReturnType = false; 571 572 if (D.getContext() == Declarator::BlockLiteralContext 573 && Skip == 0 574 && !D.getDeclSpec().hasTypeSpecifier() 575 && (D.getNumTypeObjects() == 0 576 || (D.getNumTypeObjects() == 1 577 && D.getTypeObject(0).Kind == DeclaratorChunk::Function))) 578 OmittedReturnType = true; 579 580 // long long is a C99 feature. 581 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 582 D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong) 583 Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong); 584 585 // Determine the type of the declarator. Not all forms of declarator 586 // have a type. 587 QualType T; 588 switch (D.getKind()) { 589 case Declarator::DK_Abstract: 590 case Declarator::DK_Normal: 591 case Declarator::DK_Operator: { 592 const DeclSpec& DS = D.getDeclSpec(); 593 if (OmittedReturnType) 594 // We default to a dependent type initially. Can be modified by 595 // the first return statement. 596 T = Context.DependentTy; 597 else { 598 T = ConvertDeclSpecToType(DS); 599 if (T.isNull()) 600 return T; 601 } 602 break; 603 } 604 605 case Declarator::DK_Constructor: 606 case Declarator::DK_Destructor: 607 case Declarator::DK_Conversion: 608 // Constructors and destructors don't have return types. Use 609 // "void" instead. Conversion operators will check their return 610 // types separately. 611 T = Context.VoidTy; 612 break; 613 } 614 615 // The name we're declaring, if any. 616 DeclarationName Name; 617 if (D.getIdentifier()) 618 Name = D.getIdentifier(); 619 620 // Walk the DeclTypeInfo, building the recursive type as we go. 621 // DeclTypeInfos are ordered from the identifier out, which is 622 // opposite of what we want :). 623 for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) { 624 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip); 625 switch (DeclType.Kind) { 626 default: assert(0 && "Unknown decltype!"); 627 case DeclaratorChunk::BlockPointer: 628 if (DeclType.Cls.TypeQuals) 629 Diag(D.getIdentifierLoc(), diag::err_qualified_block_pointer_type); 630 if (!T.getTypePtr()->isFunctionType()) 631 Diag(D.getIdentifierLoc(), diag::err_nonfunction_block_type); 632 else 633 T = Context.getBlockPointerType(T); 634 break; 635 case DeclaratorChunk::Pointer: 636 T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name); 637 break; 638 case DeclaratorChunk::Reference: 639 T = BuildReferenceType(T, DeclType.Ref.LValueRef, 640 DeclType.Ref.HasRestrict ? QualType::Restrict : 0, 641 DeclType.Loc, Name); 642 break; 643 case DeclaratorChunk::Array: { 644 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 645 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 646 ArrayType::ArraySizeModifier ASM; 647 if (ATI.isStar) 648 ASM = ArrayType::Star; 649 else if (ATI.hasStatic) 650 ASM = ArrayType::Static; 651 else 652 ASM = ArrayType::Normal; 653 T = BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, DeclType.Loc, Name); 654 break; 655 } 656 case DeclaratorChunk::Function: { 657 // If the function declarator has a prototype (i.e. it is not () and 658 // does not have a K&R-style identifier list), then the arguments are part 659 // of the type, otherwise the argument list is (). 660 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 661 662 // C99 6.7.5.3p1: The return type may not be a function or array type. 663 if (T->isArrayType() || T->isFunctionType()) { 664 Diag(DeclType.Loc, diag::err_func_returning_array_function) << T; 665 T = Context.IntTy; 666 D.setInvalidType(true); 667 } 668 669 if (FTI.NumArgs == 0) { 670 if (getLangOptions().CPlusPlus) { 671 // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the 672 // function takes no arguments. 673 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic,FTI.TypeQuals); 674 } else if (FTI.isVariadic) { 675 // We allow a zero-parameter variadic function in C if the 676 // function is marked with the "overloadable" 677 // attribute. Scan for this attribute now. 678 bool Overloadable = false; 679 for (const AttributeList *Attrs = D.getAttributes(); 680 Attrs; Attrs = Attrs->getNext()) { 681 if (Attrs->getKind() == AttributeList::AT_overloadable) { 682 Overloadable = true; 683 break; 684 } 685 } 686 687 if (!Overloadable) 688 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); 689 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0); 690 } else { 691 // Simple void foo(), where the incoming T is the result type. 692 T = Context.getFunctionNoProtoType(T); 693 } 694 } else if (FTI.ArgInfo[0].Param == 0) { 695 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition. 696 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 697 } else { 698 // Otherwise, we have a function with an argument list that is 699 // potentially variadic. 700 llvm::SmallVector<QualType, 16> ArgTys; 701 702 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 703 ParmVarDecl *Param = (ParmVarDecl *)FTI.ArgInfo[i].Param; 704 QualType ArgTy = Param->getType(); 705 assert(!ArgTy.isNull() && "Couldn't parse type?"); 706 707 // Adjust the parameter type. 708 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?"); 709 710 // Look for 'void'. void is allowed only as a single argument to a 711 // function with no other parameters (C99 6.7.5.3p10). We record 712 // int(void) as a FunctionProtoType with an empty argument list. 713 if (ArgTy->isVoidType()) { 714 // If this is something like 'float(int, void)', reject it. 'void' 715 // is an incomplete type (C99 6.2.5p19) and function decls cannot 716 // have arguments of incomplete type. 717 if (FTI.NumArgs != 1 || FTI.isVariadic) { 718 Diag(DeclType.Loc, diag::err_void_only_param); 719 ArgTy = Context.IntTy; 720 Param->setType(ArgTy); 721 } else if (FTI.ArgInfo[i].Ident) { 722 // Reject, but continue to parse 'int(void abc)'. 723 Diag(FTI.ArgInfo[i].IdentLoc, 724 diag::err_param_with_void_type); 725 ArgTy = Context.IntTy; 726 Param->setType(ArgTy); 727 } else { 728 // Reject, but continue to parse 'float(const void)'. 729 if (ArgTy.getCVRQualifiers()) 730 Diag(DeclType.Loc, diag::err_void_param_qualified); 731 732 // Do not add 'void' to the ArgTys list. 733 break; 734 } 735 } else if (!FTI.hasPrototype) { 736 if (ArgTy->isPromotableIntegerType()) { 737 ArgTy = Context.IntTy; 738 } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) { 739 if (BTy->getKind() == BuiltinType::Float) 740 ArgTy = Context.DoubleTy; 741 } 742 } 743 744 ArgTys.push_back(ArgTy); 745 } 746 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(), 747 FTI.isVariadic, FTI.TypeQuals); 748 } 749 break; 750 } 751 case DeclaratorChunk::MemberPointer: 752 // The scope spec must refer to a class, or be dependent. 753 DeclContext *DC = computeDeclContext(DeclType.Mem.Scope()); 754 QualType ClsType; 755 // FIXME: Extend for dependent types when it's actually supported. 756 // See ActOnCXXNestedNameSpecifier. 757 if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(DC)) { 758 ClsType = Context.getTagDeclType(RD); 759 } else { 760 if (DC) { 761 Diag(DeclType.Mem.Scope().getBeginLoc(), 762 diag::err_illegal_decl_mempointer_in_nonclass) 763 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 764 << DeclType.Mem.Scope().getRange(); 765 } 766 D.setInvalidType(true); 767 ClsType = Context.IntTy; 768 } 769 770 // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member 771 // with reference type, or "cv void." 772 if (T->isReferenceType()) { 773 Diag(DeclType.Loc, diag::err_illegal_decl_pointer_to_reference) 774 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name"); 775 D.setInvalidType(true); 776 T = Context.IntTy; 777 } 778 if (T->isVoidType()) { 779 Diag(DeclType.Loc, diag::err_illegal_decl_mempointer_to_void) 780 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name"); 781 T = Context.IntTy; 782 } 783 784 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 785 // object or incomplete types shall not be restrict-qualified." 786 if ((DeclType.Mem.TypeQuals & QualType::Restrict) && 787 !T->isIncompleteOrObjectType()) { 788 Diag(DeclType.Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 789 << T; 790 DeclType.Mem.TypeQuals &= ~QualType::Restrict; 791 } 792 793 T = Context.getMemberPointerType(T, ClsType.getTypePtr()). 794 getQualifiedType(DeclType.Mem.TypeQuals); 795 796 break; 797 } 798 799 if (T.isNull()) { 800 D.setInvalidType(true); 801 T = Context.IntTy; 802 } 803 804 // See if there are any attributes on this declarator chunk. 805 if (const AttributeList *AL = DeclType.getAttrs()) 806 ProcessTypeAttributeList(T, AL); 807 } 808 809 if (getLangOptions().CPlusPlus && T->isFunctionType()) { 810 const FunctionProtoType *FnTy = T->getAsFunctionProtoType(); 811 assert(FnTy && "Why oh why is there not a FunctionProtoType here ?"); 812 813 // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type 814 // for a nonstatic member function, the function type to which a pointer 815 // to member refers, or the top-level function type of a function typedef 816 // declaration. 817 if (FnTy->getTypeQuals() != 0 && 818 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 819 ((D.getContext() != Declarator::MemberContext && 820 (!D.getCXXScopeSpec().isSet() || 821 !computeDeclContext(D.getCXXScopeSpec())->isRecord())) || 822 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) { 823 if (D.isFunctionDeclarator()) 824 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type); 825 else 826 Diag(D.getIdentifierLoc(), 827 diag::err_invalid_qualified_typedef_function_type_use); 828 829 // Strip the cv-quals from the type. 830 T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(), 831 FnTy->getNumArgs(), FnTy->isVariadic(), 0); 832 } 833 } 834 835 // If there were any type attributes applied to the decl itself (not the 836 // type, apply the type attribute to the type!) 837 if (const AttributeList *Attrs = D.getAttributes()) 838 ProcessTypeAttributeList(T, Attrs); 839 840 return T; 841} 842 843/// ObjCGetTypeForMethodDefinition - Builds the type for a method definition 844/// declarator 845QualType Sema::ObjCGetTypeForMethodDefinition(DeclTy *D) { 846 ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(static_cast<Decl *>(D)); 847 QualType T = MDecl->getResultType(); 848 llvm::SmallVector<QualType, 16> ArgTys; 849 850 // Add the first two invisible argument types for self and _cmd. 851 if (MDecl->isInstanceMethod()) { 852 QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface()); 853 selfTy = Context.getPointerType(selfTy); 854 ArgTys.push_back(selfTy); 855 } else 856 ArgTys.push_back(Context.getObjCIdType()); 857 ArgTys.push_back(Context.getObjCSelType()); 858 859 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(), 860 E = MDecl->param_end(); PI != E; ++PI) { 861 QualType ArgTy = (*PI)->getType(); 862 assert(!ArgTy.isNull() && "Couldn't parse type?"); 863 ArgTy = adjustParameterType(ArgTy); 864 ArgTys.push_back(ArgTy); 865 } 866 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(), 867 MDecl->isVariadic(), 0); 868 return T; 869} 870 871/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 872/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 873/// they point to and return true. If T1 and T2 aren't pointer types 874/// or pointer-to-member types, or if they are not similar at this 875/// level, returns false and leaves T1 and T2 unchanged. Top-level 876/// qualifiers on T1 and T2 are ignored. This function will typically 877/// be called in a loop that successively "unwraps" pointer and 878/// pointer-to-member types to compare them at each level. 879bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) { 880 const PointerType *T1PtrType = T1->getAsPointerType(), 881 *T2PtrType = T2->getAsPointerType(); 882 if (T1PtrType && T2PtrType) { 883 T1 = T1PtrType->getPointeeType(); 884 T2 = T2PtrType->getPointeeType(); 885 return true; 886 } 887 888 const MemberPointerType *T1MPType = T1->getAsMemberPointerType(), 889 *T2MPType = T2->getAsMemberPointerType(); 890 if (T1MPType && T2MPType && 891 Context.getCanonicalType(T1MPType->getClass()) == 892 Context.getCanonicalType(T2MPType->getClass())) { 893 T1 = T1MPType->getPointeeType(); 894 T2 = T2MPType->getPointeeType(); 895 return true; 896 } 897 return false; 898} 899 900Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 901 // C99 6.7.6: Type names have no identifier. This is already validated by 902 // the parser. 903 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 904 905 QualType T = GetTypeForDeclarator(D, S); 906 if (T.isNull()) 907 return true; 908 909 // Check that there are no default arguments (C++ only). 910 if (getLangOptions().CPlusPlus) 911 CheckExtraCXXDefaultArguments(D); 912 913 return T.getAsOpaquePtr(); 914} 915 916 917 918//===----------------------------------------------------------------------===// 919// Type Attribute Processing 920//===----------------------------------------------------------------------===// 921 922/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 923/// specified type. The attribute contains 1 argument, the id of the address 924/// space for the type. 925static void HandleAddressSpaceTypeAttribute(QualType &Type, 926 const AttributeList &Attr, Sema &S){ 927 // If this type is already address space qualified, reject it. 928 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers 929 // for two or more different address spaces." 930 if (Type.getAddressSpace()) { 931 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 932 return; 933 } 934 935 // Check the attribute arguments. 936 if (Attr.getNumArgs() != 1) { 937 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 938 return; 939 } 940 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 941 llvm::APSInt addrSpace(32); 942 if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 943 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) 944 << ASArgExpr->getSourceRange(); 945 return; 946 } 947 948 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 949 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 950} 951 952/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the 953/// specified type. The attribute contains 1 argument, weak or strong. 954static void HandleObjCGCTypeAttribute(QualType &Type, 955 const AttributeList &Attr, Sema &S) { 956 if (Type.getObjCGCAttr() != QualType::GCNone) { 957 S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc); 958 return; 959 } 960 961 // Check the attribute arguments. 962 if (!Attr.getParameterName()) { 963 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string) 964 << "objc_gc" << 1; 965 return; 966 } 967 QualType::GCAttrTypes GCAttr; 968 if (Attr.getNumArgs() != 0) { 969 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 970 return; 971 } 972 if (Attr.getParameterName()->isStr("weak")) 973 GCAttr = QualType::Weak; 974 else if (Attr.getParameterName()->isStr("strong")) 975 GCAttr = QualType::Strong; 976 else { 977 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 978 << "objc_gc" << Attr.getParameterName(); 979 return; 980 } 981 982 Type = S.Context.getObjCGCQualType(Type, GCAttr); 983} 984 985void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) { 986 // Scan through and apply attributes to this type where it makes sense. Some 987 // attributes (such as __address_space__, __vector_size__, etc) apply to the 988 // type, but others can be present in the type specifiers even though they 989 // apply to the decl. Here we apply type attributes and ignore the rest. 990 for (; AL; AL = AL->getNext()) { 991 // If this is an attribute we can handle, do so now, otherwise, add it to 992 // the LeftOverAttrs list for rechaining. 993 switch (AL->getKind()) { 994 default: break; 995 case AttributeList::AT_address_space: 996 HandleAddressSpaceTypeAttribute(Result, *AL, *this); 997 break; 998 case AttributeList::AT_objc_gc: 999 HandleObjCGCTypeAttribute(Result, *AL, *this); 1000 break; 1001 } 1002 } 1003} 1004 1005/// @brief Ensure that the type T is a complete type. 1006/// 1007/// This routine checks whether the type @p T is complete in any 1008/// context where a complete type is required. If @p T is a complete 1009/// type, returns false. If @p T is a class template specialization, 1010/// this routine then attempts to perform class template 1011/// instantiation. If instantiation fails, or if @p T is incomplete 1012/// and cannot be completed, issues the diagnostic @p diag (giving it 1013/// the type @p T) and returns true. 1014/// 1015/// @param Loc The location in the source that the incomplete type 1016/// diagnostic should refer to. 1017/// 1018/// @param T The type that this routine is examining for completeness. 1019/// 1020/// @param diag The diagnostic value (e.g., 1021/// @c diag::err_typecheck_decl_incomplete_type) that will be used 1022/// for the error message if @p T is incomplete. 1023/// 1024/// @param Range1 An optional range in the source code that will be a 1025/// part of the "incomplete type" error message. 1026/// 1027/// @param Range2 An optional range in the source code that will be a 1028/// part of the "incomplete type" error message. 1029/// 1030/// @param PrintType If non-NULL, the type that should be printed 1031/// instead of @p T. This parameter should be used when the type that 1032/// we're checking for incompleteness isn't the type that should be 1033/// displayed to the user, e.g., when T is a type and PrintType is a 1034/// pointer to T. 1035/// 1036/// @returns @c true if @p T is incomplete and a diagnostic was emitted, 1037/// @c false otherwise. 1038bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, unsigned diag, 1039 SourceRange Range1, SourceRange Range2, 1040 QualType PrintType) { 1041 // If we have a complete type, we're done. 1042 if (!T->isIncompleteType()) 1043 return false; 1044 1045 // If we have a class template specialization or a class member of a 1046 // class template specialization, try to instantiate it. 1047 if (const RecordType *Record = T->getAsRecordType()) { 1048 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 1049 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 1050 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1051 // Update the class template specialization's location to 1052 // refer to the point of instantiation. 1053 if (Loc.isValid()) 1054 ClassTemplateSpec->setLocation(Loc); 1055 return InstantiateClassTemplateSpecialization(ClassTemplateSpec, 1056 /*ExplicitInstantiation=*/false); 1057 } 1058 } else if (CXXRecordDecl *Rec 1059 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 1060 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) { 1061 // Find the class template specialization that surrounds this 1062 // member class. 1063 ClassTemplateSpecializationDecl *Spec = 0; 1064 for (DeclContext *Parent = Rec->getDeclContext(); 1065 Parent && !Spec; Parent = Parent->getParent()) 1066 Spec = dyn_cast<ClassTemplateSpecializationDecl>(Parent); 1067 assert(Spec && "Not a member of a class template specialization?"); 1068 return InstantiateClass(Loc, Rec, Pattern, 1069 Spec->getTemplateArgs(), 1070 Spec->getNumTemplateArgs()); 1071 } 1072 } 1073 } 1074 1075 if (PrintType.isNull()) 1076 PrintType = T; 1077 1078 // We have an incomplete type. Produce a diagnostic. 1079 Diag(Loc, diag) << PrintType << Range1 << Range2; 1080 1081 // If the type was a forward declaration of a class/struct/union 1082 // type, produce 1083 const TagType *Tag = 0; 1084 if (const RecordType *Record = T->getAsRecordType()) 1085 Tag = Record; 1086 else if (const EnumType *Enum = T->getAsEnumType()) 1087 Tag = Enum; 1088 1089 if (Tag && !Tag->getDecl()->isInvalidDecl()) 1090 Diag(Tag->getDecl()->getLocation(), 1091 Tag->isBeingDefined() ? diag::note_type_being_defined 1092 : diag::note_forward_declaration) 1093 << QualType(Tag, 0); 1094 1095 return true; 1096} 1097 1098/// \brief Retrieve a version of the type 'T' that is qualified by the 1099/// nested-name-specifier contained in SS. 1100QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) { 1101 if (!SS.isSet() || SS.isInvalid() || T.isNull()) 1102 return T; 1103 1104 NestedNameSpecifier *NNS 1105 = static_cast<NestedNameSpecifier *>(SS.getCurrentScopeRep()); 1106 return Context.getQualifiedNameType(NNS, T); 1107} 1108