SemaType.cpp revision 788b0fd67e1992f23555454efcdb16a19dfefac3
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/CXXInheritance.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/DeclTemplate.h" 19#include "clang/AST/TypeLoc.h" 20#include "clang/AST/TypeLocVisitor.h" 21#include "clang/AST/Expr.h" 22#include "clang/Basic/PartialDiagnostic.h" 23#include "clang/Parse/DeclSpec.h" 24#include "llvm/ADT/SmallPtrSet.h" 25#include "llvm/Support/ErrorHandling.h" 26using namespace clang; 27 28#include <iostream> 29 30/// \brief Perform adjustment on the parameter type of a function. 31/// 32/// This routine adjusts the given parameter type @p T to the actual 33/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8], 34/// C++ [dcl.fct]p3). The adjusted parameter type is returned. 35QualType Sema::adjustParameterType(QualType T) { 36 // C99 6.7.5.3p7: 37 // A declaration of a parameter as "array of type" shall be 38 // adjusted to "qualified pointer to type", where the type 39 // qualifiers (if any) are those specified within the [ and ] of 40 // the array type derivation. 41 if (T->isArrayType()) 42 return Context.getArrayDecayedType(T); 43 44 // C99 6.7.5.3p8: 45 // A declaration of a parameter as "function returning type" 46 // shall be adjusted to "pointer to function returning type", as 47 // in 6.3.2.1. 48 if (T->isFunctionType()) 49 return Context.getPointerType(T); 50 51 return T; 52} 53 54 55 56/// isOmittedBlockReturnType - Return true if this declarator is missing a 57/// return type because this is a omitted return type on a block literal. 58static bool isOmittedBlockReturnType(const Declarator &D) { 59 if (D.getContext() != Declarator::BlockLiteralContext || 60 D.getDeclSpec().hasTypeSpecifier()) 61 return false; 62 63 if (D.getNumTypeObjects() == 0) 64 return true; // ^{ ... } 65 66 if (D.getNumTypeObjects() == 1 && 67 D.getTypeObject(0).Kind == DeclaratorChunk::Function) 68 return true; // ^(int X, float Y) { ... } 69 70 return false; 71} 72 73typedef std::pair<const AttributeList*,QualType> DelayedAttribute; 74typedef llvm::SmallVectorImpl<DelayedAttribute> DelayedAttributeSet; 75 76static void ProcessTypeAttributeList(Sema &S, QualType &Type, 77 bool IsDeclSpec, 78 const AttributeList *Attrs, 79 DelayedAttributeSet &DelayedFnAttrs); 80static bool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr); 81 82static void ProcessDelayedFnAttrs(Sema &S, QualType &Type, 83 DelayedAttributeSet &Attrs) { 84 for (DelayedAttributeSet::iterator I = Attrs.begin(), 85 E = Attrs.end(); I != E; ++I) 86 if (ProcessFnAttr(S, Type, *I->first)) { 87 S.Diag(I->first->getLoc(), diag::warn_function_attribute_wrong_type) 88 << I->first->getName() << I->second; 89 // Avoid any further processing of this attribute. 90 I->first->setInvalid(); 91 } 92 Attrs.clear(); 93} 94 95static void DiagnoseDelayedFnAttrs(Sema &S, DelayedAttributeSet &Attrs) { 96 for (DelayedAttributeSet::iterator I = Attrs.begin(), 97 E = Attrs.end(); I != E; ++I) { 98 S.Diag(I->first->getLoc(), diag::warn_function_attribute_wrong_type) 99 << I->first->getName() << I->second; 100 // Avoid any further processing of this attribute. 101 I->first->setInvalid(); 102 } 103 Attrs.clear(); 104} 105 106/// \brief Convert the specified declspec to the appropriate type 107/// object. 108/// \param D the declarator containing the declaration specifier. 109/// \returns The type described by the declaration specifiers. This function 110/// never returns null. 111static QualType ConvertDeclSpecToType(Sema &TheSema, 112 Declarator &TheDeclarator, 113 DelayedAttributeSet &Delayed) { 114 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 115 // checking. 116 const DeclSpec &DS = TheDeclarator.getDeclSpec(); 117 SourceLocation DeclLoc = TheDeclarator.getIdentifierLoc(); 118 if (DeclLoc.isInvalid()) 119 DeclLoc = DS.getSourceRange().getBegin(); 120 121 ASTContext &Context = TheSema.Context; 122 123 QualType Result; 124 switch (DS.getTypeSpecType()) { 125 case DeclSpec::TST_void: 126 Result = Context.VoidTy; 127 break; 128 case DeclSpec::TST_char: 129 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 130 Result = Context.CharTy; 131 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 132 Result = Context.SignedCharTy; 133 else { 134 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 135 "Unknown TSS value"); 136 Result = Context.UnsignedCharTy; 137 } 138 break; 139 case DeclSpec::TST_wchar: 140 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 141 Result = Context.WCharTy; 142 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 143 TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 144 << DS.getSpecifierName(DS.getTypeSpecType()); 145 Result = Context.getSignedWCharType(); 146 } else { 147 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 148 "Unknown TSS value"); 149 TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 150 << DS.getSpecifierName(DS.getTypeSpecType()); 151 Result = Context.getUnsignedWCharType(); 152 } 153 break; 154 case DeclSpec::TST_char16: 155 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 156 "Unknown TSS value"); 157 Result = Context.Char16Ty; 158 break; 159 case DeclSpec::TST_char32: 160 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 161 "Unknown TSS value"); 162 Result = Context.Char32Ty; 163 break; 164 case DeclSpec::TST_unspecified: 165 // "<proto1,proto2>" is an objc qualified ID with a missing id. 166 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 167 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 168 (ObjCProtocolDecl**)PQ, 169 DS.getNumProtocolQualifiers()); 170 Result = Context.getObjCObjectPointerType(Result); 171 break; 172 } 173 174 // If this is a missing declspec in a block literal return context, then it 175 // is inferred from the return statements inside the block. 176 if (isOmittedBlockReturnType(TheDeclarator)) { 177 Result = Context.DependentTy; 178 break; 179 } 180 181 // Unspecified typespec defaults to int in C90. However, the C90 grammar 182 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 183 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 184 // Note that the one exception to this is function definitions, which are 185 // allowed to be completely missing a declspec. This is handled in the 186 // parser already though by it pretending to have seen an 'int' in this 187 // case. 188 if (TheSema.getLangOptions().ImplicitInt) { 189 // In C89 mode, we only warn if there is a completely missing declspec 190 // when one is not allowed. 191 if (DS.isEmpty()) { 192 TheSema.Diag(DeclLoc, diag::ext_missing_declspec) 193 << DS.getSourceRange() 194 << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int"); 195 } 196 } else if (!DS.hasTypeSpecifier()) { 197 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 198 // "At least one type specifier shall be given in the declaration 199 // specifiers in each declaration, and in the specifier-qualifier list in 200 // each struct declaration and type name." 201 // FIXME: Does Microsoft really have the implicit int extension in C++? 202 if (TheSema.getLangOptions().CPlusPlus && 203 !TheSema.getLangOptions().Microsoft) { 204 TheSema.Diag(DeclLoc, diag::err_missing_type_specifier) 205 << DS.getSourceRange(); 206 207 // When this occurs in C++ code, often something is very broken with the 208 // value being declared, poison it as invalid so we don't get chains of 209 // errors. 210 TheDeclarator.setInvalidType(true); 211 } else { 212 TheSema.Diag(DeclLoc, diag::ext_missing_type_specifier) 213 << DS.getSourceRange(); 214 } 215 } 216 217 // FALL THROUGH. 218 case DeclSpec::TST_int: { 219 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 220 switch (DS.getTypeSpecWidth()) { 221 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 222 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 223 case DeclSpec::TSW_long: Result = Context.LongTy; break; 224 case DeclSpec::TSW_longlong: 225 Result = Context.LongLongTy; 226 227 // long long is a C99 feature. 228 if (!TheSema.getLangOptions().C99 && 229 !TheSema.getLangOptions().CPlusPlus0x) 230 TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong); 231 break; 232 } 233 } else { 234 switch (DS.getTypeSpecWidth()) { 235 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 236 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 237 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 238 case DeclSpec::TSW_longlong: 239 Result = Context.UnsignedLongLongTy; 240 241 // long long is a C99 feature. 242 if (!TheSema.getLangOptions().C99 && 243 !TheSema.getLangOptions().CPlusPlus0x) 244 TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong); 245 break; 246 } 247 } 248 break; 249 } 250 case DeclSpec::TST_float: Result = Context.FloatTy; break; 251 case DeclSpec::TST_double: 252 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 253 Result = Context.LongDoubleTy; 254 else 255 Result = Context.DoubleTy; 256 break; 257 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 258 case DeclSpec::TST_decimal32: // _Decimal32 259 case DeclSpec::TST_decimal64: // _Decimal64 260 case DeclSpec::TST_decimal128: // _Decimal128 261 TheSema.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 262 Result = Context.IntTy; 263 TheDeclarator.setInvalidType(true); 264 break; 265 case DeclSpec::TST_class: 266 case DeclSpec::TST_enum: 267 case DeclSpec::TST_union: 268 case DeclSpec::TST_struct: { 269 TypeDecl *D 270 = dyn_cast_or_null<TypeDecl>(static_cast<Decl *>(DS.getTypeRep())); 271 if (!D) { 272 // This can happen in C++ with ambiguous lookups. 273 Result = Context.IntTy; 274 TheDeclarator.setInvalidType(true); 275 break; 276 } 277 278 // If the type is deprecated or unavailable, diagnose it. 279 TheSema.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeLoc()); 280 281 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 282 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!"); 283 284 // TypeQuals handled by caller. 285 Result = Context.getTypeDeclType(D); 286 287 // In C++, make an ElaboratedType. 288 if (TheSema.getLangOptions().CPlusPlus) { 289 ElaboratedTypeKeyword Keyword 290 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); 291 Result = TheSema.getElaboratedType(Keyword, DS.getTypeSpecScope(), 292 Result); 293 } 294 if (D->isInvalidDecl()) 295 TheDeclarator.setInvalidType(true); 296 break; 297 } 298 case DeclSpec::TST_typename: { 299 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 300 DS.getTypeSpecSign() == 0 && 301 "Can't handle qualifiers on typedef names yet!"); 302 Result = TheSema.GetTypeFromParser(DS.getTypeRep()); 303 304 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 305 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) { 306 // Silently drop any existing protocol qualifiers. 307 // TODO: determine whether that's the right thing to do. 308 if (ObjT->getNumProtocols()) 309 Result = ObjT->getBaseType(); 310 311 if (DS.getNumProtocolQualifiers()) 312 Result = Context.getObjCObjectType(Result, 313 (ObjCProtocolDecl**) PQ, 314 DS.getNumProtocolQualifiers()); 315 } else if (Result->isObjCIdType()) { 316 // id<protocol-list> 317 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 318 (ObjCProtocolDecl**) PQ, 319 DS.getNumProtocolQualifiers()); 320 Result = Context.getObjCObjectPointerType(Result); 321 } else if (Result->isObjCClassType()) { 322 // Class<protocol-list> 323 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 324 (ObjCProtocolDecl**) PQ, 325 DS.getNumProtocolQualifiers()); 326 Result = Context.getObjCObjectPointerType(Result); 327 } else { 328 TheSema.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers) 329 << DS.getSourceRange(); 330 TheDeclarator.setInvalidType(true); 331 } 332 } 333 334 // TypeQuals handled by caller. 335 break; 336 } 337 case DeclSpec::TST_typeofType: 338 // FIXME: Preserve type source info. 339 Result = TheSema.GetTypeFromParser(DS.getTypeRep()); 340 assert(!Result.isNull() && "Didn't get a type for typeof?"); 341 // TypeQuals handled by caller. 342 Result = Context.getTypeOfType(Result); 343 break; 344 case DeclSpec::TST_typeofExpr: { 345 Expr *E = static_cast<Expr *>(DS.getTypeRep()); 346 assert(E && "Didn't get an expression for typeof?"); 347 // TypeQuals handled by caller. 348 Result = TheSema.BuildTypeofExprType(E); 349 if (Result.isNull()) { 350 Result = Context.IntTy; 351 TheDeclarator.setInvalidType(true); 352 } 353 break; 354 } 355 case DeclSpec::TST_decltype: { 356 Expr *E = static_cast<Expr *>(DS.getTypeRep()); 357 assert(E && "Didn't get an expression for decltype?"); 358 // TypeQuals handled by caller. 359 Result = TheSema.BuildDecltypeType(E); 360 if (Result.isNull()) { 361 Result = Context.IntTy; 362 TheDeclarator.setInvalidType(true); 363 } 364 break; 365 } 366 case DeclSpec::TST_auto: { 367 // TypeQuals handled by caller. 368 Result = Context.UndeducedAutoTy; 369 break; 370 } 371 372 case DeclSpec::TST_error: 373 Result = Context.IntTy; 374 TheDeclarator.setInvalidType(true); 375 break; 376 } 377 378 // Handle complex types. 379 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 380 if (TheSema.getLangOptions().Freestanding) 381 TheSema.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 382 Result = Context.getComplexType(Result); 383 } else if (DS.isTypeAltiVecVector()) { 384 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); 385 assert(typeSize > 0 && "type size for vector must be greater than 0 bits"); 386 VectorType::AltiVecSpecific AltiVecSpec = VectorType::AltiVec; 387 if (DS.isTypeAltiVecPixel()) 388 AltiVecSpec = VectorType::Pixel; 389 else if (DS.isTypeAltiVecBool()) 390 AltiVecSpec = VectorType::Bool; 391 Result = Context.getVectorType(Result, 128/typeSize, AltiVecSpec); 392 } 393 394 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary && 395 "FIXME: imaginary types not supported yet!"); 396 397 // See if there are any attributes on the declspec that apply to the type (as 398 // opposed to the decl). 399 if (const AttributeList *AL = DS.getAttributes()) 400 ProcessTypeAttributeList(TheSema, Result, true, AL, Delayed); 401 402 // Apply const/volatile/restrict qualifiers to T. 403 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 404 405 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 406 // or incomplete types shall not be restrict-qualified." C++ also allows 407 // restrict-qualified references. 408 if (TypeQuals & DeclSpec::TQ_restrict) { 409 if (Result->isAnyPointerType() || Result->isReferenceType()) { 410 QualType EltTy; 411 if (Result->isObjCObjectPointerType()) 412 EltTy = Result; 413 else 414 EltTy = Result->isPointerType() ? 415 Result->getAs<PointerType>()->getPointeeType() : 416 Result->getAs<ReferenceType>()->getPointeeType(); 417 418 // If we have a pointer or reference, the pointee must have an object 419 // incomplete type. 420 if (!EltTy->isIncompleteOrObjectType()) { 421 TheSema.Diag(DS.getRestrictSpecLoc(), 422 diag::err_typecheck_invalid_restrict_invalid_pointee) 423 << EltTy << DS.getSourceRange(); 424 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier. 425 } 426 } else { 427 TheSema.Diag(DS.getRestrictSpecLoc(), 428 diag::err_typecheck_invalid_restrict_not_pointer) 429 << Result << DS.getSourceRange(); 430 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier. 431 } 432 } 433 434 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification 435 // of a function type includes any type qualifiers, the behavior is 436 // undefined." 437 if (Result->isFunctionType() && TypeQuals) { 438 // Get some location to point at, either the C or V location. 439 SourceLocation Loc; 440 if (TypeQuals & DeclSpec::TQ_const) 441 Loc = DS.getConstSpecLoc(); 442 else if (TypeQuals & DeclSpec::TQ_volatile) 443 Loc = DS.getVolatileSpecLoc(); 444 else { 445 assert((TypeQuals & DeclSpec::TQ_restrict) && 446 "Has CVR quals but not C, V, or R?"); 447 Loc = DS.getRestrictSpecLoc(); 448 } 449 TheSema.Diag(Loc, diag::warn_typecheck_function_qualifiers) 450 << Result << DS.getSourceRange(); 451 } 452 453 // C++ [dcl.ref]p1: 454 // Cv-qualified references are ill-formed except when the 455 // cv-qualifiers are introduced through the use of a typedef 456 // (7.1.3) or of a template type argument (14.3), in which 457 // case the cv-qualifiers are ignored. 458 // FIXME: Shouldn't we be checking SCS_typedef here? 459 if (DS.getTypeSpecType() == DeclSpec::TST_typename && 460 TypeQuals && Result->isReferenceType()) { 461 TypeQuals &= ~DeclSpec::TQ_const; 462 TypeQuals &= ~DeclSpec::TQ_volatile; 463 } 464 465 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals); 466 Result = Context.getQualifiedType(Result, Quals); 467 } 468 469 return Result; 470} 471 472static std::string getPrintableNameForEntity(DeclarationName Entity) { 473 if (Entity) 474 return Entity.getAsString(); 475 476 return "type name"; 477} 478 479QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 480 Qualifiers Qs) { 481 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 482 // object or incomplete types shall not be restrict-qualified." 483 if (Qs.hasRestrict()) { 484 unsigned DiagID = 0; 485 QualType ProblemTy; 486 487 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr(); 488 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) { 489 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) { 490 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 491 ProblemTy = T->getAs<ReferenceType>()->getPointeeType(); 492 } 493 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) { 494 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) { 495 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 496 ProblemTy = T->getAs<PointerType>()->getPointeeType(); 497 } 498 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) { 499 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) { 500 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 501 ProblemTy = T->getAs<PointerType>()->getPointeeType(); 502 } 503 } else if (!Ty->isDependentType()) { 504 // FIXME: this deserves a proper diagnostic 505 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 506 ProblemTy = T; 507 } 508 509 if (DiagID) { 510 Diag(Loc, DiagID) << ProblemTy; 511 Qs.removeRestrict(); 512 } 513 } 514 515 return Context.getQualifiedType(T, Qs); 516} 517 518/// \brief Build a pointer type. 519/// 520/// \param T The type to which we'll be building a pointer. 521/// 522/// \param Loc The location of the entity whose type involves this 523/// pointer type or, if there is no such entity, the location of the 524/// type that will have pointer type. 525/// 526/// \param Entity The name of the entity that involves the pointer 527/// type, if known. 528/// 529/// \returns A suitable pointer type, if there are no 530/// errors. Otherwise, returns a NULL type. 531QualType Sema::BuildPointerType(QualType T, 532 SourceLocation Loc, DeclarationName Entity) { 533 if (T->isReferenceType()) { 534 // C++ 8.3.2p4: There shall be no ... pointers to references ... 535 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 536 << getPrintableNameForEntity(Entity) << T; 537 return QualType(); 538 } 539 540 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType"); 541 542 // Build the pointer type. 543 return Context.getPointerType(T); 544} 545 546/// \brief Build a reference type. 547/// 548/// \param T The type to which we'll be building a reference. 549/// 550/// \param Loc The location of the entity whose type involves this 551/// reference type or, if there is no such entity, the location of the 552/// type that will have reference type. 553/// 554/// \param Entity The name of the entity that involves the reference 555/// type, if known. 556/// 557/// \returns A suitable reference type, if there are no 558/// errors. Otherwise, returns a NULL type. 559QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, 560 SourceLocation Loc, 561 DeclarationName Entity) { 562 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); 563 564 // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a 565 // reference to a type T, and attempt to create the type "lvalue 566 // reference to cv TD" creates the type "lvalue reference to T". 567 // We use the qualifiers (restrict or none) of the original reference, 568 // not the new ones. This is consistent with GCC. 569 570 // C++ [dcl.ref]p4: There shall be no references to references. 571 // 572 // According to C++ DR 106, references to references are only 573 // diagnosed when they are written directly (e.g., "int & &"), 574 // but not when they happen via a typedef: 575 // 576 // typedef int& intref; 577 // typedef intref& intref2; 578 // 579 // Parser::ParseDeclaratorInternal diagnoses the case where 580 // references are written directly; here, we handle the 581 // collapsing of references-to-references as described in C++ 582 // DR 106 and amended by C++ DR 540. 583 584 // C++ [dcl.ref]p1: 585 // A declarator that specifies the type "reference to cv void" 586 // is ill-formed. 587 if (T->isVoidType()) { 588 Diag(Loc, diag::err_reference_to_void); 589 return QualType(); 590 } 591 592 // Handle restrict on references. 593 if (LValueRef) 594 return Context.getLValueReferenceType(T, SpelledAsLValue); 595 return Context.getRValueReferenceType(T); 596} 597 598/// \brief Build an array type. 599/// 600/// \param T The type of each element in the array. 601/// 602/// \param ASM C99 array size modifier (e.g., '*', 'static'). 603/// 604/// \param ArraySize Expression describing the size of the array. 605/// 606/// \param Loc The location of the entity whose type involves this 607/// array type or, if there is no such entity, the location of the 608/// type that will have array type. 609/// 610/// \param Entity The name of the entity that involves the array 611/// type, if known. 612/// 613/// \returns A suitable array type, if there are no errors. Otherwise, 614/// returns a NULL type. 615QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 616 Expr *ArraySize, unsigned Quals, 617 SourceRange Brackets, DeclarationName Entity) { 618 619 SourceLocation Loc = Brackets.getBegin(); 620 if (getLangOptions().CPlusPlus) { 621 // C++ [dcl.array]p1: 622 // T is called the array element type; this type shall not be a reference 623 // type, the (possibly cv-qualified) type void, a function type or an 624 // abstract class type. 625 // 626 // Note: function types are handled in the common path with C. 627 if (T->isReferenceType()) { 628 Diag(Loc, diag::err_illegal_decl_array_of_references) 629 << getPrintableNameForEntity(Entity) << T; 630 return QualType(); 631 } 632 633 if (T->isVoidType()) { 634 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; 635 return QualType(); 636 } 637 638 if (RequireNonAbstractType(Brackets.getBegin(), T, 639 diag::err_array_of_abstract_type)) 640 return QualType(); 641 642 } else { 643 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 644 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 645 if (RequireCompleteType(Loc, T, 646 diag::err_illegal_decl_array_incomplete_type)) 647 return QualType(); 648 } 649 650 if (T->isFunctionType()) { 651 Diag(Loc, diag::err_illegal_decl_array_of_functions) 652 << getPrintableNameForEntity(Entity) << T; 653 return QualType(); 654 } 655 656 if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) { 657 Diag(Loc, diag::err_illegal_decl_array_of_auto) 658 << getPrintableNameForEntity(Entity); 659 return QualType(); 660 } 661 662 if (const RecordType *EltTy = T->getAs<RecordType>()) { 663 // If the element type is a struct or union that contains a variadic 664 // array, accept it as a GNU extension: C99 6.7.2.1p2. 665 if (EltTy->getDecl()->hasFlexibleArrayMember()) 666 Diag(Loc, diag::ext_flexible_array_in_array) << T; 667 } else if (T->isObjCObjectType()) { 668 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 669 return QualType(); 670 } 671 672 // C99 6.7.5.2p1: The size expression shall have integer type. 673 if (ArraySize && !ArraySize->isTypeDependent() && 674 !ArraySize->getType()->isIntegerType()) { 675 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 676 << ArraySize->getType() << ArraySize->getSourceRange(); 677 ArraySize->Destroy(Context); 678 return QualType(); 679 } 680 llvm::APSInt ConstVal(32); 681 if (!ArraySize) { 682 if (ASM == ArrayType::Star) 683 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets); 684 else 685 T = Context.getIncompleteArrayType(T, ASM, Quals); 686 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { 687 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 688 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) || 689 (!T->isDependentType() && !T->isIncompleteType() && 690 !T->isConstantSizeType())) { 691 // Per C99, a variable array is an array with either a non-constant 692 // size or an element type that has a non-constant-size 693 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 694 } else { 695 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 696 // have a value greater than zero. 697 if (ConstVal.isSigned() && ConstVal.isNegative()) { 698 Diag(ArraySize->getLocStart(), 699 diag::err_typecheck_negative_array_size) 700 << ArraySize->getSourceRange(); 701 return QualType(); 702 } 703 if (ConstVal == 0) { 704 // GCC accepts zero sized static arrays. We allow them when 705 // we're not in a SFINAE context. 706 Diag(ArraySize->getLocStart(), 707 isSFINAEContext()? diag::err_typecheck_zero_array_size 708 : diag::ext_typecheck_zero_array_size) 709 << ArraySize->getSourceRange(); 710 } 711 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); 712 } 713 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 714 if (!getLangOptions().C99) { 715 if (T->isVariableArrayType()) { 716 // Prohibit the use of non-POD types in VLAs. 717 if (!T->isDependentType() && 718 !Context.getBaseElementType(T)->isPODType()) { 719 Diag(Loc, diag::err_vla_non_pod) 720 << Context.getBaseElementType(T); 721 return QualType(); 722 } 723 // Prohibit the use of VLAs during template argument deduction. 724 else if (isSFINAEContext()) { 725 Diag(Loc, diag::err_vla_in_sfinae); 726 return QualType(); 727 } 728 // Just extwarn about VLAs. 729 else 730 Diag(Loc, diag::ext_vla); 731 } else if (ASM != ArrayType::Normal || Quals != 0) 732 Diag(Loc, 733 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx 734 : diag::ext_c99_array_usage); 735 } 736 737 return T; 738} 739 740/// \brief Build an ext-vector type. 741/// 742/// Run the required checks for the extended vector type. 743QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize, 744 SourceLocation AttrLoc) { 745 746 Expr *Arg = (Expr *)ArraySize.get(); 747 748 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 749 // in conjunction with complex types (pointers, arrays, functions, etc.). 750 if (!T->isDependentType() && 751 !T->isIntegerType() && !T->isRealFloatingType()) { 752 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 753 return QualType(); 754 } 755 756 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 757 llvm::APSInt vecSize(32); 758 if (!Arg->isIntegerConstantExpr(vecSize, Context)) { 759 Diag(AttrLoc, diag::err_attribute_argument_not_int) 760 << "ext_vector_type" << Arg->getSourceRange(); 761 return QualType(); 762 } 763 764 // unlike gcc's vector_size attribute, the size is specified as the 765 // number of elements, not the number of bytes. 766 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 767 768 if (vectorSize == 0) { 769 Diag(AttrLoc, diag::err_attribute_zero_size) 770 << Arg->getSourceRange(); 771 return QualType(); 772 } 773 774 if (!T->isDependentType()) 775 return Context.getExtVectorType(T, vectorSize); 776 } 777 778 return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(), 779 AttrLoc); 780} 781 782/// \brief Build a function type. 783/// 784/// This routine checks the function type according to C++ rules and 785/// under the assumption that the result type and parameter types have 786/// just been instantiated from a template. It therefore duplicates 787/// some of the behavior of GetTypeForDeclarator, but in a much 788/// simpler form that is only suitable for this narrow use case. 789/// 790/// \param T The return type of the function. 791/// 792/// \param ParamTypes The parameter types of the function. This array 793/// will be modified to account for adjustments to the types of the 794/// function parameters. 795/// 796/// \param NumParamTypes The number of parameter types in ParamTypes. 797/// 798/// \param Variadic Whether this is a variadic function type. 799/// 800/// \param Quals The cvr-qualifiers to be applied to the function type. 801/// 802/// \param Loc The location of the entity whose type involves this 803/// function type or, if there is no such entity, the location of the 804/// type that will have function type. 805/// 806/// \param Entity The name of the entity that involves the function 807/// type, if known. 808/// 809/// \returns A suitable function type, if there are no 810/// errors. Otherwise, returns a NULL type. 811QualType Sema::BuildFunctionType(QualType T, 812 QualType *ParamTypes, 813 unsigned NumParamTypes, 814 bool Variadic, unsigned Quals, 815 SourceLocation Loc, DeclarationName Entity) { 816 if (T->isArrayType() || T->isFunctionType()) { 817 Diag(Loc, diag::err_func_returning_array_function) 818 << T->isFunctionType() << T; 819 return QualType(); 820 } 821 822 bool Invalid = false; 823 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) { 824 QualType ParamType = adjustParameterType(ParamTypes[Idx]); 825 if (ParamType->isVoidType()) { 826 Diag(Loc, diag::err_param_with_void_type); 827 Invalid = true; 828 } 829 830 ParamTypes[Idx] = ParamType; 831 } 832 833 if (Invalid) 834 return QualType(); 835 836 return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic, 837 Quals, false, false, 0, 0, 838 FunctionType::ExtInfo()); 839} 840 841/// \brief Build a member pointer type \c T Class::*. 842/// 843/// \param T the type to which the member pointer refers. 844/// \param Class the class type into which the member pointer points. 845/// \param CVR Qualifiers applied to the member pointer type 846/// \param Loc the location where this type begins 847/// \param Entity the name of the entity that will have this member pointer type 848/// 849/// \returns a member pointer type, if successful, or a NULL type if there was 850/// an error. 851QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 852 SourceLocation Loc, 853 DeclarationName Entity) { 854 // Verify that we're not building a pointer to pointer to function with 855 // exception specification. 856 if (CheckDistantExceptionSpec(T)) { 857 Diag(Loc, diag::err_distant_exception_spec); 858 859 // FIXME: If we're doing this as part of template instantiation, 860 // we should return immediately. 861 862 // Build the type anyway, but use the canonical type so that the 863 // exception specifiers are stripped off. 864 T = Context.getCanonicalType(T); 865 } 866 867 // C++ 8.3.3p3: A pointer to member shall not point to ... a member 868 // with reference type, or "cv void." 869 if (T->isReferenceType()) { 870 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 871 << (Entity? Entity.getAsString() : "type name") << T; 872 return QualType(); 873 } 874 875 if (T->isVoidType()) { 876 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 877 << (Entity? Entity.getAsString() : "type name"); 878 return QualType(); 879 } 880 881 if (!Class->isDependentType() && !Class->isRecordType()) { 882 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 883 return QualType(); 884 } 885 886 return Context.getMemberPointerType(T, Class.getTypePtr()); 887} 888 889/// \brief Build a block pointer type. 890/// 891/// \param T The type to which we'll be building a block pointer. 892/// 893/// \param CVR The cvr-qualifiers to be applied to the block pointer type. 894/// 895/// \param Loc The location of the entity whose type involves this 896/// block pointer type or, if there is no such entity, the location of the 897/// type that will have block pointer type. 898/// 899/// \param Entity The name of the entity that involves the block pointer 900/// type, if known. 901/// 902/// \returns A suitable block pointer type, if there are no 903/// errors. Otherwise, returns a NULL type. 904QualType Sema::BuildBlockPointerType(QualType T, 905 SourceLocation Loc, 906 DeclarationName Entity) { 907 if (!T->isFunctionType()) { 908 Diag(Loc, diag::err_nonfunction_block_type); 909 return QualType(); 910 } 911 912 return Context.getBlockPointerType(T); 913} 914 915QualType Sema::GetTypeFromParser(TypeTy *Ty, TypeSourceInfo **TInfo) { 916 QualType QT = QualType::getFromOpaquePtr(Ty); 917 if (QT.isNull()) { 918 if (TInfo) *TInfo = 0; 919 return QualType(); 920 } 921 922 TypeSourceInfo *DI = 0; 923 if (LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 924 QT = LIT->getType(); 925 DI = LIT->getTypeSourceInfo(); 926 } 927 928 if (TInfo) *TInfo = DI; 929 return QT; 930} 931 932/// GetTypeForDeclarator - Convert the type for the specified 933/// declarator to Type instances. 934/// 935/// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq 936/// owns the declaration of a type (e.g., the definition of a struct 937/// type), then *OwnedDecl will receive the owned declaration. 938/// 939/// The result of this call will never be null, but the associated 940/// type may be a null type if there's an unrecoverable error. 941TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S, 942 TagDecl **OwnedDecl) { 943 // Determine the type of the declarator. Not all forms of declarator 944 // have a type. 945 QualType T; 946 TypeSourceInfo *ReturnTypeInfo = 0; 947 948 llvm::SmallVector<DelayedAttribute,4> FnAttrsFromDeclSpec; 949 950 switch (D.getName().getKind()) { 951 case UnqualifiedId::IK_Identifier: 952 case UnqualifiedId::IK_OperatorFunctionId: 953 case UnqualifiedId::IK_LiteralOperatorId: 954 case UnqualifiedId::IK_TemplateId: 955 T = ConvertDeclSpecToType(*this, D, FnAttrsFromDeclSpec); 956 957 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 958 TagDecl* Owned = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep()); 959 // Owned is embedded if it was defined here, or if it is the 960 // very first (i.e., canonical) declaration of this tag type. 961 Owned->setEmbeddedInDeclarator(Owned->isDefinition() || 962 Owned->isCanonicalDecl()); 963 if (OwnedDecl) *OwnedDecl = Owned; 964 } 965 break; 966 967 case UnqualifiedId::IK_ConstructorName: 968 case UnqualifiedId::IK_ConstructorTemplateId: 969 case UnqualifiedId::IK_DestructorName: 970 // Constructors and destructors don't have return types. Use 971 // "void" instead. 972 T = Context.VoidTy; 973 break; 974 975 case UnqualifiedId::IK_ConversionFunctionId: 976 // The result type of a conversion function is the type that it 977 // converts to. 978 T = GetTypeFromParser(D.getName().ConversionFunctionId, 979 &ReturnTypeInfo); 980 break; 981 } 982 983 if (T.isNull()) 984 return Context.getNullTypeSourceInfo(); 985 986 if (T == Context.UndeducedAutoTy) { 987 int Error = -1; 988 989 switch (D.getContext()) { 990 case Declarator::KNRTypeListContext: 991 assert(0 && "K&R type lists aren't allowed in C++"); 992 break; 993 case Declarator::PrototypeContext: 994 Error = 0; // Function prototype 995 break; 996 case Declarator::MemberContext: 997 switch (cast<TagDecl>(CurContext)->getTagKind()) { 998 case TTK_Enum: assert(0 && "unhandled tag kind"); break; 999 case TTK_Struct: Error = 1; /* Struct member */ break; 1000 case TTK_Union: Error = 2; /* Union member */ break; 1001 case TTK_Class: Error = 3; /* Class member */ break; 1002 } 1003 break; 1004 case Declarator::CXXCatchContext: 1005 Error = 4; // Exception declaration 1006 break; 1007 case Declarator::TemplateParamContext: 1008 Error = 5; // Template parameter 1009 break; 1010 case Declarator::BlockLiteralContext: 1011 Error = 6; // Block literal 1012 break; 1013 case Declarator::FileContext: 1014 case Declarator::BlockContext: 1015 case Declarator::ForContext: 1016 case Declarator::ConditionContext: 1017 case Declarator::TypeNameContext: 1018 break; 1019 } 1020 1021 if (Error != -1) { 1022 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed) 1023 << Error; 1024 T = Context.IntTy; 1025 D.setInvalidType(true); 1026 } 1027 } 1028 1029 // The name we're declaring, if any. 1030 DeclarationName Name; 1031 if (D.getIdentifier()) 1032 Name = D.getIdentifier(); 1033 1034 llvm::SmallVector<DelayedAttribute,4> FnAttrsFromPreviousChunk; 1035 1036 // Walk the DeclTypeInfo, building the recursive type as we go. 1037 // DeclTypeInfos are ordered from the identifier out, which is 1038 // opposite of what we want :). 1039 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 1040 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1); 1041 switch (DeclType.Kind) { 1042 default: assert(0 && "Unknown decltype!"); 1043 case DeclaratorChunk::BlockPointer: 1044 // If blocks are disabled, emit an error. 1045 if (!LangOpts.Blocks) 1046 Diag(DeclType.Loc, diag::err_blocks_disable); 1047 1048 T = BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 1049 if (DeclType.Cls.TypeQuals) 1050 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 1051 break; 1052 case DeclaratorChunk::Pointer: 1053 // Verify that we're not building a pointer to pointer to function with 1054 // exception specification. 1055 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1056 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1057 D.setInvalidType(true); 1058 // Build the type anyway. 1059 } 1060 if (getLangOptions().ObjC1 && T->getAs<ObjCObjectType>()) { 1061 T = Context.getObjCObjectPointerType(T); 1062 if (DeclType.Ptr.TypeQuals) 1063 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 1064 break; 1065 } 1066 T = BuildPointerType(T, DeclType.Loc, Name); 1067 if (DeclType.Ptr.TypeQuals) 1068 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 1069 break; 1070 case DeclaratorChunk::Reference: { 1071 // Verify that we're not building a reference 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 T = BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 1079 1080 Qualifiers Quals; 1081 if (DeclType.Ref.HasRestrict) 1082 T = BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 1083 break; 1084 } 1085 case DeclaratorChunk::Array: { 1086 // Verify that we're not building an array of pointers to function with 1087 // exception specification. 1088 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1089 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1090 D.setInvalidType(true); 1091 // Build the type anyway. 1092 } 1093 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 1094 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 1095 ArrayType::ArraySizeModifier ASM; 1096 if (ATI.isStar) 1097 ASM = ArrayType::Star; 1098 else if (ATI.hasStatic) 1099 ASM = ArrayType::Static; 1100 else 1101 ASM = ArrayType::Normal; 1102 if (ASM == ArrayType::Star && 1103 D.getContext() != Declarator::PrototypeContext) { 1104 // FIXME: This check isn't quite right: it allows star in prototypes 1105 // for function definitions, and disallows some edge cases detailed 1106 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 1107 Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 1108 ASM = ArrayType::Normal; 1109 D.setInvalidType(true); 1110 } 1111 T = BuildArrayType(T, ASM, ArraySize, 1112 Qualifiers::fromCVRMask(ATI.TypeQuals), 1113 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 1114 break; 1115 } 1116 case DeclaratorChunk::Function: { 1117 // If the function declarator has a prototype (i.e. it is not () and 1118 // does not have a K&R-style identifier list), then the arguments are part 1119 // of the type, otherwise the argument list is (). 1120 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 1121 1122 // C99 6.7.5.3p1: The return type may not be a function or array type. 1123 // For conversion functions, we'll diagnose this particular error later. 1124 if ((T->isArrayType() || T->isFunctionType()) && 1125 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 1126 Diag(DeclType.Loc, diag::err_func_returning_array_function) 1127 << T->isFunctionType() << T; 1128 T = Context.IntTy; 1129 D.setInvalidType(true); 1130 } 1131 1132 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) { 1133 // C++ [dcl.fct]p6: 1134 // Types shall not be defined in return or parameter types. 1135 TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep()); 1136 if (Tag->isDefinition()) 1137 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 1138 << Context.getTypeDeclType(Tag); 1139 } 1140 1141 // Exception specs are not allowed in typedefs. Complain, but add it 1142 // anyway. 1143 if (FTI.hasExceptionSpec && 1144 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 1145 Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef); 1146 1147 if (!FTI.NumArgs && !FTI.isVariadic && !getLangOptions().CPlusPlus) { 1148 // Simple void foo(), where the incoming T is the result type. 1149 T = Context.getFunctionNoProtoType(T); 1150 } else { 1151 // We allow a zero-parameter variadic function in C if the 1152 // function is marked with the "overloadable" attribute. Scan 1153 // for this attribute now. 1154 if (!FTI.NumArgs && FTI.isVariadic && !getLangOptions().CPlusPlus) { 1155 bool Overloadable = false; 1156 for (const AttributeList *Attrs = D.getAttributes(); 1157 Attrs; Attrs = Attrs->getNext()) { 1158 if (Attrs->getKind() == AttributeList::AT_overloadable) { 1159 Overloadable = true; 1160 break; 1161 } 1162 } 1163 1164 if (!Overloadable) 1165 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); 1166 } 1167 1168 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) { 1169 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 1170 // definition. 1171 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 1172 D.setInvalidType(true); 1173 break; 1174 } 1175 1176 // Otherwise, we have a function with an argument list that is 1177 // potentially variadic. 1178 llvm::SmallVector<QualType, 16> ArgTys; 1179 ArgTys.reserve(FTI.NumArgs); 1180 1181 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 1182 ParmVarDecl *Param = 1183 cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>()); 1184 QualType ArgTy = Param->getType(); 1185 assert(!ArgTy.isNull() && "Couldn't parse type?"); 1186 1187 // Adjust the parameter type. 1188 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?"); 1189 1190 // Look for 'void'. void is allowed only as a single argument to a 1191 // function with no other parameters (C99 6.7.5.3p10). We record 1192 // int(void) as a FunctionProtoType with an empty argument list. 1193 if (ArgTy->isVoidType()) { 1194 // If this is something like 'float(int, void)', reject it. 'void' 1195 // is an incomplete type (C99 6.2.5p19) and function decls cannot 1196 // have arguments of incomplete type. 1197 if (FTI.NumArgs != 1 || FTI.isVariadic) { 1198 Diag(DeclType.Loc, diag::err_void_only_param); 1199 ArgTy = Context.IntTy; 1200 Param->setType(ArgTy); 1201 } else if (FTI.ArgInfo[i].Ident) { 1202 // Reject, but continue to parse 'int(void abc)'. 1203 Diag(FTI.ArgInfo[i].IdentLoc, 1204 diag::err_param_with_void_type); 1205 ArgTy = Context.IntTy; 1206 Param->setType(ArgTy); 1207 } else { 1208 // Reject, but continue to parse 'float(const void)'. 1209 if (ArgTy.hasQualifiers()) 1210 Diag(DeclType.Loc, diag::err_void_param_qualified); 1211 1212 // Do not add 'void' to the ArgTys list. 1213 break; 1214 } 1215 } else if (!FTI.hasPrototype) { 1216 if (ArgTy->isPromotableIntegerType()) { 1217 ArgTy = Context.getPromotedIntegerType(ArgTy); 1218 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) { 1219 if (BTy->getKind() == BuiltinType::Float) 1220 ArgTy = Context.DoubleTy; 1221 } 1222 } 1223 1224 ArgTys.push_back(ArgTy); 1225 } 1226 1227 llvm::SmallVector<QualType, 4> Exceptions; 1228 Exceptions.reserve(FTI.NumExceptions); 1229 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) { 1230 // FIXME: Preserve type source info. 1231 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty); 1232 // Check that the type is valid for an exception spec, and drop it if 1233 // not. 1234 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range)) 1235 Exceptions.push_back(ET); 1236 } 1237 1238 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), 1239 FTI.isVariadic, FTI.TypeQuals, 1240 FTI.hasExceptionSpec, 1241 FTI.hasAnyExceptionSpec, 1242 Exceptions.size(), Exceptions.data(), 1243 FunctionType::ExtInfo()); 1244 } 1245 1246 // For GCC compatibility, we allow attributes that apply only to 1247 // function types to be placed on a function's return type 1248 // instead (as long as that type doesn't happen to be function 1249 // or function-pointer itself). 1250 ProcessDelayedFnAttrs(*this, T, FnAttrsFromPreviousChunk); 1251 1252 break; 1253 } 1254 case DeclaratorChunk::MemberPointer: 1255 // The scope spec must refer to a class, or be dependent. 1256 QualType ClsType; 1257 if (DeclType.Mem.Scope().isInvalid()) { 1258 // Avoid emitting extra errors if we already errored on the scope. 1259 D.setInvalidType(true); 1260 } else if (isDependentScopeSpecifier(DeclType.Mem.Scope()) 1261 || dyn_cast_or_null<CXXRecordDecl>( 1262 computeDeclContext(DeclType.Mem.Scope()))) { 1263 NestedNameSpecifier *NNS 1264 = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep(); 1265 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 1266 switch (NNS->getKind()) { 1267 case NestedNameSpecifier::Identifier: 1268 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 1269 NNS->getAsIdentifier()); 1270 break; 1271 1272 case NestedNameSpecifier::Namespace: 1273 case NestedNameSpecifier::Global: 1274 llvm_unreachable("Nested-name-specifier must name a type"); 1275 break; 1276 1277 case NestedNameSpecifier::TypeSpec: 1278 case NestedNameSpecifier::TypeSpecWithTemplate: 1279 ClsType = QualType(NNS->getAsType(), 0); 1280 if (NNSPrefix) 1281 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 1282 break; 1283 } 1284 } else { 1285 Diag(DeclType.Mem.Scope().getBeginLoc(), 1286 diag::err_illegal_decl_mempointer_in_nonclass) 1287 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 1288 << DeclType.Mem.Scope().getRange(); 1289 D.setInvalidType(true); 1290 } 1291 1292 if (!ClsType.isNull()) 1293 T = BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier()); 1294 if (T.isNull()) { 1295 T = Context.IntTy; 1296 D.setInvalidType(true); 1297 } else if (DeclType.Mem.TypeQuals) { 1298 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 1299 } 1300 break; 1301 } 1302 1303 if (T.isNull()) { 1304 D.setInvalidType(true); 1305 T = Context.IntTy; 1306 } 1307 1308 DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk); 1309 1310 // See if there are any attributes on this declarator chunk. 1311 if (const AttributeList *AL = DeclType.getAttrs()) 1312 ProcessTypeAttributeList(*this, T, false, AL, FnAttrsFromPreviousChunk); 1313 } 1314 1315 if (getLangOptions().CPlusPlus && T->isFunctionType()) { 1316 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 1317 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 1318 1319 // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type 1320 // for a nonstatic member function, the function type to which a pointer 1321 // to member refers, or the top-level function type of a function typedef 1322 // declaration. 1323 if (FnTy->getTypeQuals() != 0 && 1324 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 1325 ((D.getContext() != Declarator::MemberContext && 1326 (!D.getCXXScopeSpec().isSet() || 1327 !computeDeclContext(D.getCXXScopeSpec(), /*FIXME:*/true) 1328 ->isRecord())) || 1329 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) { 1330 if (D.isFunctionDeclarator()) 1331 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type); 1332 else 1333 Diag(D.getIdentifierLoc(), 1334 diag::err_invalid_qualified_typedef_function_type_use); 1335 1336 // Strip the cv-quals from the type. 1337 T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(), 1338 FnTy->getNumArgs(), FnTy->isVariadic(), 0, 1339 false, false, 0, 0, FunctionType::ExtInfo()); 1340 } 1341 } 1342 1343 // If there's a constexpr specifier, treat it as a top-level const. 1344 if (D.getDeclSpec().isConstexprSpecified()) { 1345 T.addConst(); 1346 } 1347 1348 // Process any function attributes we might have delayed from the 1349 // declaration-specifiers. 1350 ProcessDelayedFnAttrs(*this, T, FnAttrsFromDeclSpec); 1351 1352 // If there were any type attributes applied to the decl itself, not 1353 // the type, apply them to the result type. But don't do this for 1354 // block-literal expressions, which are parsed wierdly. 1355 if (D.getContext() != Declarator::BlockLiteralContext) 1356 if (const AttributeList *Attrs = D.getAttributes()) 1357 ProcessTypeAttributeList(*this, T, false, Attrs, 1358 FnAttrsFromPreviousChunk); 1359 1360 DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk); 1361 1362 if (T.isNull()) 1363 return Context.getNullTypeSourceInfo(); 1364 else if (D.isInvalidType()) 1365 return Context.getTrivialTypeSourceInfo(T); 1366 return GetTypeSourceInfoForDeclarator(D, T, ReturnTypeInfo); 1367} 1368 1369namespace { 1370 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 1371 const DeclSpec &DS; 1372 1373 public: 1374 TypeSpecLocFiller(const DeclSpec &DS) : DS(DS) {} 1375 1376 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1377 Visit(TL.getUnqualifiedLoc()); 1378 } 1379 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 1380 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 1381 } 1382 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 1383 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 1384 } 1385 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 1386 // Handle the base type, which might not have been written explicitly. 1387 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { 1388 TL.setHasBaseTypeAsWritten(false); 1389 TL.getBaseLoc().initialize(SourceLocation()); 1390 } else { 1391 TL.setHasBaseTypeAsWritten(true); 1392 Visit(TL.getBaseLoc()); 1393 } 1394 1395 // Protocol qualifiers. 1396 if (DS.getProtocolQualifiers()) { 1397 assert(TL.getNumProtocols() > 0); 1398 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers()); 1399 TL.setLAngleLoc(DS.getProtocolLAngleLoc()); 1400 TL.setRAngleLoc(DS.getSourceRange().getEnd()); 1401 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i) 1402 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]); 1403 } else { 1404 assert(TL.getNumProtocols() == 0); 1405 TL.setLAngleLoc(SourceLocation()); 1406 TL.setRAngleLoc(SourceLocation()); 1407 } 1408 } 1409 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1410 TL.setStarLoc(SourceLocation()); 1411 Visit(TL.getPointeeLoc()); 1412 } 1413 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 1414 TypeSourceInfo *TInfo = 0; 1415 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo); 1416 1417 // If we got no declarator info from previous Sema routines, 1418 // just fill with the typespec loc. 1419 if (!TInfo) { 1420 TL.initialize(DS.getTypeSpecTypeLoc()); 1421 return; 1422 } 1423 1424 TypeLoc OldTL = TInfo->getTypeLoc(); 1425 if (TInfo->getType()->getAs<ElaboratedType>()) { 1426 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL); 1427 TemplateSpecializationTypeLoc NamedTL = 1428 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc()); 1429 TL.copy(NamedTL); 1430 } 1431 else 1432 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL)); 1433 } 1434 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 1435 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 1436 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 1437 TL.setParensRange(DS.getTypeofParensRange()); 1438 } 1439 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 1440 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 1441 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 1442 TL.setParensRange(DS.getTypeofParensRange()); 1443 assert(DS.getTypeRep()); 1444 TypeSourceInfo *TInfo = 0; 1445 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo); 1446 TL.setUnderlyingTInfo(TInfo); 1447 } 1448 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 1449 // By default, use the source location of the type specifier. 1450 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 1451 if (TL.needsExtraLocalData()) { 1452 // Set info for the written builtin specifiers. 1453 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 1454 // Try to have a meaningful source location. 1455 if (TL.getWrittenSignSpec() != TSS_unspecified) 1456 // Sign spec loc overrides the others (e.g., 'unsigned long'). 1457 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 1458 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 1459 // Width spec loc overrides type spec loc (e.g., 'short int'). 1460 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 1461 } 1462 } 1463 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 1464 ElaboratedTypeKeyword Keyword 1465 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 1466 if (Keyword == ETK_Typename) { 1467 TypeSourceInfo *TInfo = 0; 1468 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo); 1469 if (TInfo) { 1470 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc())); 1471 return; 1472 } 1473 } 1474 TL.setKeywordLoc(Keyword != ETK_None 1475 ? DS.getTypeSpecTypeLoc() 1476 : SourceLocation()); 1477 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 1478 TL.setQualifierRange(SS.isEmpty() ? SourceRange(): SS.getRange()); 1479 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 1480 } 1481 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 1482 ElaboratedTypeKeyword Keyword 1483 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 1484 if (Keyword == ETK_Typename) { 1485 TypeSourceInfo *TInfo = 0; 1486 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo); 1487 if (TInfo) { 1488 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc())); 1489 return; 1490 } 1491 } 1492 TL.setKeywordLoc(Keyword != ETK_None 1493 ? DS.getTypeSpecTypeLoc() 1494 : SourceLocation()); 1495 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 1496 TL.setQualifierRange(SS.isEmpty() ? SourceRange() : SS.getRange()); 1497 // FIXME: load appropriate source location. 1498 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 1499 } 1500 void VisitDependentTemplateSpecializationTypeLoc( 1501 DependentTemplateSpecializationTypeLoc TL) { 1502 ElaboratedTypeKeyword Keyword 1503 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 1504 if (Keyword == ETK_Typename) { 1505 TypeSourceInfo *TInfo = 0; 1506 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo); 1507 if (TInfo) { 1508 TL.copy(cast<DependentTemplateSpecializationTypeLoc>( 1509 TInfo->getTypeLoc())); 1510 return; 1511 } 1512 } 1513 TL.initializeLocal(SourceLocation()); 1514 TL.setKeywordLoc(Keyword != ETK_None 1515 ? DS.getTypeSpecTypeLoc() 1516 : SourceLocation()); 1517 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 1518 TL.setQualifierRange(SS.isEmpty() ? SourceRange() : SS.getRange()); 1519 // FIXME: load appropriate source location. 1520 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 1521 } 1522 1523 void VisitTypeLoc(TypeLoc TL) { 1524 // FIXME: add other typespec types and change this to an assert. 1525 TL.initialize(DS.getTypeSpecTypeLoc()); 1526 } 1527 }; 1528 1529 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 1530 const DeclaratorChunk &Chunk; 1531 1532 public: 1533 DeclaratorLocFiller(const DeclaratorChunk &Chunk) : Chunk(Chunk) {} 1534 1535 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1536 llvm_unreachable("qualified type locs not expected here!"); 1537 } 1538 1539 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 1540 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 1541 TL.setCaretLoc(Chunk.Loc); 1542 } 1543 void VisitPointerTypeLoc(PointerTypeLoc TL) { 1544 assert(Chunk.Kind == DeclaratorChunk::Pointer); 1545 TL.setStarLoc(Chunk.Loc); 1546 } 1547 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1548 assert(Chunk.Kind == DeclaratorChunk::Pointer); 1549 TL.setStarLoc(Chunk.Loc); 1550 } 1551 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 1552 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 1553 TL.setStarLoc(Chunk.Loc); 1554 // FIXME: nested name specifier 1555 } 1556 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 1557 assert(Chunk.Kind == DeclaratorChunk::Reference); 1558 // 'Amp' is misleading: this might have been originally 1559 /// spelled with AmpAmp. 1560 TL.setAmpLoc(Chunk.Loc); 1561 } 1562 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 1563 assert(Chunk.Kind == DeclaratorChunk::Reference); 1564 assert(!Chunk.Ref.LValueRef); 1565 TL.setAmpAmpLoc(Chunk.Loc); 1566 } 1567 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 1568 assert(Chunk.Kind == DeclaratorChunk::Array); 1569 TL.setLBracketLoc(Chunk.Loc); 1570 TL.setRBracketLoc(Chunk.EndLoc); 1571 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 1572 } 1573 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 1574 assert(Chunk.Kind == DeclaratorChunk::Function); 1575 TL.setLParenLoc(Chunk.Loc); 1576 TL.setRParenLoc(Chunk.EndLoc); 1577 1578 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 1579 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) { 1580 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>(); 1581 TL.setArg(tpi++, Param); 1582 } 1583 // FIXME: exception specs 1584 } 1585 1586 void VisitTypeLoc(TypeLoc TL) { 1587 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 1588 } 1589 }; 1590} 1591 1592/// \brief Create and instantiate a TypeSourceInfo with type source information. 1593/// 1594/// \param T QualType referring to the type as written in source code. 1595/// 1596/// \param ReturnTypeInfo For declarators whose return type does not show 1597/// up in the normal place in the declaration specifiers (such as a C++ 1598/// conversion function), this pointer will refer to a type source information 1599/// for that return type. 1600TypeSourceInfo * 1601Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 1602 TypeSourceInfo *ReturnTypeInfo) { 1603 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 1604 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 1605 1606 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 1607 DeclaratorLocFiller(D.getTypeObject(i)).Visit(CurrTL); 1608 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 1609 } 1610 1611 TypeSpecLocFiller(D.getDeclSpec()).Visit(CurrTL); 1612 1613 // We have source information for the return type that was not in the 1614 // declaration specifiers; copy that information into the current type 1615 // location so that it will be retained. This occurs, for example, with 1616 // a C++ conversion function, where the return type occurs within the 1617 // declarator-id rather than in the declaration specifiers. 1618 if (ReturnTypeInfo && D.getDeclSpec().getTypeSpecType() == TST_unspecified) { 1619 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 1620 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 1621 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 1622 } 1623 1624 return TInfo; 1625} 1626 1627/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 1628QualType Sema::CreateLocInfoType(QualType T, TypeSourceInfo *TInfo) { 1629 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 1630 // and Sema during declaration parsing. Try deallocating/caching them when 1631 // it's appropriate, instead of allocating them and keeping them around. 1632 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 8); 1633 new (LocT) LocInfoType(T, TInfo); 1634 assert(LocT->getTypeClass() != T->getTypeClass() && 1635 "LocInfoType's TypeClass conflicts with an existing Type class"); 1636 return QualType(LocT, 0); 1637} 1638 1639void LocInfoType::getAsStringInternal(std::string &Str, 1640 const PrintingPolicy &Policy) const { 1641 assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*" 1642 " was used directly instead of getting the QualType through" 1643 " GetTypeFromParser"); 1644} 1645 1646Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 1647 // C99 6.7.6: Type names have no identifier. This is already validated by 1648 // the parser. 1649 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 1650 1651 TagDecl *OwnedTag = 0; 1652 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag); 1653 QualType T = TInfo->getType(); 1654 if (D.isInvalidType()) 1655 return true; 1656 1657 if (getLangOptions().CPlusPlus) { 1658 // Check that there are no default arguments (C++ only). 1659 CheckExtraCXXDefaultArguments(D); 1660 1661 // C++0x [dcl.type]p3: 1662 // A type-specifier-seq shall not define a class or enumeration 1663 // unless it appears in the type-id of an alias-declaration 1664 // (7.1.3). 1665 if (OwnedTag && OwnedTag->isDefinition()) 1666 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier) 1667 << Context.getTypeDeclType(OwnedTag); 1668 } 1669 1670 T = CreateLocInfoType(T, TInfo); 1671 return T.getAsOpaquePtr(); 1672} 1673 1674 1675 1676//===----------------------------------------------------------------------===// 1677// Type Attribute Processing 1678//===----------------------------------------------------------------------===// 1679 1680/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 1681/// specified type. The attribute contains 1 argument, the id of the address 1682/// space for the type. 1683static void HandleAddressSpaceTypeAttribute(QualType &Type, 1684 const AttributeList &Attr, Sema &S){ 1685 1686 // If this type is already address space qualified, reject it. 1687 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers 1688 // for two or more different address spaces." 1689 if (Type.getAddressSpace()) { 1690 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 1691 Attr.setInvalid(); 1692 return; 1693 } 1694 1695 // Check the attribute arguments. 1696 if (Attr.getNumArgs() != 1) { 1697 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1698 Attr.setInvalid(); 1699 return; 1700 } 1701 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 1702 llvm::APSInt addrSpace(32); 1703 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 1704 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 1705 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) 1706 << ASArgExpr->getSourceRange(); 1707 Attr.setInvalid(); 1708 return; 1709 } 1710 1711 // Bounds checking. 1712 if (addrSpace.isSigned()) { 1713 if (addrSpace.isNegative()) { 1714 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 1715 << ASArgExpr->getSourceRange(); 1716 Attr.setInvalid(); 1717 return; 1718 } 1719 addrSpace.setIsSigned(false); 1720 } 1721 llvm::APSInt max(addrSpace.getBitWidth()); 1722 max = Qualifiers::MaxAddressSpace; 1723 if (addrSpace > max) { 1724 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 1725 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange(); 1726 Attr.setInvalid(); 1727 return; 1728 } 1729 1730 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 1731 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 1732} 1733 1734/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the 1735/// specified type. The attribute contains 1 argument, weak or strong. 1736static void HandleObjCGCTypeAttribute(QualType &Type, 1737 const AttributeList &Attr, Sema &S) { 1738 if (Type.getObjCGCAttr() != Qualifiers::GCNone) { 1739 S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc); 1740 Attr.setInvalid(); 1741 return; 1742 } 1743 1744 // Check the attribute arguments. 1745 if (!Attr.getParameterName()) { 1746 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string) 1747 << "objc_gc" << 1; 1748 Attr.setInvalid(); 1749 return; 1750 } 1751 Qualifiers::GC GCAttr; 1752 if (Attr.getNumArgs() != 0) { 1753 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1754 Attr.setInvalid(); 1755 return; 1756 } 1757 if (Attr.getParameterName()->isStr("weak")) 1758 GCAttr = Qualifiers::Weak; 1759 else if (Attr.getParameterName()->isStr("strong")) 1760 GCAttr = Qualifiers::Strong; 1761 else { 1762 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 1763 << "objc_gc" << Attr.getParameterName(); 1764 Attr.setInvalid(); 1765 return; 1766 } 1767 1768 Type = S.Context.getObjCGCQualType(Type, GCAttr); 1769} 1770 1771/// Process an individual function attribute. Returns true if the 1772/// attribute does not make sense to apply to this type. 1773bool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr) { 1774 if (Attr.getKind() == AttributeList::AT_noreturn) { 1775 // Complain immediately if the arg count is wrong. 1776 if (Attr.getNumArgs() != 0) { 1777 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0; 1778 Attr.setInvalid(); 1779 return false; 1780 } 1781 1782 // Delay if this is not a function or pointer to block. 1783 if (!Type->isFunctionPointerType() 1784 && !Type->isBlockPointerType() 1785 && !Type->isFunctionType()) 1786 return true; 1787 1788 // Otherwise we can process right away. 1789 Type = S.Context.getNoReturnType(Type); 1790 return false; 1791 } 1792 1793 if (Attr.getKind() == AttributeList::AT_regparm) { 1794 // The warning is emitted elsewhere 1795 if (Attr.getNumArgs() != 1) { 1796 return false; 1797 } 1798 1799 // Delay if this is not a function or pointer to block. 1800 if (!Type->isFunctionPointerType() 1801 && !Type->isBlockPointerType() 1802 && !Type->isFunctionType()) 1803 return true; 1804 1805 // Otherwise we can process right away. 1806 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArg(0)); 1807 llvm::APSInt NumParams(32); 1808 1809 // The warning is emitted elsewhere 1810 if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() || 1811 !NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) 1812 return false; 1813 1814 Type = S.Context.getRegParmType(Type, NumParams.getZExtValue()); 1815 return false; 1816 } 1817 1818 // Otherwise, a calling convention. 1819 if (Attr.getNumArgs() != 0) { 1820 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0; 1821 Attr.setInvalid(); 1822 return false; 1823 } 1824 1825 QualType T = Type; 1826 if (const PointerType *PT = Type->getAs<PointerType>()) 1827 T = PT->getPointeeType(); 1828 const FunctionType *Fn = T->getAs<FunctionType>(); 1829 1830 // Delay if the type didn't work out to a function. 1831 if (!Fn) return true; 1832 1833 // TODO: diagnose uses of these conventions on the wrong target. 1834 CallingConv CC; 1835 switch (Attr.getKind()) { 1836 case AttributeList::AT_cdecl: CC = CC_C; break; 1837 case AttributeList::AT_fastcall: CC = CC_X86FastCall; break; 1838 case AttributeList::AT_stdcall: CC = CC_X86StdCall; break; 1839 case AttributeList::AT_thiscall: CC = CC_X86ThisCall; break; 1840 default: llvm_unreachable("unexpected attribute kind"); return false; 1841 } 1842 1843 CallingConv CCOld = Fn->getCallConv(); 1844 if (S.Context.getCanonicalCallConv(CC) == 1845 S.Context.getCanonicalCallConv(CCOld)) { 1846 Attr.setInvalid(); 1847 return false; 1848 } 1849 1850 if (CCOld != CC_Default) { 1851 // Should we diagnose reapplications of the same convention? 1852 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 1853 << FunctionType::getNameForCallConv(CC) 1854 << FunctionType::getNameForCallConv(CCOld); 1855 Attr.setInvalid(); 1856 return false; 1857 } 1858 1859 // Diagnose the use of X86 fastcall on varargs or unprototyped functions. 1860 if (CC == CC_X86FastCall) { 1861 if (isa<FunctionNoProtoType>(Fn)) { 1862 S.Diag(Attr.getLoc(), diag::err_cconv_knr) 1863 << FunctionType::getNameForCallConv(CC); 1864 Attr.setInvalid(); 1865 return false; 1866 } 1867 1868 const FunctionProtoType *FnP = cast<FunctionProtoType>(Fn); 1869 if (FnP->isVariadic()) { 1870 S.Diag(Attr.getLoc(), diag::err_cconv_varargs) 1871 << FunctionType::getNameForCallConv(CC); 1872 Attr.setInvalid(); 1873 return false; 1874 } 1875 } 1876 1877 Type = S.Context.getCallConvType(Type, CC); 1878 return false; 1879} 1880 1881/// HandleVectorSizeAttribute - this attribute is only applicable to integral 1882/// and float scalars, although arrays, pointers, and function return values are 1883/// allowed in conjunction with this construct. Aggregates with this attribute 1884/// are invalid, even if they are of the same size as a corresponding scalar. 1885/// The raw attribute should contain precisely 1 argument, the vector size for 1886/// the variable, measured in bytes. If curType and rawAttr are well formed, 1887/// this routine will return a new vector type. 1888static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 1889 Sema &S) { 1890 // Check the attribute arugments. 1891 if (Attr.getNumArgs() != 1) { 1892 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1893 Attr.setInvalid(); 1894 return; 1895 } 1896 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 1897 llvm::APSInt vecSize(32); 1898 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 1899 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 1900 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 1901 << "vector_size" << sizeExpr->getSourceRange(); 1902 Attr.setInvalid(); 1903 return; 1904 } 1905 // the base type must be integer or float, and can't already be a vector. 1906 if (CurType->isVectorType() || 1907 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) { 1908 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 1909 Attr.setInvalid(); 1910 return; 1911 } 1912 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 1913 // vecSize is specified in bytes - convert to bits. 1914 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 1915 1916 // the vector size needs to be an integral multiple of the type size. 1917 if (vectorSize % typeSize) { 1918 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 1919 << sizeExpr->getSourceRange(); 1920 Attr.setInvalid(); 1921 return; 1922 } 1923 if (vectorSize == 0) { 1924 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 1925 << sizeExpr->getSourceRange(); 1926 Attr.setInvalid(); 1927 return; 1928 } 1929 1930 // Success! Instantiate the vector type, the number of elements is > 0, and 1931 // not required to be a power of 2, unlike GCC. 1932 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 1933 VectorType::NotAltiVec); 1934} 1935 1936void ProcessTypeAttributeList(Sema &S, QualType &Result, 1937 bool IsDeclSpec, const AttributeList *AL, 1938 DelayedAttributeSet &FnAttrs) { 1939 // Scan through and apply attributes to this type where it makes sense. Some 1940 // attributes (such as __address_space__, __vector_size__, etc) apply to the 1941 // type, but others can be present in the type specifiers even though they 1942 // apply to the decl. Here we apply type attributes and ignore the rest. 1943 for (; AL; AL = AL->getNext()) { 1944 // Skip attributes that were marked to be invalid. 1945 if (AL->isInvalid()) 1946 continue; 1947 1948 // If this is an attribute we can handle, do so now, 1949 // otherwise, add it to the FnAttrs list for rechaining. 1950 switch (AL->getKind()) { 1951 default: break; 1952 1953 case AttributeList::AT_address_space: 1954 HandleAddressSpaceTypeAttribute(Result, *AL, S); 1955 break; 1956 case AttributeList::AT_objc_gc: 1957 HandleObjCGCTypeAttribute(Result, *AL, S); 1958 break; 1959 case AttributeList::AT_vector_size: 1960 HandleVectorSizeAttr(Result, *AL, S); 1961 break; 1962 1963 case AttributeList::AT_noreturn: 1964 case AttributeList::AT_cdecl: 1965 case AttributeList::AT_fastcall: 1966 case AttributeList::AT_stdcall: 1967 case AttributeList::AT_thiscall: 1968 case AttributeList::AT_regparm: 1969 // Don't process these on the DeclSpec. 1970 if (IsDeclSpec || 1971 ProcessFnAttr(S, Result, *AL)) 1972 FnAttrs.push_back(DelayedAttribute(AL, Result)); 1973 break; 1974 } 1975 } 1976} 1977 1978/// @brief Ensure that the type T is a complete type. 1979/// 1980/// This routine checks whether the type @p T is complete in any 1981/// context where a complete type is required. If @p T is a complete 1982/// type, returns false. If @p T is a class template specialization, 1983/// this routine then attempts to perform class template 1984/// instantiation. If instantiation fails, or if @p T is incomplete 1985/// and cannot be completed, issues the diagnostic @p diag (giving it 1986/// the type @p T) and returns true. 1987/// 1988/// @param Loc The location in the source that the incomplete type 1989/// diagnostic should refer to. 1990/// 1991/// @param T The type that this routine is examining for completeness. 1992/// 1993/// @param PD The partial diagnostic that will be printed out if T is not a 1994/// complete type. 1995/// 1996/// @returns @c true if @p T is incomplete and a diagnostic was emitted, 1997/// @c false otherwise. 1998bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 1999 const PartialDiagnostic &PD, 2000 std::pair<SourceLocation, 2001 PartialDiagnostic> Note) { 2002 unsigned diag = PD.getDiagID(); 2003 2004 // FIXME: Add this assertion to make sure we always get instantiation points. 2005 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 2006 // FIXME: Add this assertion to help us flush out problems with 2007 // checking for dependent types and type-dependent expressions. 2008 // 2009 // assert(!T->isDependentType() && 2010 // "Can't ask whether a dependent type is complete"); 2011 2012 // If we have a complete type, we're done. 2013 if (!T->isIncompleteType()) 2014 return false; 2015 2016 // If we have a class template specialization or a class member of a 2017 // class template specialization, or an array with known size of such, 2018 // try to instantiate it. 2019 QualType MaybeTemplate = T; 2020 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T)) 2021 MaybeTemplate = Array->getElementType(); 2022 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 2023 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 2024 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 2025 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) 2026 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec, 2027 TSK_ImplicitInstantiation, 2028 /*Complain=*/diag != 0); 2029 } else if (CXXRecordDecl *Rec 2030 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 2031 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) { 2032 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo(); 2033 assert(MSInfo && "Missing member specialization information?"); 2034 // This record was instantiated from a class within a template. 2035 if (MSInfo->getTemplateSpecializationKind() 2036 != TSK_ExplicitSpecialization) 2037 return InstantiateClass(Loc, Rec, Pattern, 2038 getTemplateInstantiationArgs(Rec), 2039 TSK_ImplicitInstantiation, 2040 /*Complain=*/diag != 0); 2041 } 2042 } 2043 } 2044 2045 if (diag == 0) 2046 return true; 2047 2048 const TagType *Tag = 0; 2049 if (const RecordType *Record = T->getAs<RecordType>()) 2050 Tag = Record; 2051 else if (const EnumType *Enum = T->getAs<EnumType>()) 2052 Tag = Enum; 2053 2054 // Avoid diagnosing invalid decls as incomplete. 2055 if (Tag && Tag->getDecl()->isInvalidDecl()) 2056 return true; 2057 2058 // We have an incomplete type. Produce a diagnostic. 2059 Diag(Loc, PD) << T; 2060 2061 // If we have a note, produce it. 2062 if (!Note.first.isInvalid()) 2063 Diag(Note.first, Note.second); 2064 2065 // If the type was a forward declaration of a class/struct/union 2066 // type, produce a note. 2067 if (Tag && !Tag->getDecl()->isInvalidDecl()) 2068 Diag(Tag->getDecl()->getLocation(), 2069 Tag->isBeingDefined() ? diag::note_type_being_defined 2070 : diag::note_forward_declaration) 2071 << QualType(Tag, 0); 2072 2073 return true; 2074} 2075 2076bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 2077 const PartialDiagnostic &PD) { 2078 return RequireCompleteType(Loc, T, PD, 2079 std::make_pair(SourceLocation(), PDiag(0))); 2080} 2081 2082bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 2083 unsigned DiagID) { 2084 return RequireCompleteType(Loc, T, PDiag(DiagID), 2085 std::make_pair(SourceLocation(), PDiag(0))); 2086} 2087 2088/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 2089/// and qualified by the nested-name-specifier contained in SS. 2090QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 2091 const CXXScopeSpec &SS, QualType T) { 2092 if (T.isNull()) 2093 return T; 2094 NestedNameSpecifier *NNS; 2095 if (SS.isValid()) 2096 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 2097 else { 2098 if (Keyword == ETK_None) 2099 return T; 2100 NNS = 0; 2101 } 2102 return Context.getElaboratedType(Keyword, NNS, T); 2103} 2104 2105QualType Sema::BuildTypeofExprType(Expr *E) { 2106 if (E->getType() == Context.OverloadTy) { 2107 // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a 2108 // function template specialization wherever deduction cannot occur. 2109 if (FunctionDecl *Specialization 2110 = ResolveSingleFunctionTemplateSpecialization(E)) { 2111 // The access doesn't really matter in this case. 2112 DeclAccessPair Found = DeclAccessPair::make(Specialization, 2113 Specialization->getAccess()); 2114 E = FixOverloadedFunctionReference(E, Found, Specialization); 2115 if (!E) 2116 return QualType(); 2117 } else { 2118 Diag(E->getLocStart(), 2119 diag::err_cannot_determine_declared_type_of_overloaded_function) 2120 << false << E->getSourceRange(); 2121 return QualType(); 2122 } 2123 } 2124 2125 return Context.getTypeOfExprType(E); 2126} 2127 2128QualType Sema::BuildDecltypeType(Expr *E) { 2129 if (E->getType() == Context.OverloadTy) { 2130 // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a 2131 // function template specialization wherever deduction cannot occur. 2132 if (FunctionDecl *Specialization 2133 = ResolveSingleFunctionTemplateSpecialization(E)) { 2134 // The access doesn't really matter in this case. 2135 DeclAccessPair Found = DeclAccessPair::make(Specialization, 2136 Specialization->getAccess()); 2137 E = FixOverloadedFunctionReference(E, Found, Specialization); 2138 if (!E) 2139 return QualType(); 2140 } else { 2141 Diag(E->getLocStart(), 2142 diag::err_cannot_determine_declared_type_of_overloaded_function) 2143 << true << E->getSourceRange(); 2144 return QualType(); 2145 } 2146 } 2147 2148 return Context.getDecltypeType(E); 2149} 2150