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