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