SemaType.cpp revision 06bfa84588658d721094f383d6950e75100c4c4c
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 "clang/Sema/SemaInternal.h" 15#include "clang/Sema/Template.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/CXXInheritance.h" 18#include "clang/AST/DeclObjC.h" 19#include "clang/AST/DeclTemplate.h" 20#include "clang/AST/TypeLoc.h" 21#include "clang/AST/TypeLocVisitor.h" 22#include "clang/AST/Expr.h" 23#include "clang/Basic/PartialDiagnostic.h" 24#include "clang/Basic/TargetInfo.h" 25#include "clang/Sema/DeclSpec.h" 26#include "llvm/ADT/SmallPtrSet.h" 27#include "llvm/Support/ErrorHandling.h" 28using namespace clang; 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 73// objc_gc applies to Objective-C pointers or, otherwise, to the 74// smallest available pointer type (i.e. 'void*' in 'void**'). 75#define OBJC_POINTER_TYPE_ATTRS_CASELIST \ 76 case AttributeList::AT_objc_gc 77 78// Function type attributes. 79#define FUNCTION_TYPE_ATTRS_CASELIST \ 80 case AttributeList::AT_noreturn: \ 81 case AttributeList::AT_cdecl: \ 82 case AttributeList::AT_fastcall: \ 83 case AttributeList::AT_stdcall: \ 84 case AttributeList::AT_thiscall: \ 85 case AttributeList::AT_pascal: \ 86 case AttributeList::AT_regparm 87 88namespace { 89 /// An object which stores processing state for the entire 90 /// GetTypeForDeclarator process. 91 class TypeProcessingState { 92 Sema &sema; 93 94 /// The declarator being processed. 95 Declarator &declarator; 96 97 /// The index of the declarator chunk we're currently processing. 98 /// May be the total number of valid chunks, indicating the 99 /// DeclSpec. 100 unsigned chunkIndex; 101 102 /// Whether there are non-trivial modifications to the decl spec. 103 bool trivial; 104 105 /// The original set of attributes on the DeclSpec. 106 llvm::SmallVector<AttributeList*, 2> savedAttrs; 107 108 /// A list of attributes to diagnose the uselessness of when the 109 /// processing is complete. 110 llvm::SmallVector<AttributeList*, 2> ignoredTypeAttrs; 111 112 public: 113 TypeProcessingState(Sema &sema, Declarator &declarator) 114 : sema(sema), declarator(declarator), 115 chunkIndex(declarator.getNumTypeObjects()), 116 trivial(true) {} 117 118 Sema &getSema() const { 119 return sema; 120 } 121 122 Declarator &getDeclarator() const { 123 return declarator; 124 } 125 126 unsigned getCurrentChunkIndex() const { 127 return chunkIndex; 128 } 129 130 void setCurrentChunkIndex(unsigned idx) { 131 assert(idx <= declarator.getNumTypeObjects()); 132 chunkIndex = idx; 133 } 134 135 AttributeList *&getCurrentAttrListRef() const { 136 assert(chunkIndex <= declarator.getNumTypeObjects()); 137 if (chunkIndex == declarator.getNumTypeObjects()) 138 return getMutableDeclSpec().getAttributes().getListRef(); 139 return declarator.getTypeObject(chunkIndex).getAttrListRef(); 140 } 141 142 /// Save the current set of attributes on the DeclSpec. 143 void saveDeclSpecAttrs() { 144 // Don't try to save them multiple times. 145 if (!savedAttrs.empty()) return; 146 147 DeclSpec &spec = getMutableDeclSpec(); 148 for (AttributeList *attr = spec.getAttributes().getList(); attr; 149 attr = attr->getNext()) 150 savedAttrs.push_back(attr); 151 trivial &= savedAttrs.empty(); 152 } 153 154 /// Record that we had nowhere to put the given type attribute. 155 /// We will diagnose such attributes later. 156 void addIgnoredTypeAttr(AttributeList &attr) { 157 ignoredTypeAttrs.push_back(&attr); 158 } 159 160 /// Diagnose all the ignored type attributes, given that the 161 /// declarator worked out to the given type. 162 void diagnoseIgnoredTypeAttrs(QualType type) const { 163 for (llvm::SmallVectorImpl<AttributeList*>::const_iterator 164 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end(); 165 i != e; ++i) { 166 AttributeList &attr = **i; 167 getSema().Diag(attr.getLoc(), diag::warn_function_attribute_wrong_type) 168 << attr.getName() << type; 169 } 170 } 171 172 ~TypeProcessingState() { 173 if (trivial) return; 174 175 restoreDeclSpecAttrs(); 176 } 177 178 private: 179 DeclSpec &getMutableDeclSpec() const { 180 return const_cast<DeclSpec&>(declarator.getDeclSpec()); 181 } 182 183 void restoreDeclSpecAttrs() { 184 assert(!savedAttrs.empty()); 185 getMutableDeclSpec().getAttributes().set(savedAttrs[0]); 186 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i) 187 savedAttrs[i]->setNext(savedAttrs[i+1]); 188 savedAttrs.back()->setNext(0); 189 } 190 }; 191 192 /// Basically std::pair except that we really want to avoid an 193 /// implicit operator= for safety concerns. It's also a minor 194 /// link-time optimization for this to be a private type. 195 struct AttrAndList { 196 /// The attribute. 197 AttributeList &first; 198 199 /// The head of the list the attribute is currently in. 200 AttributeList *&second; 201 202 AttrAndList(AttributeList &attr, AttributeList *&head) 203 : first(attr), second(head) {} 204 }; 205} 206 207namespace llvm { 208 template <> struct isPodLike<AttrAndList> { 209 static const bool value = true; 210 }; 211} 212 213static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) { 214 attr.setNext(head); 215 head = &attr; 216} 217 218static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) { 219 if (head == &attr) { 220 head = attr.getNext(); 221 return; 222 } 223 224 AttributeList *cur = head; 225 while (true) { 226 assert(cur && cur->getNext() && "ran out of attrs?"); 227 if (cur->getNext() == &attr) { 228 cur->setNext(attr.getNext()); 229 return; 230 } 231 cur = cur->getNext(); 232 } 233} 234 235static void moveAttrFromListToList(AttributeList &attr, 236 AttributeList *&fromList, 237 AttributeList *&toList) { 238 spliceAttrOutOfList(attr, fromList); 239 spliceAttrIntoList(attr, toList); 240} 241 242static void processTypeAttrs(TypeProcessingState &state, 243 QualType &type, bool isDeclSpec, 244 AttributeList *attrs); 245 246static bool handleFunctionTypeAttr(TypeProcessingState &state, 247 AttributeList &attr, 248 QualType &type); 249 250static bool handleObjCGCTypeAttr(TypeProcessingState &state, 251 AttributeList &attr, QualType &type); 252 253static bool handleObjCPointerTypeAttr(TypeProcessingState &state, 254 AttributeList &attr, QualType &type) { 255 // Right now, we have exactly one of these attributes: objc_gc. 256 assert(attr.getKind() == AttributeList::AT_objc_gc); 257 return handleObjCGCTypeAttr(state, attr, type); 258} 259 260/// Given that an objc_gc attribute was written somewhere on a 261/// declaration *other* than on the declarator itself (for which, use 262/// distributeObjCPointerTypeAttrFromDeclarator), and given that it 263/// didn't apply in whatever position it was written in, try to move 264/// it to a more appropriate position. 265static void distributeObjCPointerTypeAttr(TypeProcessingState &state, 266 AttributeList &attr, 267 QualType type) { 268 Declarator &declarator = state.getDeclarator(); 269 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 270 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 271 switch (chunk.Kind) { 272 case DeclaratorChunk::Pointer: 273 case DeclaratorChunk::BlockPointer: 274 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 275 chunk.getAttrListRef()); 276 return; 277 278 case DeclaratorChunk::Paren: 279 case DeclaratorChunk::Array: 280 continue; 281 282 // Don't walk through these. 283 case DeclaratorChunk::Reference: 284 case DeclaratorChunk::Function: 285 case DeclaratorChunk::MemberPointer: 286 goto error; 287 } 288 } 289 error: 290 291 state.getSema().Diag(attr.getLoc(), diag::warn_function_attribute_wrong_type) 292 << attr.getName() << type; 293} 294 295/// Distribute an objc_gc type attribute that was written on the 296/// declarator. 297static void 298distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, 299 AttributeList &attr, 300 QualType &declSpecType) { 301 Declarator &declarator = state.getDeclarator(); 302 303 // objc_gc goes on the innermost pointer to something that's not a 304 // pointer. 305 unsigned innermost = -1U; 306 bool considerDeclSpec = true; 307 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 308 DeclaratorChunk &chunk = declarator.getTypeObject(i); 309 switch (chunk.Kind) { 310 case DeclaratorChunk::Pointer: 311 case DeclaratorChunk::BlockPointer: 312 innermost = i; 313 continue; 314 315 case DeclaratorChunk::Reference: 316 case DeclaratorChunk::MemberPointer: 317 case DeclaratorChunk::Paren: 318 case DeclaratorChunk::Array: 319 continue; 320 321 case DeclaratorChunk::Function: 322 considerDeclSpec = false; 323 goto done; 324 } 325 } 326 done: 327 328 // That might actually be the decl spec if we weren't blocked by 329 // anything in the declarator. 330 if (considerDeclSpec) { 331 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) 332 return; 333 } 334 335 // Otherwise, if we found an appropriate chunk, splice the attribute 336 // into it. 337 if (innermost != -1U) { 338 moveAttrFromListToList(attr, declarator.getAttrListRef(), 339 declarator.getTypeObject(innermost).getAttrListRef()); 340 return; 341 } 342 343 // Otherwise, diagnose when we're done building the type. 344 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 345 state.addIgnoredTypeAttr(attr); 346} 347 348/// A function type attribute was written somewhere in a declaration 349/// *other* than on the declarator itself or in the decl spec. Given 350/// that it didn't apply in whatever position it was written in, try 351/// to move it to a more appropriate position. 352static void distributeFunctionTypeAttr(TypeProcessingState &state, 353 AttributeList &attr, 354 QualType type) { 355 Declarator &declarator = state.getDeclarator(); 356 357 // Try to push the attribute from the return type of a function to 358 // the function itself. 359 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 360 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 361 switch (chunk.Kind) { 362 case DeclaratorChunk::Function: 363 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 364 chunk.getAttrListRef()); 365 return; 366 367 case DeclaratorChunk::Paren: 368 case DeclaratorChunk::Pointer: 369 case DeclaratorChunk::BlockPointer: 370 case DeclaratorChunk::Array: 371 case DeclaratorChunk::Reference: 372 case DeclaratorChunk::MemberPointer: 373 continue; 374 } 375 } 376 377 state.getSema().Diag(attr.getLoc(), diag::warn_function_attribute_wrong_type) 378 << attr.getName() << type; 379} 380 381/// Try to distribute a function type attribute to the innermost 382/// function chunk or type. Returns true if the attribute was 383/// distributed, false if no location was found. 384static bool 385distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, 386 AttributeList &attr, 387 AttributeList *&attrList, 388 QualType &declSpecType) { 389 Declarator &declarator = state.getDeclarator(); 390 391 // Put it on the innermost function chunk, if there is one. 392 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 393 DeclaratorChunk &chunk = declarator.getTypeObject(i); 394 if (chunk.Kind != DeclaratorChunk::Function) continue; 395 396 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef()); 397 return true; 398 } 399 400 return handleFunctionTypeAttr(state, attr, declSpecType); 401} 402 403/// A function type attribute was written in the decl spec. Try to 404/// apply it somewhere. 405static void 406distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, 407 AttributeList &attr, 408 QualType &declSpecType) { 409 state.saveDeclSpecAttrs(); 410 411 // Try to distribute to the innermost. 412 if (distributeFunctionTypeAttrToInnermost(state, attr, 413 state.getCurrentAttrListRef(), 414 declSpecType)) 415 return; 416 417 // If that failed, diagnose the bad attribute when the declarator is 418 // fully built. 419 state.addIgnoredTypeAttr(attr); 420} 421 422/// A function type attribute was written on the declarator. Try to 423/// apply it somewhere. 424static void 425distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, 426 AttributeList &attr, 427 QualType &declSpecType) { 428 Declarator &declarator = state.getDeclarator(); 429 430 // Try to distribute to the innermost. 431 if (distributeFunctionTypeAttrToInnermost(state, attr, 432 declarator.getAttrListRef(), 433 declSpecType)) 434 return; 435 436 // If that failed, diagnose the bad attribute when the declarator is 437 // fully built. 438 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 439 state.addIgnoredTypeAttr(attr); 440} 441 442/// \brief Given that there are attributes written on the declarator 443/// itself, try to distribute any type attributes to the appropriate 444/// declarator chunk. 445/// 446/// These are attributes like the following: 447/// int f ATTR; 448/// int (f ATTR)(); 449/// but not necessarily this: 450/// int f() ATTR; 451static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, 452 QualType &declSpecType) { 453 // Collect all the type attributes from the declarator itself. 454 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!"); 455 AttributeList *attr = state.getDeclarator().getAttributes(); 456 AttributeList *next; 457 do { 458 next = attr->getNext(); 459 460 switch (attr->getKind()) { 461 OBJC_POINTER_TYPE_ATTRS_CASELIST: 462 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType); 463 break; 464 465 FUNCTION_TYPE_ATTRS_CASELIST: 466 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType); 467 break; 468 469 default: 470 break; 471 } 472 } while ((attr = next)); 473} 474 475/// Add a synthetic '()' to a block-literal declarator if it is 476/// required, given the return type. 477static void maybeSynthesizeBlockSignature(TypeProcessingState &state, 478 QualType declSpecType) { 479 Declarator &declarator = state.getDeclarator(); 480 481 // First, check whether the declarator would produce a function, 482 // i.e. whether the innermost semantic chunk is a function. 483 if (declarator.isFunctionDeclarator()) { 484 // If so, make that declarator a prototyped declarator. 485 declarator.getFunctionTypeInfo().hasPrototype = true; 486 return; 487 } 488 489 // If there are any type objects, the type as written won't name a 490 // function, regardless of the decl spec type. This is because a 491 // block signature declarator is always an abstract-declarator, and 492 // abstract-declarators can't just be parentheses chunks. Therefore 493 // we need to build a function chunk unless there are no type 494 // objects and the decl spec type is a function. 495 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) 496 return; 497 498 // Note that there *are* cases with invalid declarators where 499 // declarators consist solely of parentheses. In general, these 500 // occur only in failed efforts to make function declarators, so 501 // faking up the function chunk is still the right thing to do. 502 503 // Otherwise, we need to fake up a function declarator. 504 SourceLocation loc = declarator.getSourceRange().getBegin(); 505 506 // ...and *prepend* it to the declarator. 507 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( 508 ParsedAttributes(), 509 /*proto*/ true, 510 /*variadic*/ false, SourceLocation(), 511 /*args*/ 0, 0, 512 /*type quals*/ 0, 513 /*ref-qualifier*/true, SourceLocation(), 514 /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0, 515 /*parens*/ loc, loc, 516 declarator)); 517 518 // For consistency, make sure the state still has us as processing 519 // the decl spec. 520 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1); 521 state.setCurrentChunkIndex(declarator.getNumTypeObjects()); 522} 523 524/// \brief Convert the specified declspec to the appropriate type 525/// object. 526/// \param D the declarator containing the declaration specifier. 527/// \returns The type described by the declaration specifiers. This function 528/// never returns null. 529static QualType ConvertDeclSpecToType(Sema &S, TypeProcessingState &state) { 530 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 531 // checking. 532 533 Declarator &declarator = state.getDeclarator(); 534 const DeclSpec &DS = declarator.getDeclSpec(); 535 SourceLocation DeclLoc = declarator.getIdentifierLoc(); 536 if (DeclLoc.isInvalid()) 537 DeclLoc = DS.getSourceRange().getBegin(); 538 539 ASTContext &Context = S.Context; 540 541 QualType Result; 542 switch (DS.getTypeSpecType()) { 543 case DeclSpec::TST_void: 544 Result = Context.VoidTy; 545 break; 546 case DeclSpec::TST_char: 547 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 548 Result = Context.CharTy; 549 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 550 Result = Context.SignedCharTy; 551 else { 552 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 553 "Unknown TSS value"); 554 Result = Context.UnsignedCharTy; 555 } 556 break; 557 case DeclSpec::TST_wchar: 558 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 559 Result = Context.WCharTy; 560 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 561 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 562 << DS.getSpecifierName(DS.getTypeSpecType()); 563 Result = Context.getSignedWCharType(); 564 } else { 565 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 566 "Unknown TSS value"); 567 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 568 << DS.getSpecifierName(DS.getTypeSpecType()); 569 Result = Context.getUnsignedWCharType(); 570 } 571 break; 572 case DeclSpec::TST_char16: 573 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 574 "Unknown TSS value"); 575 Result = Context.Char16Ty; 576 break; 577 case DeclSpec::TST_char32: 578 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 579 "Unknown TSS value"); 580 Result = Context.Char32Ty; 581 break; 582 case DeclSpec::TST_unspecified: 583 // "<proto1,proto2>" is an objc qualified ID with a missing id. 584 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 585 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 586 (ObjCProtocolDecl**)PQ, 587 DS.getNumProtocolQualifiers()); 588 Result = Context.getObjCObjectPointerType(Result); 589 break; 590 } 591 592 // If this is a missing declspec in a block literal return context, then it 593 // is inferred from the return statements inside the block. 594 if (isOmittedBlockReturnType(declarator)) { 595 Result = Context.DependentTy; 596 break; 597 } 598 599 // Unspecified typespec defaults to int in C90. However, the C90 grammar 600 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 601 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 602 // Note that the one exception to this is function definitions, which are 603 // allowed to be completely missing a declspec. This is handled in the 604 // parser already though by it pretending to have seen an 'int' in this 605 // case. 606 if (S.getLangOptions().ImplicitInt) { 607 // In C89 mode, we only warn if there is a completely missing declspec 608 // when one is not allowed. 609 if (DS.isEmpty()) { 610 S.Diag(DeclLoc, diag::ext_missing_declspec) 611 << DS.getSourceRange() 612 << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int"); 613 } 614 } else if (!DS.hasTypeSpecifier()) { 615 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 616 // "At least one type specifier shall be given in the declaration 617 // specifiers in each declaration, and in the specifier-qualifier list in 618 // each struct declaration and type name." 619 // FIXME: Does Microsoft really have the implicit int extension in C++? 620 if (S.getLangOptions().CPlusPlus && 621 !S.getLangOptions().Microsoft) { 622 S.Diag(DeclLoc, diag::err_missing_type_specifier) 623 << DS.getSourceRange(); 624 625 // When this occurs in C++ code, often something is very broken with the 626 // value being declared, poison it as invalid so we don't get chains of 627 // errors. 628 declarator.setInvalidType(true); 629 } else { 630 S.Diag(DeclLoc, diag::ext_missing_type_specifier) 631 << DS.getSourceRange(); 632 } 633 } 634 635 // FALL THROUGH. 636 case DeclSpec::TST_int: { 637 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 638 switch (DS.getTypeSpecWidth()) { 639 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 640 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 641 case DeclSpec::TSW_long: Result = Context.LongTy; break; 642 case DeclSpec::TSW_longlong: 643 Result = Context.LongLongTy; 644 645 // long long is a C99 feature. 646 if (!S.getLangOptions().C99 && 647 !S.getLangOptions().CPlusPlus0x) 648 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong); 649 break; 650 } 651 } else { 652 switch (DS.getTypeSpecWidth()) { 653 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 654 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 655 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 656 case DeclSpec::TSW_longlong: 657 Result = Context.UnsignedLongLongTy; 658 659 // long long is a C99 feature. 660 if (!S.getLangOptions().C99 && 661 !S.getLangOptions().CPlusPlus0x) 662 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong); 663 break; 664 } 665 } 666 break; 667 } 668 case DeclSpec::TST_float: Result = Context.FloatTy; break; 669 case DeclSpec::TST_double: 670 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 671 Result = Context.LongDoubleTy; 672 else 673 Result = Context.DoubleTy; 674 675 if (S.getLangOptions().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) { 676 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64); 677 declarator.setInvalidType(true); 678 } 679 break; 680 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 681 case DeclSpec::TST_decimal32: // _Decimal32 682 case DeclSpec::TST_decimal64: // _Decimal64 683 case DeclSpec::TST_decimal128: // _Decimal128 684 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 685 Result = Context.IntTy; 686 declarator.setInvalidType(true); 687 break; 688 case DeclSpec::TST_class: 689 case DeclSpec::TST_enum: 690 case DeclSpec::TST_union: 691 case DeclSpec::TST_struct: { 692 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl()); 693 if (!D) { 694 // This can happen in C++ with ambiguous lookups. 695 Result = Context.IntTy; 696 declarator.setInvalidType(true); 697 break; 698 } 699 700 // If the type is deprecated or unavailable, diagnose it. 701 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeLoc()); 702 703 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 704 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!"); 705 706 // TypeQuals handled by caller. 707 Result = Context.getTypeDeclType(D); 708 709 // In C++, make an ElaboratedType. 710 if (S.getLangOptions().CPlusPlus) { 711 ElaboratedTypeKeyword Keyword 712 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); 713 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result); 714 } 715 if (D->isInvalidDecl()) 716 declarator.setInvalidType(true); 717 break; 718 } 719 case DeclSpec::TST_typename: { 720 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 721 DS.getTypeSpecSign() == 0 && 722 "Can't handle qualifiers on typedef names yet!"); 723 Result = S.GetTypeFromParser(DS.getRepAsType()); 724 if (Result.isNull()) 725 declarator.setInvalidType(true); 726 else if (DeclSpec::ProtocolQualifierListTy PQ 727 = DS.getProtocolQualifiers()) { 728 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) { 729 // Silently drop any existing protocol qualifiers. 730 // TODO: determine whether that's the right thing to do. 731 if (ObjT->getNumProtocols()) 732 Result = ObjT->getBaseType(); 733 734 if (DS.getNumProtocolQualifiers()) 735 Result = Context.getObjCObjectType(Result, 736 (ObjCProtocolDecl**) PQ, 737 DS.getNumProtocolQualifiers()); 738 } else if (Result->isObjCIdType()) { 739 // id<protocol-list> 740 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 741 (ObjCProtocolDecl**) PQ, 742 DS.getNumProtocolQualifiers()); 743 Result = Context.getObjCObjectPointerType(Result); 744 } else if (Result->isObjCClassType()) { 745 // Class<protocol-list> 746 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 747 (ObjCProtocolDecl**) PQ, 748 DS.getNumProtocolQualifiers()); 749 Result = Context.getObjCObjectPointerType(Result); 750 } else { 751 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers) 752 << DS.getSourceRange(); 753 declarator.setInvalidType(true); 754 } 755 } 756 757 // TypeQuals handled by caller. 758 break; 759 } 760 case DeclSpec::TST_typeofType: 761 // FIXME: Preserve type source info. 762 Result = S.GetTypeFromParser(DS.getRepAsType()); 763 assert(!Result.isNull() && "Didn't get a type for typeof?"); 764 if (!Result->isDependentType()) 765 if (const TagType *TT = Result->getAs<TagType>()) 766 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); 767 // TypeQuals handled by caller. 768 Result = Context.getTypeOfType(Result); 769 break; 770 case DeclSpec::TST_typeofExpr: { 771 Expr *E = DS.getRepAsExpr(); 772 assert(E && "Didn't get an expression for typeof?"); 773 // TypeQuals handled by caller. 774 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); 775 if (Result.isNull()) { 776 Result = Context.IntTy; 777 declarator.setInvalidType(true); 778 } 779 break; 780 } 781 case DeclSpec::TST_decltype: { 782 Expr *E = DS.getRepAsExpr(); 783 assert(E && "Didn't get an expression for decltype?"); 784 // TypeQuals handled by caller. 785 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); 786 if (Result.isNull()) { 787 Result = Context.IntTy; 788 declarator.setInvalidType(true); 789 } 790 break; 791 } 792 case DeclSpec::TST_auto: { 793 // TypeQuals handled by caller. 794 Result = Context.getAutoType(QualType()); 795 break; 796 } 797 798 case DeclSpec::TST_error: 799 Result = Context.IntTy; 800 declarator.setInvalidType(true); 801 break; 802 } 803 804 // Handle complex types. 805 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 806 if (S.getLangOptions().Freestanding) 807 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 808 Result = Context.getComplexType(Result); 809 } else if (DS.isTypeAltiVecVector()) { 810 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); 811 assert(typeSize > 0 && "type size for vector must be greater than 0 bits"); 812 VectorType::VectorKind VecKind = VectorType::AltiVecVector; 813 if (DS.isTypeAltiVecPixel()) 814 VecKind = VectorType::AltiVecPixel; 815 else if (DS.isTypeAltiVecBool()) 816 VecKind = VectorType::AltiVecBool; 817 Result = Context.getVectorType(Result, 128/typeSize, VecKind); 818 } 819 820 // FIXME: Imaginary. 821 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) 822 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); 823 824 // Before we process any type attributes, synthesize a block literal 825 // function declarator if necessary. 826 if (declarator.getContext() == Declarator::BlockLiteralContext) 827 maybeSynthesizeBlockSignature(state, Result); 828 829 // Apply any type attributes from the decl spec. This may cause the 830 // list of type attributes to be temporarily saved while the type 831 // attributes are pushed around. 832 if (AttributeList *attrs = DS.getAttributes().getList()) 833 processTypeAttrs(state, Result, true, attrs); 834 835 // Apply const/volatile/restrict qualifiers to T. 836 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 837 838 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 839 // or incomplete types shall not be restrict-qualified." C++ also allows 840 // restrict-qualified references. 841 if (TypeQuals & DeclSpec::TQ_restrict) { 842 if (Result->isAnyPointerType() || Result->isReferenceType()) { 843 QualType EltTy; 844 if (Result->isObjCObjectPointerType()) 845 EltTy = Result; 846 else 847 EltTy = Result->isPointerType() ? 848 Result->getAs<PointerType>()->getPointeeType() : 849 Result->getAs<ReferenceType>()->getPointeeType(); 850 851 // If we have a pointer or reference, the pointee must have an object 852 // incomplete type. 853 if (!EltTy->isIncompleteOrObjectType()) { 854 S.Diag(DS.getRestrictSpecLoc(), 855 diag::err_typecheck_invalid_restrict_invalid_pointee) 856 << EltTy << DS.getSourceRange(); 857 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier. 858 } 859 } else { 860 S.Diag(DS.getRestrictSpecLoc(), 861 diag::err_typecheck_invalid_restrict_not_pointer) 862 << Result << DS.getSourceRange(); 863 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier. 864 } 865 } 866 867 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification 868 // of a function type includes any type qualifiers, the behavior is 869 // undefined." 870 if (Result->isFunctionType() && TypeQuals) { 871 // Get some location to point at, either the C or V location. 872 SourceLocation Loc; 873 if (TypeQuals & DeclSpec::TQ_const) 874 Loc = DS.getConstSpecLoc(); 875 else if (TypeQuals & DeclSpec::TQ_volatile) 876 Loc = DS.getVolatileSpecLoc(); 877 else { 878 assert((TypeQuals & DeclSpec::TQ_restrict) && 879 "Has CVR quals but not C, V, or R?"); 880 Loc = DS.getRestrictSpecLoc(); 881 } 882 S.Diag(Loc, diag::warn_typecheck_function_qualifiers) 883 << Result << DS.getSourceRange(); 884 } 885 886 // C++ [dcl.ref]p1: 887 // Cv-qualified references are ill-formed except when the 888 // cv-qualifiers are introduced through the use of a typedef 889 // (7.1.3) or of a template type argument (14.3), in which 890 // case the cv-qualifiers are ignored. 891 // FIXME: Shouldn't we be checking SCS_typedef here? 892 if (DS.getTypeSpecType() == DeclSpec::TST_typename && 893 TypeQuals && Result->isReferenceType()) { 894 TypeQuals &= ~DeclSpec::TQ_const; 895 TypeQuals &= ~DeclSpec::TQ_volatile; 896 } 897 898 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals); 899 Result = Context.getQualifiedType(Result, Quals); 900 } 901 902 return Result; 903} 904 905static std::string getPrintableNameForEntity(DeclarationName Entity) { 906 if (Entity) 907 return Entity.getAsString(); 908 909 return "type name"; 910} 911 912QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 913 Qualifiers Qs) { 914 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 915 // object or incomplete types shall not be restrict-qualified." 916 if (Qs.hasRestrict()) { 917 unsigned DiagID = 0; 918 QualType ProblemTy; 919 920 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr(); 921 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) { 922 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) { 923 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 924 ProblemTy = T->getAs<ReferenceType>()->getPointeeType(); 925 } 926 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) { 927 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) { 928 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 929 ProblemTy = T->getAs<PointerType>()->getPointeeType(); 930 } 931 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) { 932 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) { 933 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 934 ProblemTy = T->getAs<PointerType>()->getPointeeType(); 935 } 936 } else if (!Ty->isDependentType()) { 937 // FIXME: this deserves a proper diagnostic 938 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 939 ProblemTy = T; 940 } 941 942 if (DiagID) { 943 Diag(Loc, DiagID) << ProblemTy; 944 Qs.removeRestrict(); 945 } 946 } 947 948 return Context.getQualifiedType(T, Qs); 949} 950 951/// \brief Build a paren type including \p T. 952QualType Sema::BuildParenType(QualType T) { 953 return Context.getParenType(T); 954} 955 956/// \brief Build a pointer type. 957/// 958/// \param T The type to which we'll be building a pointer. 959/// 960/// \param Loc The location of the entity whose type involves this 961/// pointer type or, if there is no such entity, the location of the 962/// type that will have pointer type. 963/// 964/// \param Entity The name of the entity that involves the pointer 965/// type, if known. 966/// 967/// \returns A suitable pointer type, if there are no 968/// errors. Otherwise, returns a NULL type. 969QualType Sema::BuildPointerType(QualType T, 970 SourceLocation Loc, DeclarationName Entity) { 971 if (T->isReferenceType()) { 972 // C++ 8.3.2p4: There shall be no ... pointers to references ... 973 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 974 << getPrintableNameForEntity(Entity) << T; 975 return QualType(); 976 } 977 978 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType"); 979 980 // Build the pointer type. 981 return Context.getPointerType(T); 982} 983 984/// \brief Build a reference type. 985/// 986/// \param T The type to which we'll be building a reference. 987/// 988/// \param Loc The location of the entity whose type involves this 989/// reference type or, if there is no such entity, the location of the 990/// type that will have reference type. 991/// 992/// \param Entity The name of the entity that involves the reference 993/// type, if known. 994/// 995/// \returns A suitable reference type, if there are no 996/// errors. Otherwise, returns a NULL type. 997QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, 998 SourceLocation Loc, 999 DeclarationName Entity) { 1000 // C++0x [dcl.ref]p6: 1001 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a 1002 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a 1003 // type T, an attempt to create the type "lvalue reference to cv TR" creates 1004 // the type "lvalue reference to T", while an attempt to create the type 1005 // "rvalue reference to cv TR" creates the type TR. 1006 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); 1007 1008 // C++ [dcl.ref]p4: There shall be no references to references. 1009 // 1010 // According to C++ DR 106, references to references are only 1011 // diagnosed when they are written directly (e.g., "int & &"), 1012 // but not when they happen via a typedef: 1013 // 1014 // typedef int& intref; 1015 // typedef intref& intref2; 1016 // 1017 // Parser::ParseDeclaratorInternal diagnoses the case where 1018 // references are written directly; here, we handle the 1019 // collapsing of references-to-references as described in C++0x. 1020 // DR 106 and 540 introduce reference-collapsing into C++98/03. 1021 1022 // C++ [dcl.ref]p1: 1023 // A declarator that specifies the type "reference to cv void" 1024 // is ill-formed. 1025 if (T->isVoidType()) { 1026 Diag(Loc, diag::err_reference_to_void); 1027 return QualType(); 1028 } 1029 1030 // Handle restrict on references. 1031 if (LValueRef) 1032 return Context.getLValueReferenceType(T, SpelledAsLValue); 1033 return Context.getRValueReferenceType(T); 1034} 1035 1036/// \brief Build an array type. 1037/// 1038/// \param T The type of each element in the array. 1039/// 1040/// \param ASM C99 array size modifier (e.g., '*', 'static'). 1041/// 1042/// \param ArraySize Expression describing the size of the array. 1043/// 1044/// \param Loc The location of the entity whose type involves this 1045/// array type or, if there is no such entity, the location of the 1046/// type that will have array type. 1047/// 1048/// \param Entity The name of the entity that involves the array 1049/// type, if known. 1050/// 1051/// \returns A suitable array type, if there are no errors. Otherwise, 1052/// returns a NULL type. 1053QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 1054 Expr *ArraySize, unsigned Quals, 1055 SourceRange Brackets, DeclarationName Entity) { 1056 1057 SourceLocation Loc = Brackets.getBegin(); 1058 if (getLangOptions().CPlusPlus) { 1059 // C++ [dcl.array]p1: 1060 // T is called the array element type; this type shall not be a reference 1061 // type, the (possibly cv-qualified) type void, a function type or an 1062 // abstract class type. 1063 // 1064 // Note: function types are handled in the common path with C. 1065 if (T->isReferenceType()) { 1066 Diag(Loc, diag::err_illegal_decl_array_of_references) 1067 << getPrintableNameForEntity(Entity) << T; 1068 return QualType(); 1069 } 1070 1071 if (T->isVoidType()) { 1072 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; 1073 return QualType(); 1074 } 1075 1076 if (RequireNonAbstractType(Brackets.getBegin(), T, 1077 diag::err_array_of_abstract_type)) 1078 return QualType(); 1079 1080 } else { 1081 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 1082 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 1083 if (RequireCompleteType(Loc, T, 1084 diag::err_illegal_decl_array_incomplete_type)) 1085 return QualType(); 1086 } 1087 1088 if (T->isFunctionType()) { 1089 Diag(Loc, diag::err_illegal_decl_array_of_functions) 1090 << getPrintableNameForEntity(Entity) << T; 1091 return QualType(); 1092 } 1093 1094 if (T->getContainedAutoType()) { 1095 Diag(Loc, diag::err_illegal_decl_array_of_auto) 1096 << getPrintableNameForEntity(Entity) << T; 1097 return QualType(); 1098 } 1099 1100 if (const RecordType *EltTy = T->getAs<RecordType>()) { 1101 // If the element type is a struct or union that contains a variadic 1102 // array, accept it as a GNU extension: C99 6.7.2.1p2. 1103 if (EltTy->getDecl()->hasFlexibleArrayMember()) 1104 Diag(Loc, diag::ext_flexible_array_in_array) << T; 1105 } else if (T->isObjCObjectType()) { 1106 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 1107 return QualType(); 1108 } 1109 1110 // Do lvalue-to-rvalue conversions on the array size expression. 1111 if (ArraySize && !ArraySize->isRValue()) 1112 DefaultLvalueConversion(ArraySize); 1113 1114 // C99 6.7.5.2p1: The size expression shall have integer type. 1115 // TODO: in theory, if we were insane, we could allow contextual 1116 // conversions to integer type here. 1117 if (ArraySize && !ArraySize->isTypeDependent() && 1118 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 1119 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 1120 << ArraySize->getType() << ArraySize->getSourceRange(); 1121 return QualType(); 1122 } 1123 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); 1124 if (!ArraySize) { 1125 if (ASM == ArrayType::Star) 1126 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets); 1127 else 1128 T = Context.getIncompleteArrayType(T, ASM, Quals); 1129 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { 1130 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 1131 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) || 1132 (!T->isDependentType() && !T->isIncompleteType() && 1133 !T->isConstantSizeType())) { 1134 // Per C99, a variable array is an array with either a non-constant 1135 // size or an element type that has a non-constant-size 1136 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 1137 } else { 1138 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 1139 // have a value greater than zero. 1140 if (ConstVal.isSigned() && ConstVal.isNegative()) { 1141 if (Entity) 1142 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size) 1143 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange(); 1144 else 1145 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size) 1146 << ArraySize->getSourceRange(); 1147 return QualType(); 1148 } 1149 if (ConstVal == 0) { 1150 // GCC accepts zero sized static arrays. We allow them when 1151 // we're not in a SFINAE context. 1152 Diag(ArraySize->getLocStart(), 1153 isSFINAEContext()? diag::err_typecheck_zero_array_size 1154 : diag::ext_typecheck_zero_array_size) 1155 << ArraySize->getSourceRange(); 1156 } else if (!T->isDependentType() && !T->isVariablyModifiedType() && 1157 !T->isIncompleteType()) { 1158 // Is the array too large? 1159 unsigned ActiveSizeBits 1160 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal); 1161 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) 1162 Diag(ArraySize->getLocStart(), diag::err_array_too_large) 1163 << ConstVal.toString(10) 1164 << ArraySize->getSourceRange(); 1165 } 1166 1167 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); 1168 } 1169 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 1170 if (!getLangOptions().C99) { 1171 if (T->isVariableArrayType()) { 1172 // Prohibit the use of non-POD types in VLAs. 1173 if (!T->isDependentType() && 1174 !Context.getBaseElementType(T)->isPODType()) { 1175 Diag(Loc, diag::err_vla_non_pod) 1176 << Context.getBaseElementType(T); 1177 return QualType(); 1178 } 1179 // Prohibit the use of VLAs during template argument deduction. 1180 else if (isSFINAEContext()) { 1181 Diag(Loc, diag::err_vla_in_sfinae); 1182 return QualType(); 1183 } 1184 // Just extwarn about VLAs. 1185 else 1186 Diag(Loc, diag::ext_vla); 1187 } else if (ASM != ArrayType::Normal || Quals != 0) 1188 Diag(Loc, 1189 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx 1190 : diag::ext_c99_array_usage); 1191 } 1192 1193 return T; 1194} 1195 1196/// \brief Build an ext-vector type. 1197/// 1198/// Run the required checks for the extended vector type. 1199QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, 1200 SourceLocation AttrLoc) { 1201 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 1202 // in conjunction with complex types (pointers, arrays, functions, etc.). 1203 if (!T->isDependentType() && 1204 !T->isIntegerType() && !T->isRealFloatingType()) { 1205 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 1206 return QualType(); 1207 } 1208 1209 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { 1210 llvm::APSInt vecSize(32); 1211 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { 1212 Diag(AttrLoc, diag::err_attribute_argument_not_int) 1213 << "ext_vector_type" << ArraySize->getSourceRange(); 1214 return QualType(); 1215 } 1216 1217 // unlike gcc's vector_size attribute, the size is specified as the 1218 // number of elements, not the number of bytes. 1219 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 1220 1221 if (vectorSize == 0) { 1222 Diag(AttrLoc, diag::err_attribute_zero_size) 1223 << ArraySize->getSourceRange(); 1224 return QualType(); 1225 } 1226 1227 if (!T->isDependentType()) 1228 return Context.getExtVectorType(T, vectorSize); 1229 } 1230 1231 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); 1232} 1233 1234/// \brief Build a function type. 1235/// 1236/// This routine checks the function type according to C++ rules and 1237/// under the assumption that the result type and parameter types have 1238/// just been instantiated from a template. It therefore duplicates 1239/// some of the behavior of GetTypeForDeclarator, but in a much 1240/// simpler form that is only suitable for this narrow use case. 1241/// 1242/// \param T The return type of the function. 1243/// 1244/// \param ParamTypes The parameter types of the function. This array 1245/// will be modified to account for adjustments to the types of the 1246/// function parameters. 1247/// 1248/// \param NumParamTypes The number of parameter types in ParamTypes. 1249/// 1250/// \param Variadic Whether this is a variadic function type. 1251/// 1252/// \param Quals The cvr-qualifiers to be applied to the function type. 1253/// 1254/// \param Loc The location of the entity whose type involves this 1255/// function type or, if there is no such entity, the location of the 1256/// type that will have function type. 1257/// 1258/// \param Entity The name of the entity that involves the function 1259/// type, if known. 1260/// 1261/// \returns A suitable function type, if there are no 1262/// errors. Otherwise, returns a NULL type. 1263QualType Sema::BuildFunctionType(QualType T, 1264 QualType *ParamTypes, 1265 unsigned NumParamTypes, 1266 bool Variadic, unsigned Quals, 1267 RefQualifierKind RefQualifier, 1268 SourceLocation Loc, DeclarationName Entity, 1269 FunctionType::ExtInfo Info) { 1270 if (T->isArrayType() || T->isFunctionType()) { 1271 Diag(Loc, diag::err_func_returning_array_function) 1272 << T->isFunctionType() << T; 1273 return QualType(); 1274 } 1275 1276 bool Invalid = false; 1277 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) { 1278 QualType ParamType = adjustParameterType(ParamTypes[Idx]); 1279 if (ParamType->isVoidType()) { 1280 Diag(Loc, diag::err_param_with_void_type); 1281 Invalid = true; 1282 } 1283 1284 ParamTypes[Idx] = ParamType; 1285 } 1286 1287 if (Invalid) 1288 return QualType(); 1289 1290 FunctionProtoType::ExtProtoInfo EPI; 1291 EPI.Variadic = Variadic; 1292 EPI.TypeQuals = Quals; 1293 EPI.RefQualifier = RefQualifier; 1294 EPI.ExtInfo = Info; 1295 1296 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI); 1297} 1298 1299/// \brief Build a member pointer type \c T Class::*. 1300/// 1301/// \param T the type to which the member pointer refers. 1302/// \param Class the class type into which the member pointer points. 1303/// \param CVR Qualifiers applied to the member pointer type 1304/// \param Loc the location where this type begins 1305/// \param Entity the name of the entity that will have this member pointer type 1306/// 1307/// \returns a member pointer type, if successful, or a NULL type if there was 1308/// an error. 1309QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 1310 SourceLocation Loc, 1311 DeclarationName Entity) { 1312 // Verify that we're not building a pointer to pointer to function with 1313 // exception specification. 1314 if (CheckDistantExceptionSpec(T)) { 1315 Diag(Loc, diag::err_distant_exception_spec); 1316 1317 // FIXME: If we're doing this as part of template instantiation, 1318 // we should return immediately. 1319 1320 // Build the type anyway, but use the canonical type so that the 1321 // exception specifiers are stripped off. 1322 T = Context.getCanonicalType(T); 1323 } 1324 1325 // C++ 8.3.3p3: A pointer to member shall not point to ... a member 1326 // with reference type, or "cv void." 1327 if (T->isReferenceType()) { 1328 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 1329 << (Entity? Entity.getAsString() : "type name") << T; 1330 return QualType(); 1331 } 1332 1333 if (T->isVoidType()) { 1334 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 1335 << (Entity? Entity.getAsString() : "type name"); 1336 return QualType(); 1337 } 1338 1339 if (!Class->isDependentType() && !Class->isRecordType()) { 1340 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 1341 return QualType(); 1342 } 1343 1344 // In the Microsoft ABI, the class is allowed to be an incomplete 1345 // type. In such cases, the compiler makes a worst-case assumption. 1346 // We make no such assumption right now, so emit an error if the 1347 // class isn't a complete type. 1348 if (Context.Target.getCXXABI() == CXXABI_Microsoft && 1349 RequireCompleteType(Loc, Class, diag::err_incomplete_type)) 1350 return QualType(); 1351 1352 return Context.getMemberPointerType(T, Class.getTypePtr()); 1353} 1354 1355/// \brief Build a block pointer type. 1356/// 1357/// \param T The type to which we'll be building a block pointer. 1358/// 1359/// \param CVR The cvr-qualifiers to be applied to the block pointer type. 1360/// 1361/// \param Loc The location of the entity whose type involves this 1362/// block pointer type or, if there is no such entity, the location of the 1363/// type that will have block pointer type. 1364/// 1365/// \param Entity The name of the entity that involves the block pointer 1366/// type, if known. 1367/// 1368/// \returns A suitable block pointer type, if there are no 1369/// errors. Otherwise, returns a NULL type. 1370QualType Sema::BuildBlockPointerType(QualType T, 1371 SourceLocation Loc, 1372 DeclarationName Entity) { 1373 if (!T->isFunctionType()) { 1374 Diag(Loc, diag::err_nonfunction_block_type); 1375 return QualType(); 1376 } 1377 1378 return Context.getBlockPointerType(T); 1379} 1380 1381QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { 1382 QualType QT = Ty.get(); 1383 if (QT.isNull()) { 1384 if (TInfo) *TInfo = 0; 1385 return QualType(); 1386 } 1387 1388 TypeSourceInfo *DI = 0; 1389 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 1390 QT = LIT->getType(); 1391 DI = LIT->getTypeSourceInfo(); 1392 } 1393 1394 if (TInfo) *TInfo = DI; 1395 return QT; 1396} 1397 1398static void DiagnoseIgnoredQualifiers(unsigned Quals, 1399 SourceLocation ConstQualLoc, 1400 SourceLocation VolatileQualLoc, 1401 SourceLocation RestrictQualLoc, 1402 Sema& S) { 1403 std::string QualStr; 1404 unsigned NumQuals = 0; 1405 SourceLocation Loc; 1406 1407 FixItHint ConstFixIt; 1408 FixItHint VolatileFixIt; 1409 FixItHint RestrictFixIt; 1410 1411 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to 1412 // find a range and grow it to encompass all the qualifiers, regardless of 1413 // the order in which they textually appear. 1414 if (Quals & Qualifiers::Const) { 1415 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc); 1416 Loc = ConstQualLoc; 1417 ++NumQuals; 1418 QualStr = "const"; 1419 } 1420 if (Quals & Qualifiers::Volatile) { 1421 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc); 1422 if (NumQuals == 0) { 1423 Loc = VolatileQualLoc; 1424 QualStr = "volatile"; 1425 } else { 1426 QualStr += " volatile"; 1427 } 1428 ++NumQuals; 1429 } 1430 if (Quals & Qualifiers::Restrict) { 1431 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc); 1432 if (NumQuals == 0) { 1433 Loc = RestrictQualLoc; 1434 QualStr = "restrict"; 1435 } else { 1436 QualStr += " restrict"; 1437 } 1438 ++NumQuals; 1439 } 1440 1441 assert(NumQuals > 0 && "No known qualifiers?"); 1442 1443 S.Diag(Loc, diag::warn_qual_return_type) 1444 << QualStr << NumQuals 1445 << ConstFixIt << VolatileFixIt << RestrictFixIt; 1446} 1447 1448/// GetTypeForDeclarator - Convert the type for the specified 1449/// declarator to Type instances. 1450/// 1451/// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq 1452/// owns the declaration of a type (e.g., the definition of a struct 1453/// type), then *OwnedDecl will receive the owned declaration. 1454/// 1455/// The result of this call will never be null, but the associated 1456/// type may be a null type if there's an unrecoverable error. 1457TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S, 1458 TagDecl **OwnedDecl, 1459 bool AutoAllowedInTypeName) { 1460 // Determine the type of the declarator. Not all forms of declarator 1461 // have a type. 1462 QualType T; 1463 TypeSourceInfo *ReturnTypeInfo = 0; 1464 1465 TypeProcessingState state(*this, D); 1466 1467 switch (D.getName().getKind()) { 1468 case UnqualifiedId::IK_Identifier: 1469 case UnqualifiedId::IK_OperatorFunctionId: 1470 case UnqualifiedId::IK_LiteralOperatorId: 1471 case UnqualifiedId::IK_TemplateId: 1472 T = ConvertDeclSpecToType(*this, state); 1473 1474 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 1475 TagDecl* Owned = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 1476 // Owned is embedded if it was defined here, or if it is the 1477 // very first (i.e., canonical) declaration of this tag type. 1478 Owned->setEmbeddedInDeclarator(Owned->isDefinition() || 1479 Owned->isCanonicalDecl()); 1480 if (OwnedDecl) *OwnedDecl = Owned; 1481 } 1482 break; 1483 1484 case UnqualifiedId::IK_ConstructorName: 1485 case UnqualifiedId::IK_ConstructorTemplateId: 1486 case UnqualifiedId::IK_DestructorName: 1487 // Constructors and destructors don't have return types. Use 1488 // "void" instead. 1489 T = Context.VoidTy; 1490 break; 1491 1492 case UnqualifiedId::IK_ConversionFunctionId: 1493 // The result type of a conversion function is the type that it 1494 // converts to. 1495 T = GetTypeFromParser(D.getName().ConversionFunctionId, 1496 &ReturnTypeInfo); 1497 break; 1498 } 1499 1500 if (D.getAttributes()) 1501 distributeTypeAttrsFromDeclarator(state, T); 1502 1503 // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. 1504 // In C++0x, a function declarator using 'auto' must have a trailing return 1505 // type (this is checked later) and we can skip this. In other languages 1506 // using auto, we need to check regardless. 1507 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 1508 (!getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())) { 1509 int Error = -1; 1510 1511 switch (D.getContext()) { 1512 case Declarator::KNRTypeListContext: 1513 assert(0 && "K&R type lists aren't allowed in C++"); 1514 break; 1515 case Declarator::PrototypeContext: 1516 Error = 0; // Function prototype 1517 break; 1518 case Declarator::MemberContext: 1519 switch (cast<TagDecl>(CurContext)->getTagKind()) { 1520 case TTK_Enum: assert(0 && "unhandled tag kind"); break; 1521 case TTK_Struct: Error = 1; /* Struct member */ break; 1522 case TTK_Union: Error = 2; /* Union member */ break; 1523 case TTK_Class: Error = 3; /* Class member */ break; 1524 } 1525 break; 1526 case Declarator::CXXCatchContext: 1527 Error = 4; // Exception declaration 1528 break; 1529 case Declarator::TemplateParamContext: 1530 Error = 5; // Template parameter 1531 break; 1532 case Declarator::BlockLiteralContext: 1533 Error = 6; // Block literal 1534 break; 1535 case Declarator::TemplateTypeArgContext: 1536 Error = 7; // Template type argument 1537 break; 1538 case Declarator::TypeNameContext: 1539 if (!AutoAllowedInTypeName) 1540 Error = 10; // Generic 1541 break; 1542 case Declarator::FileContext: 1543 case Declarator::BlockContext: 1544 case Declarator::ForContext: 1545 case Declarator::ConditionContext: 1546 break; 1547 } 1548 1549 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 1550 Error = 8; 1551 1552 // In Objective-C it is an error to use 'auto' on a function declarator. 1553 if (D.isFunctionDeclarator()) 1554 Error = 9; 1555 1556 // C++0x [dcl.spec.auto]p2: 'auto' is always fine if the declarator 1557 // contains a trailing return type. That is only legal at the outermost 1558 // level. Check all declarator chunks (outermost first) anyway, to give 1559 // better diagnostics. 1560 if (getLangOptions().CPlusPlus0x && Error != -1) { 1561 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 1562 unsigned chunkIndex = e - i - 1; 1563 state.setCurrentChunkIndex(chunkIndex); 1564 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 1565 if (DeclType.Kind == DeclaratorChunk::Function) { 1566 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 1567 if (FTI.TrailingReturnType) { 1568 Error = -1; 1569 break; 1570 } 1571 } 1572 } 1573 } 1574 1575 if (Error != -1) { 1576 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed) 1577 << Error; 1578 T = Context.IntTy; 1579 D.setInvalidType(true); 1580 } 1581 } 1582 1583 if (T.isNull()) 1584 return Context.getNullTypeSourceInfo(); 1585 1586 // The name we're declaring, if any. 1587 DeclarationName Name; 1588 if (D.getIdentifier()) 1589 Name = D.getIdentifier(); 1590 1591 // Walk the DeclTypeInfo, building the recursive type as we go. 1592 // DeclTypeInfos are ordered from the identifier out, which is 1593 // opposite of what we want :). 1594 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 1595 unsigned chunkIndex = e - i - 1; 1596 state.setCurrentChunkIndex(chunkIndex); 1597 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 1598 switch (DeclType.Kind) { 1599 default: assert(0 && "Unknown decltype!"); 1600 case DeclaratorChunk::Paren: 1601 T = BuildParenType(T); 1602 break; 1603 case DeclaratorChunk::BlockPointer: 1604 // If blocks are disabled, emit an error. 1605 if (!LangOpts.Blocks) 1606 Diag(DeclType.Loc, diag::err_blocks_disable); 1607 1608 T = BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 1609 if (DeclType.Cls.TypeQuals) 1610 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 1611 break; 1612 case DeclaratorChunk::Pointer: 1613 // Verify that we're not building a pointer to pointer to function with 1614 // exception specification. 1615 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1616 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1617 D.setInvalidType(true); 1618 // Build the type anyway. 1619 } 1620 if (getLangOptions().ObjC1 && T->getAs<ObjCObjectType>()) { 1621 T = Context.getObjCObjectPointerType(T); 1622 if (DeclType.Ptr.TypeQuals) 1623 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 1624 break; 1625 } 1626 T = BuildPointerType(T, DeclType.Loc, Name); 1627 if (DeclType.Ptr.TypeQuals) 1628 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 1629 1630 break; 1631 case DeclaratorChunk::Reference: { 1632 // Verify that we're not building a reference to pointer to function with 1633 // exception specification. 1634 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1635 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1636 D.setInvalidType(true); 1637 // Build the type anyway. 1638 } 1639 T = BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 1640 1641 Qualifiers Quals; 1642 if (DeclType.Ref.HasRestrict) 1643 T = BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 1644 break; 1645 } 1646 case DeclaratorChunk::Array: { 1647 // Verify that we're not building an array of pointers to function with 1648 // exception specification. 1649 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1650 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1651 D.setInvalidType(true); 1652 // Build the type anyway. 1653 } 1654 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 1655 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 1656 ArrayType::ArraySizeModifier ASM; 1657 if (ATI.isStar) 1658 ASM = ArrayType::Star; 1659 else if (ATI.hasStatic) 1660 ASM = ArrayType::Static; 1661 else 1662 ASM = ArrayType::Normal; 1663 if (ASM == ArrayType::Star && 1664 D.getContext() != Declarator::PrototypeContext) { 1665 // FIXME: This check isn't quite right: it allows star in prototypes 1666 // for function definitions, and disallows some edge cases detailed 1667 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 1668 Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 1669 ASM = ArrayType::Normal; 1670 D.setInvalidType(true); 1671 } 1672 T = BuildArrayType(T, ASM, ArraySize, 1673 Qualifiers::fromCVRMask(ATI.TypeQuals), 1674 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 1675 break; 1676 } 1677 case DeclaratorChunk::Function: { 1678 // If the function declarator has a prototype (i.e. it is not () and 1679 // does not have a K&R-style identifier list), then the arguments are part 1680 // of the type, otherwise the argument list is (). 1681 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 1682 1683 // Check for auto functions and trailing return type and adjust the 1684 // return type accordingly. 1685 if (!D.isInvalidType()) { 1686 // trailing-return-type is only required if we're declaring a function, 1687 // and not, for instance, a pointer to a function. 1688 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 1689 !FTI.TrailingReturnType && chunkIndex == 0) { 1690 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 1691 diag::err_auto_missing_trailing_return); 1692 T = Context.IntTy; 1693 D.setInvalidType(true); 1694 } else if (FTI.TrailingReturnType) { 1695 // T must be exactly 'auto' at this point. See CWG issue 681. 1696 if (isa<ParenType>(T)) { 1697 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 1698 diag::err_trailing_return_in_parens) 1699 << T << D.getDeclSpec().getSourceRange(); 1700 D.setInvalidType(true); 1701 } else if (T.hasQualifiers() || !isa<AutoType>(T)) { 1702 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 1703 diag::err_trailing_return_without_auto) 1704 << T << D.getDeclSpec().getSourceRange(); 1705 D.setInvalidType(true); 1706 } 1707 1708 T = GetTypeFromParser( 1709 ParsedType::getFromOpaquePtr(FTI.TrailingReturnType), 1710 &ReturnTypeInfo); 1711 } 1712 } 1713 1714 // C99 6.7.5.3p1: The return type may not be a function or array type. 1715 // For conversion functions, we'll diagnose this particular error later. 1716 if ((T->isArrayType() || T->isFunctionType()) && 1717 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 1718 unsigned diagID = diag::err_func_returning_array_function; 1719 // Last processing chunk in block context means this function chunk 1720 // represents the block. 1721 if (chunkIndex == 0 && 1722 D.getContext() == Declarator::BlockLiteralContext) 1723 diagID = diag::err_block_returning_array_function; 1724 Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 1725 T = Context.IntTy; 1726 D.setInvalidType(true); 1727 } 1728 1729 // cv-qualifiers on return types are pointless except when the type is a 1730 // class type in C++. 1731 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() && 1732 (!getLangOptions().CPlusPlus || !T->isDependentType())) { 1733 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?"); 1734 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 1735 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer); 1736 1737 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr; 1738 1739 DiagnoseIgnoredQualifiers(PTI.TypeQuals, 1740 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), 1741 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), 1742 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), 1743 *this); 1744 1745 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() && 1746 (!getLangOptions().CPlusPlus || 1747 (!T->isDependentType() && !T->isRecordType()))) { 1748 1749 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(), 1750 D.getDeclSpec().getConstSpecLoc(), 1751 D.getDeclSpec().getVolatileSpecLoc(), 1752 D.getDeclSpec().getRestrictSpecLoc(), 1753 *this); 1754 } 1755 1756 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) { 1757 // C++ [dcl.fct]p6: 1758 // Types shall not be defined in return or parameter types. 1759 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 1760 if (Tag->isDefinition()) 1761 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 1762 << Context.getTypeDeclType(Tag); 1763 } 1764 1765 // Exception specs are not allowed in typedefs. Complain, but add it 1766 // anyway. 1767 if (FTI.getExceptionSpecType() != EST_None && 1768 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 1769 Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef); 1770 1771 if (!FTI.NumArgs && !FTI.isVariadic && !getLangOptions().CPlusPlus) { 1772 // Simple void foo(), where the incoming T is the result type. 1773 T = Context.getFunctionNoProtoType(T); 1774 } else { 1775 // We allow a zero-parameter variadic function in C if the 1776 // function is marked with the "overloadable" attribute. Scan 1777 // for this attribute now. 1778 if (!FTI.NumArgs && FTI.isVariadic && !getLangOptions().CPlusPlus) { 1779 bool Overloadable = false; 1780 for (const AttributeList *Attrs = D.getAttributes(); 1781 Attrs; Attrs = Attrs->getNext()) { 1782 if (Attrs->getKind() == AttributeList::AT_overloadable) { 1783 Overloadable = true; 1784 break; 1785 } 1786 } 1787 1788 if (!Overloadable) 1789 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); 1790 } 1791 1792 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) { 1793 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 1794 // definition. 1795 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 1796 D.setInvalidType(true); 1797 break; 1798 } 1799 1800 FunctionProtoType::ExtProtoInfo EPI; 1801 EPI.Variadic = FTI.isVariadic; 1802 EPI.TypeQuals = FTI.TypeQuals; 1803 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 1804 : FTI.RefQualifierIsLValueRef? RQ_LValue 1805 : RQ_RValue; 1806 1807 // Otherwise, we have a function with an argument list that is 1808 // potentially variadic. 1809 llvm::SmallVector<QualType, 16> ArgTys; 1810 ArgTys.reserve(FTI.NumArgs); 1811 1812 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 1813 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 1814 QualType ArgTy = Param->getType(); 1815 assert(!ArgTy.isNull() && "Couldn't parse type?"); 1816 1817 // Adjust the parameter type. 1818 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?"); 1819 1820 // Look for 'void'. void is allowed only as a single argument to a 1821 // function with no other parameters (C99 6.7.5.3p10). We record 1822 // int(void) as a FunctionProtoType with an empty argument list. 1823 if (ArgTy->isVoidType()) { 1824 // If this is something like 'float(int, void)', reject it. 'void' 1825 // is an incomplete type (C99 6.2.5p19) and function decls cannot 1826 // have arguments of incomplete type. 1827 if (FTI.NumArgs != 1 || FTI.isVariadic) { 1828 Diag(DeclType.Loc, diag::err_void_only_param); 1829 ArgTy = Context.IntTy; 1830 Param->setType(ArgTy); 1831 } else if (FTI.ArgInfo[i].Ident) { 1832 // Reject, but continue to parse 'int(void abc)'. 1833 Diag(FTI.ArgInfo[i].IdentLoc, 1834 diag::err_param_with_void_type); 1835 ArgTy = Context.IntTy; 1836 Param->setType(ArgTy); 1837 } else { 1838 // Reject, but continue to parse 'float(const void)'. 1839 if (ArgTy.hasQualifiers()) 1840 Diag(DeclType.Loc, diag::err_void_param_qualified); 1841 1842 // Do not add 'void' to the ArgTys list. 1843 break; 1844 } 1845 } else if (!FTI.hasPrototype) { 1846 if (ArgTy->isPromotableIntegerType()) { 1847 ArgTy = Context.getPromotedIntegerType(ArgTy); 1848 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) { 1849 if (BTy->getKind() == BuiltinType::Float) 1850 ArgTy = Context.DoubleTy; 1851 } 1852 } 1853 1854 ArgTys.push_back(ArgTy); 1855 } 1856 1857 llvm::SmallVector<QualType, 4> Exceptions; 1858 EPI.ExceptionSpecType = FTI.getExceptionSpecType(); 1859 if (FTI.getExceptionSpecType() == EST_Dynamic) { 1860 Exceptions.reserve(FTI.NumExceptions); 1861 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) { 1862 // FIXME: Preserve type source info. 1863 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty); 1864 // Check that the type is valid for an exception spec, and 1865 // drop it if not. 1866 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range)) 1867 Exceptions.push_back(ET); 1868 } 1869 EPI.NumExceptions = Exceptions.size(); 1870 EPI.Exceptions = Exceptions.data(); 1871 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 1872 EPI.NoexceptExpr = FTI.NoexceptExpr; 1873 } 1874 1875 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI); 1876 } 1877 1878 break; 1879 } 1880 case DeclaratorChunk::MemberPointer: 1881 // The scope spec must refer to a class, or be dependent. 1882 CXXScopeSpec &SS = DeclType.Mem.Scope(); 1883 QualType ClsType; 1884 if (SS.isInvalid()) { 1885 // Avoid emitting extra errors if we already errored on the scope. 1886 D.setInvalidType(true); 1887 } else if (isDependentScopeSpecifier(SS) || 1888 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS))) { 1889 NestedNameSpecifier *NNS 1890 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1891 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 1892 switch (NNS->getKind()) { 1893 case NestedNameSpecifier::Identifier: 1894 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 1895 NNS->getAsIdentifier()); 1896 break; 1897 1898 case NestedNameSpecifier::Namespace: 1899 case NestedNameSpecifier::NamespaceAlias: 1900 case NestedNameSpecifier::Global: 1901 llvm_unreachable("Nested-name-specifier must name a type"); 1902 break; 1903 1904 case NestedNameSpecifier::TypeSpec: 1905 case NestedNameSpecifier::TypeSpecWithTemplate: 1906 ClsType = QualType(NNS->getAsType(), 0); 1907 // Note: if NNS is dependent, then its prefix (if any) is already 1908 // included in ClsType; this does not hold if the NNS is 1909 // nondependent: in this case (if there is indeed a prefix) 1910 // ClsType needs to be wrapped into an elaborated type. 1911 if (NNSPrefix && !NNS->isDependent()) 1912 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 1913 break; 1914 } 1915 } else { 1916 Diag(DeclType.Mem.Scope().getBeginLoc(), 1917 diag::err_illegal_decl_mempointer_in_nonclass) 1918 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 1919 << DeclType.Mem.Scope().getRange(); 1920 D.setInvalidType(true); 1921 } 1922 1923 if (!ClsType.isNull()) 1924 T = BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier()); 1925 if (T.isNull()) { 1926 T = Context.IntTy; 1927 D.setInvalidType(true); 1928 } else if (DeclType.Mem.TypeQuals) { 1929 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 1930 } 1931 break; 1932 } 1933 1934 if (T.isNull()) { 1935 D.setInvalidType(true); 1936 T = Context.IntTy; 1937 } 1938 1939 // See if there are any attributes on this declarator chunk. 1940 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs())) 1941 processTypeAttrs(state, T, false, attrs); 1942 } 1943 1944 if (getLangOptions().CPlusPlus && T->isFunctionType()) { 1945 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 1946 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 1947 1948 // C++ 8.3.5p4: 1949 // A cv-qualifier-seq shall only be part of the function type 1950 // for a nonstatic member function, the function type to which a pointer 1951 // to member refers, or the top-level function type of a function typedef 1952 // declaration. 1953 // 1954 // Core issue 547 also allows cv-qualifiers on function types that are 1955 // top-level template type arguments. 1956 bool FreeFunction; 1957 if (!D.getCXXScopeSpec().isSet()) { 1958 FreeFunction = (D.getContext() != Declarator::MemberContext || 1959 D.getDeclSpec().isFriendSpecified()); 1960 } else { 1961 DeclContext *DC = computeDeclContext(D.getCXXScopeSpec()); 1962 FreeFunction = (DC && !DC->isRecord()); 1963 } 1964 1965 // C++0x [dcl.fct]p6: 1966 // A ref-qualifier shall only be part of the function type for a 1967 // non-static member function, the function type to which a pointer to 1968 // member refers, or the top-level function type of a function typedef 1969 // declaration. 1970 if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) && 1971 !(D.getContext() == Declarator::TemplateTypeArgContext && 1972 !D.isFunctionDeclarator()) && 1973 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 1974 (FreeFunction || 1975 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) { 1976 if (D.getContext() == Declarator::TemplateTypeArgContext) { 1977 // Accept qualified function types as template type arguments as a GNU 1978 // extension. This is also the subject of C++ core issue 547. 1979 std::string Quals; 1980 if (FnTy->getTypeQuals() != 0) 1981 Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString(); 1982 1983 switch (FnTy->getRefQualifier()) { 1984 case RQ_None: 1985 break; 1986 1987 case RQ_LValue: 1988 if (!Quals.empty()) 1989 Quals += ' '; 1990 Quals += '&'; 1991 break; 1992 1993 case RQ_RValue: 1994 if (!Quals.empty()) 1995 Quals += ' '; 1996 Quals += "&&"; 1997 break; 1998 } 1999 2000 Diag(D.getIdentifierLoc(), 2001 diag::ext_qualified_function_type_template_arg) 2002 << Quals; 2003 } else { 2004 if (FnTy->getTypeQuals() != 0) { 2005 if (D.isFunctionDeclarator()) 2006 Diag(D.getIdentifierLoc(), 2007 diag::err_invalid_qualified_function_type); 2008 else 2009 Diag(D.getIdentifierLoc(), 2010 diag::err_invalid_qualified_typedef_function_type_use) 2011 << FreeFunction; 2012 } 2013 2014 if (FnTy->getRefQualifier()) { 2015 if (D.isFunctionDeclarator()) { 2016 SourceLocation Loc = D.getIdentifierLoc(); 2017 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) { 2018 const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1); 2019 if (Chunk.Kind == DeclaratorChunk::Function && 2020 Chunk.Fun.hasRefQualifier()) { 2021 Loc = Chunk.Fun.getRefQualifierLoc(); 2022 break; 2023 } 2024 } 2025 2026 Diag(Loc, diag::err_invalid_ref_qualifier_function_type) 2027 << (FnTy->getRefQualifier() == RQ_LValue) 2028 << FixItHint::CreateRemoval(Loc); 2029 } else { 2030 Diag(D.getIdentifierLoc(), 2031 diag::err_invalid_ref_qualifier_typedef_function_type_use) 2032 << FreeFunction 2033 << (FnTy->getRefQualifier() == RQ_LValue); 2034 } 2035 } 2036 2037 // Strip the cv-qualifiers and ref-qualifiers from the type. 2038 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 2039 EPI.TypeQuals = 0; 2040 EPI.RefQualifier = RQ_None; 2041 2042 T = Context.getFunctionType(FnTy->getResultType(), 2043 FnTy->arg_type_begin(), 2044 FnTy->getNumArgs(), EPI); 2045 } 2046 } 2047 } 2048 2049 // Apply any undistributed attributes from the declarator. 2050 if (!T.isNull()) 2051 if (AttributeList *attrs = D.getAttributes()) 2052 processTypeAttrs(state, T, false, attrs); 2053 2054 // Diagnose any ignored type attributes. 2055 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T); 2056 2057 // If there's a constexpr specifier, treat it as a top-level const. 2058 if (D.getDeclSpec().isConstexprSpecified()) { 2059 T.addConst(); 2060 } 2061 2062 // If there was an ellipsis in the declarator, the declaration declares a 2063 // parameter pack whose type may be a pack expansion type. 2064 if (D.hasEllipsis() && !T.isNull()) { 2065 // C++0x [dcl.fct]p13: 2066 // A declarator-id or abstract-declarator containing an ellipsis shall 2067 // only be used in a parameter-declaration. Such a parameter-declaration 2068 // is a parameter pack (14.5.3). [...] 2069 switch (D.getContext()) { 2070 case Declarator::PrototypeContext: 2071 // C++0x [dcl.fct]p13: 2072 // [...] When it is part of a parameter-declaration-clause, the 2073 // parameter pack is a function parameter pack (14.5.3). The type T 2074 // of the declarator-id of the function parameter pack shall contain 2075 // a template parameter pack; each template parameter pack in T is 2076 // expanded by the function parameter pack. 2077 // 2078 // We represent function parameter packs as function parameters whose 2079 // type is a pack expansion. 2080 if (!T->containsUnexpandedParameterPack()) { 2081 Diag(D.getEllipsisLoc(), 2082 diag::err_function_parameter_pack_without_parameter_packs) 2083 << T << D.getSourceRange(); 2084 D.setEllipsisLoc(SourceLocation()); 2085 } else { 2086 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>()); 2087 } 2088 break; 2089 2090 case Declarator::TemplateParamContext: 2091 // C++0x [temp.param]p15: 2092 // If a template-parameter is a [...] is a parameter-declaration that 2093 // declares a parameter pack (8.3.5), then the template-parameter is a 2094 // template parameter pack (14.5.3). 2095 // 2096 // Note: core issue 778 clarifies that, if there are any unexpanded 2097 // parameter packs in the type of the non-type template parameter, then 2098 // it expands those parameter packs. 2099 if (T->containsUnexpandedParameterPack()) 2100 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>()); 2101 else if (!getLangOptions().CPlusPlus0x) 2102 Diag(D.getEllipsisLoc(), diag::ext_variadic_templates); 2103 break; 2104 2105 case Declarator::FileContext: 2106 case Declarator::KNRTypeListContext: 2107 case Declarator::TypeNameContext: 2108 case Declarator::MemberContext: 2109 case Declarator::BlockContext: 2110 case Declarator::ForContext: 2111 case Declarator::ConditionContext: 2112 case Declarator::CXXCatchContext: 2113 case Declarator::BlockLiteralContext: 2114 case Declarator::TemplateTypeArgContext: 2115 // FIXME: We may want to allow parameter packs in block-literal contexts 2116 // in the future. 2117 Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter); 2118 D.setEllipsisLoc(SourceLocation()); 2119 break; 2120 } 2121 } 2122 2123 if (T.isNull()) 2124 return Context.getNullTypeSourceInfo(); 2125 else if (D.isInvalidType()) 2126 return Context.getTrivialTypeSourceInfo(T); 2127 return GetTypeSourceInfoForDeclarator(D, T, ReturnTypeInfo); 2128} 2129 2130/// Map an AttributedType::Kind to an AttributeList::Kind. 2131static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 2132 switch (kind) { 2133 case AttributedType::attr_address_space: 2134 return AttributeList::AT_address_space; 2135 case AttributedType::attr_regparm: 2136 return AttributeList::AT_regparm; 2137 case AttributedType::attr_vector_size: 2138 return AttributeList::AT_vector_size; 2139 case AttributedType::attr_neon_vector_type: 2140 return AttributeList::AT_neon_vector_type; 2141 case AttributedType::attr_neon_polyvector_type: 2142 return AttributeList::AT_neon_polyvector_type; 2143 case AttributedType::attr_objc_gc: 2144 return AttributeList::AT_objc_gc; 2145 case AttributedType::attr_noreturn: 2146 return AttributeList::AT_noreturn; 2147 case AttributedType::attr_cdecl: 2148 return AttributeList::AT_cdecl; 2149 case AttributedType::attr_fastcall: 2150 return AttributeList::AT_fastcall; 2151 case AttributedType::attr_stdcall: 2152 return AttributeList::AT_stdcall; 2153 case AttributedType::attr_thiscall: 2154 return AttributeList::AT_thiscall; 2155 case AttributedType::attr_pascal: 2156 return AttributeList::AT_pascal; 2157 } 2158 llvm_unreachable("unexpected attribute kind!"); 2159 return AttributeList::Kind(); 2160} 2161 2162static void fillAttributedTypeLoc(AttributedTypeLoc TL, 2163 const AttributeList *attrs) { 2164 AttributedType::Kind kind = TL.getAttrKind(); 2165 2166 assert(attrs && "no type attributes in the expected location!"); 2167 AttributeList::Kind parsedKind = getAttrListKind(kind); 2168 while (attrs->getKind() != parsedKind) { 2169 attrs = attrs->getNext(); 2170 assert(attrs && "no matching attribute in expected location!"); 2171 } 2172 2173 TL.setAttrNameLoc(attrs->getLoc()); 2174 if (TL.hasAttrExprOperand()) 2175 TL.setAttrExprOperand(attrs->getArg(0)); 2176 else if (TL.hasAttrEnumOperand()) 2177 TL.setAttrEnumOperandLoc(attrs->getParameterLoc()); 2178 2179 // FIXME: preserve this information to here. 2180 if (TL.hasAttrOperand()) 2181 TL.setAttrOperandParensRange(SourceRange()); 2182} 2183 2184namespace { 2185 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 2186 ASTContext &Context; 2187 const DeclSpec &DS; 2188 2189 public: 2190 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 2191 : Context(Context), DS(DS) {} 2192 2193 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 2194 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 2195 Visit(TL.getModifiedLoc()); 2196 } 2197 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 2198 Visit(TL.getUnqualifiedLoc()); 2199 } 2200 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 2201 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 2202 } 2203 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 2204 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 2205 } 2206 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 2207 // Handle the base type, which might not have been written explicitly. 2208 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { 2209 TL.setHasBaseTypeAsWritten(false); 2210 TL.getBaseLoc().initialize(Context, SourceLocation()); 2211 } else { 2212 TL.setHasBaseTypeAsWritten(true); 2213 Visit(TL.getBaseLoc()); 2214 } 2215 2216 // Protocol qualifiers. 2217 if (DS.getProtocolQualifiers()) { 2218 assert(TL.getNumProtocols() > 0); 2219 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers()); 2220 TL.setLAngleLoc(DS.getProtocolLAngleLoc()); 2221 TL.setRAngleLoc(DS.getSourceRange().getEnd()); 2222 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i) 2223 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]); 2224 } else { 2225 assert(TL.getNumProtocols() == 0); 2226 TL.setLAngleLoc(SourceLocation()); 2227 TL.setRAngleLoc(SourceLocation()); 2228 } 2229 } 2230 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 2231 TL.setStarLoc(SourceLocation()); 2232 Visit(TL.getPointeeLoc()); 2233 } 2234 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 2235 TypeSourceInfo *TInfo = 0; 2236 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 2237 2238 // If we got no declarator info from previous Sema routines, 2239 // just fill with the typespec loc. 2240 if (!TInfo) { 2241 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 2242 return; 2243 } 2244 2245 TypeLoc OldTL = TInfo->getTypeLoc(); 2246 if (TInfo->getType()->getAs<ElaboratedType>()) { 2247 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL); 2248 TemplateSpecializationTypeLoc NamedTL = 2249 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc()); 2250 TL.copy(NamedTL); 2251 } 2252 else 2253 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL)); 2254 } 2255 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 2256 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 2257 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 2258 TL.setParensRange(DS.getTypeofParensRange()); 2259 } 2260 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 2261 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 2262 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 2263 TL.setParensRange(DS.getTypeofParensRange()); 2264 assert(DS.getRepAsType()); 2265 TypeSourceInfo *TInfo = 0; 2266 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 2267 TL.setUnderlyingTInfo(TInfo); 2268 } 2269 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 2270 // By default, use the source location of the type specifier. 2271 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 2272 if (TL.needsExtraLocalData()) { 2273 // Set info for the written builtin specifiers. 2274 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 2275 // Try to have a meaningful source location. 2276 if (TL.getWrittenSignSpec() != TSS_unspecified) 2277 // Sign spec loc overrides the others (e.g., 'unsigned long'). 2278 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 2279 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 2280 // Width spec loc overrides type spec loc (e.g., 'short int'). 2281 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 2282 } 2283 } 2284 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 2285 ElaboratedTypeKeyword Keyword 2286 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 2287 if (DS.getTypeSpecType() == TST_typename) { 2288 TypeSourceInfo *TInfo = 0; 2289 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 2290 if (TInfo) { 2291 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc())); 2292 return; 2293 } 2294 } 2295 TL.setKeywordLoc(Keyword != ETK_None 2296 ? DS.getTypeSpecTypeLoc() 2297 : SourceLocation()); 2298 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 2299 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 2300 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 2301 } 2302 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 2303 ElaboratedTypeKeyword Keyword 2304 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 2305 if (DS.getTypeSpecType() == TST_typename) { 2306 TypeSourceInfo *TInfo = 0; 2307 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 2308 if (TInfo) { 2309 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc())); 2310 return; 2311 } 2312 } 2313 TL.setKeywordLoc(Keyword != ETK_None 2314 ? DS.getTypeSpecTypeLoc() 2315 : SourceLocation()); 2316 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 2317 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 2318 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 2319 } 2320 void VisitDependentTemplateSpecializationTypeLoc( 2321 DependentTemplateSpecializationTypeLoc TL) { 2322 ElaboratedTypeKeyword Keyword 2323 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 2324 if (Keyword == ETK_Typename) { 2325 TypeSourceInfo *TInfo = 0; 2326 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 2327 if (TInfo) { 2328 TL.copy(cast<DependentTemplateSpecializationTypeLoc>( 2329 TInfo->getTypeLoc())); 2330 return; 2331 } 2332 } 2333 TL.initializeLocal(Context, SourceLocation()); 2334 TL.setKeywordLoc(Keyword != ETK_None 2335 ? DS.getTypeSpecTypeLoc() 2336 : SourceLocation()); 2337 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 2338 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 2339 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 2340 } 2341 2342 void VisitTypeLoc(TypeLoc TL) { 2343 // FIXME: add other typespec types and change this to an assert. 2344 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 2345 } 2346 }; 2347 2348 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 2349 ASTContext &Context; 2350 const DeclaratorChunk &Chunk; 2351 2352 public: 2353 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 2354 : Context(Context), Chunk(Chunk) {} 2355 2356 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 2357 llvm_unreachable("qualified type locs not expected here!"); 2358 } 2359 2360 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 2361 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 2362 TL.setCaretLoc(Chunk.Loc); 2363 } 2364 void VisitPointerTypeLoc(PointerTypeLoc TL) { 2365 assert(Chunk.Kind == DeclaratorChunk::Pointer); 2366 TL.setStarLoc(Chunk.Loc); 2367 } 2368 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 2369 assert(Chunk.Kind == DeclaratorChunk::Pointer); 2370 TL.setStarLoc(Chunk.Loc); 2371 } 2372 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 2373 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 2374 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 2375 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 2376 2377 const Type* ClsTy = TL.getClass(); 2378 QualType ClsQT = QualType(ClsTy, 0); 2379 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 2380 // Now copy source location info into the type loc component. 2381 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 2382 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 2383 case NestedNameSpecifier::Identifier: 2384 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 2385 { 2386 DependentNameTypeLoc DNTLoc = *cast<DependentNameTypeLoc>(&ClsTL); 2387 DNTLoc.setKeywordLoc(SourceLocation()); 2388 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 2389 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 2390 } 2391 break; 2392 2393 case NestedNameSpecifier::TypeSpec: 2394 case NestedNameSpecifier::TypeSpecWithTemplate: 2395 if (isa<ElaboratedType>(ClsTy)) { 2396 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL); 2397 ETLoc.setKeywordLoc(SourceLocation()); 2398 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 2399 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 2400 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 2401 } else { 2402 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 2403 } 2404 break; 2405 2406 case NestedNameSpecifier::Namespace: 2407 case NestedNameSpecifier::NamespaceAlias: 2408 case NestedNameSpecifier::Global: 2409 llvm_unreachable("Nested-name-specifier must name a type"); 2410 break; 2411 } 2412 2413 // Finally fill in MemberPointerLocInfo fields. 2414 TL.setStarLoc(Chunk.Loc); 2415 TL.setClassTInfo(ClsTInfo); 2416 } 2417 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 2418 assert(Chunk.Kind == DeclaratorChunk::Reference); 2419 // 'Amp' is misleading: this might have been originally 2420 /// spelled with AmpAmp. 2421 TL.setAmpLoc(Chunk.Loc); 2422 } 2423 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 2424 assert(Chunk.Kind == DeclaratorChunk::Reference); 2425 assert(!Chunk.Ref.LValueRef); 2426 TL.setAmpAmpLoc(Chunk.Loc); 2427 } 2428 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 2429 assert(Chunk.Kind == DeclaratorChunk::Array); 2430 TL.setLBracketLoc(Chunk.Loc); 2431 TL.setRBracketLoc(Chunk.EndLoc); 2432 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 2433 } 2434 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 2435 assert(Chunk.Kind == DeclaratorChunk::Function); 2436 TL.setLParenLoc(Chunk.Loc); 2437 TL.setRParenLoc(Chunk.EndLoc); 2438 TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType); 2439 2440 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 2441 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) { 2442 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 2443 TL.setArg(tpi++, Param); 2444 } 2445 // FIXME: exception specs 2446 } 2447 void VisitParenTypeLoc(ParenTypeLoc TL) { 2448 assert(Chunk.Kind == DeclaratorChunk::Paren); 2449 TL.setLParenLoc(Chunk.Loc); 2450 TL.setRParenLoc(Chunk.EndLoc); 2451 } 2452 2453 void VisitTypeLoc(TypeLoc TL) { 2454 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 2455 } 2456 }; 2457} 2458 2459/// \brief Create and instantiate a TypeSourceInfo with type source information. 2460/// 2461/// \param T QualType referring to the type as written in source code. 2462/// 2463/// \param ReturnTypeInfo For declarators whose return type does not show 2464/// up in the normal place in the declaration specifiers (such as a C++ 2465/// conversion function), this pointer will refer to a type source information 2466/// for that return type. 2467TypeSourceInfo * 2468Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 2469 TypeSourceInfo *ReturnTypeInfo) { 2470 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 2471 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 2472 2473 // Handle parameter packs whose type is a pack expansion. 2474 if (isa<PackExpansionType>(T)) { 2475 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc()); 2476 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 2477 } 2478 2479 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2480 while (isa<AttributedTypeLoc>(CurrTL)) { 2481 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL); 2482 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs()); 2483 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 2484 } 2485 2486 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 2487 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 2488 } 2489 2490 // If we have different source information for the return type, use 2491 // that. This really only applies to C++ conversion functions. 2492 if (ReturnTypeInfo) { 2493 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 2494 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 2495 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 2496 } else { 2497 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 2498 } 2499 2500 return TInfo; 2501} 2502 2503/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 2504ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 2505 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 2506 // and Sema during declaration parsing. Try deallocating/caching them when 2507 // it's appropriate, instead of allocating them and keeping them around. 2508 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 2509 TypeAlignment); 2510 new (LocT) LocInfoType(T, TInfo); 2511 assert(LocT->getTypeClass() != T->getTypeClass() && 2512 "LocInfoType's TypeClass conflicts with an existing Type class"); 2513 return ParsedType::make(QualType(LocT, 0)); 2514} 2515 2516void LocInfoType::getAsStringInternal(std::string &Str, 2517 const PrintingPolicy &Policy) const { 2518 assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*" 2519 " was used directly instead of getting the QualType through" 2520 " GetTypeFromParser"); 2521} 2522 2523TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 2524 // C99 6.7.6: Type names have no identifier. This is already validated by 2525 // the parser. 2526 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 2527 2528 TagDecl *OwnedTag = 0; 2529 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag); 2530 QualType T = TInfo->getType(); 2531 if (D.isInvalidType()) 2532 return true; 2533 2534 if (getLangOptions().CPlusPlus) { 2535 // Check that there are no default arguments (C++ only). 2536 CheckExtraCXXDefaultArguments(D); 2537 2538 // C++0x [dcl.type]p3: 2539 // A type-specifier-seq shall not define a class or enumeration 2540 // unless it appears in the type-id of an alias-declaration 2541 // (7.1.3). 2542 if (OwnedTag && OwnedTag->isDefinition()) 2543 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier) 2544 << Context.getTypeDeclType(OwnedTag); 2545 } 2546 2547 return CreateParsedType(T, TInfo); 2548} 2549 2550 2551 2552//===----------------------------------------------------------------------===// 2553// Type Attribute Processing 2554//===----------------------------------------------------------------------===// 2555 2556/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 2557/// specified type. The attribute contains 1 argument, the id of the address 2558/// space for the type. 2559static void HandleAddressSpaceTypeAttribute(QualType &Type, 2560 const AttributeList &Attr, Sema &S){ 2561 2562 // If this type is already address space qualified, reject it. 2563 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers 2564 // for two or more different address spaces." 2565 if (Type.getAddressSpace()) { 2566 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 2567 Attr.setInvalid(); 2568 return; 2569 } 2570 2571 // Check the attribute arguments. 2572 if (Attr.getNumArgs() != 1) { 2573 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 2574 Attr.setInvalid(); 2575 return; 2576 } 2577 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 2578 llvm::APSInt addrSpace(32); 2579 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 2580 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 2581 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) 2582 << ASArgExpr->getSourceRange(); 2583 Attr.setInvalid(); 2584 return; 2585 } 2586 2587 // Bounds checking. 2588 if (addrSpace.isSigned()) { 2589 if (addrSpace.isNegative()) { 2590 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 2591 << ASArgExpr->getSourceRange(); 2592 Attr.setInvalid(); 2593 return; 2594 } 2595 addrSpace.setIsSigned(false); 2596 } 2597 llvm::APSInt max(addrSpace.getBitWidth()); 2598 max = Qualifiers::MaxAddressSpace; 2599 if (addrSpace > max) { 2600 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 2601 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange(); 2602 Attr.setInvalid(); 2603 return; 2604 } 2605 2606 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 2607 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 2608} 2609 2610/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 2611/// attribute on the specified type. Returns true to indicate that 2612/// the attribute was handled, false to indicate that the type does 2613/// not permit the attribute. 2614static bool handleObjCGCTypeAttr(TypeProcessingState &state, 2615 AttributeList &attr, 2616 QualType &type) { 2617 Sema &S = state.getSema(); 2618 2619 // Delay if this isn't some kind of pointer. 2620 if (!type->isPointerType() && 2621 !type->isObjCObjectPointerType() && 2622 !type->isBlockPointerType()) 2623 return false; 2624 2625 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 2626 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 2627 attr.setInvalid(); 2628 return true; 2629 } 2630 2631 // Check the attribute arguments. 2632 if (!attr.getParameterName()) { 2633 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string) 2634 << "objc_gc" << 1; 2635 attr.setInvalid(); 2636 return true; 2637 } 2638 Qualifiers::GC GCAttr; 2639 if (attr.getNumArgs() != 0) { 2640 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 2641 attr.setInvalid(); 2642 return true; 2643 } 2644 if (attr.getParameterName()->isStr("weak")) 2645 GCAttr = Qualifiers::Weak; 2646 else if (attr.getParameterName()->isStr("strong")) 2647 GCAttr = Qualifiers::Strong; 2648 else { 2649 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 2650 << "objc_gc" << attr.getParameterName(); 2651 attr.setInvalid(); 2652 return true; 2653 } 2654 2655 QualType origType = type; 2656 type = S.Context.getObjCGCQualType(origType, GCAttr); 2657 2658 // Make an attributed type to preserve the source information. 2659 if (attr.getLoc().isValid()) 2660 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 2661 origType, type); 2662 2663 return true; 2664} 2665 2666namespace { 2667 /// A helper class to unwrap a type down to a function for the 2668 /// purposes of applying attributes there. 2669 /// 2670 /// Use: 2671 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 2672 /// if (unwrapped.isFunctionType()) { 2673 /// const FunctionType *fn = unwrapped.get(); 2674 /// // change fn somehow 2675 /// T = unwrapped.wrap(fn); 2676 /// } 2677 struct FunctionTypeUnwrapper { 2678 enum WrapKind { 2679 Desugar, 2680 Parens, 2681 Pointer, 2682 BlockPointer, 2683 Reference, 2684 MemberPointer 2685 }; 2686 2687 QualType Original; 2688 const FunctionType *Fn; 2689 llvm::SmallVector<unsigned char /*WrapKind*/, 8> Stack; 2690 2691 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 2692 while (true) { 2693 const Type *Ty = T.getTypePtr(); 2694 if (isa<FunctionType>(Ty)) { 2695 Fn = cast<FunctionType>(Ty); 2696 return; 2697 } else if (isa<ParenType>(Ty)) { 2698 T = cast<ParenType>(Ty)->getInnerType(); 2699 Stack.push_back(Parens); 2700 } else if (isa<PointerType>(Ty)) { 2701 T = cast<PointerType>(Ty)->getPointeeType(); 2702 Stack.push_back(Pointer); 2703 } else if (isa<BlockPointerType>(Ty)) { 2704 T = cast<BlockPointerType>(Ty)->getPointeeType(); 2705 Stack.push_back(BlockPointer); 2706 } else if (isa<MemberPointerType>(Ty)) { 2707 T = cast<MemberPointerType>(Ty)->getPointeeType(); 2708 Stack.push_back(MemberPointer); 2709 } else if (isa<ReferenceType>(Ty)) { 2710 T = cast<ReferenceType>(Ty)->getPointeeType(); 2711 Stack.push_back(Reference); 2712 } else { 2713 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 2714 if (Ty == DTy) { 2715 Fn = 0; 2716 return; 2717 } 2718 2719 T = QualType(DTy, 0); 2720 Stack.push_back(Desugar); 2721 } 2722 } 2723 } 2724 2725 bool isFunctionType() const { return (Fn != 0); } 2726 const FunctionType *get() const { return Fn; } 2727 2728 QualType wrap(Sema &S, const FunctionType *New) { 2729 // If T wasn't modified from the unwrapped type, do nothing. 2730 if (New == get()) return Original; 2731 2732 Fn = New; 2733 return wrap(S.Context, Original, 0); 2734 } 2735 2736 private: 2737 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 2738 if (I == Stack.size()) 2739 return C.getQualifiedType(Fn, Old.getQualifiers()); 2740 2741 // Build up the inner type, applying the qualifiers from the old 2742 // type to the new type. 2743 SplitQualType SplitOld = Old.split(); 2744 2745 // As a special case, tail-recurse if there are no qualifiers. 2746 if (SplitOld.second.empty()) 2747 return wrap(C, SplitOld.first, I); 2748 return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.second); 2749 } 2750 2751 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 2752 if (I == Stack.size()) return QualType(Fn, 0); 2753 2754 switch (static_cast<WrapKind>(Stack[I++])) { 2755 case Desugar: 2756 // This is the point at which we potentially lose source 2757 // information. 2758 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 2759 2760 case Parens: { 2761 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 2762 return C.getParenType(New); 2763 } 2764 2765 case Pointer: { 2766 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 2767 return C.getPointerType(New); 2768 } 2769 2770 case BlockPointer: { 2771 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 2772 return C.getBlockPointerType(New); 2773 } 2774 2775 case MemberPointer: { 2776 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 2777 QualType New = wrap(C, OldMPT->getPointeeType(), I); 2778 return C.getMemberPointerType(New, OldMPT->getClass()); 2779 } 2780 2781 case Reference: { 2782 const ReferenceType *OldRef = cast<ReferenceType>(Old); 2783 QualType New = wrap(C, OldRef->getPointeeType(), I); 2784 if (isa<LValueReferenceType>(OldRef)) 2785 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 2786 else 2787 return C.getRValueReferenceType(New); 2788 } 2789 } 2790 2791 llvm_unreachable("unknown wrapping kind"); 2792 return QualType(); 2793 } 2794 }; 2795} 2796 2797/// Process an individual function attribute. Returns true to 2798/// indicate that the attribute was handled, false if it wasn't. 2799static bool handleFunctionTypeAttr(TypeProcessingState &state, 2800 AttributeList &attr, 2801 QualType &type) { 2802 Sema &S = state.getSema(); 2803 2804 FunctionTypeUnwrapper unwrapped(S, type); 2805 2806 if (attr.getKind() == AttributeList::AT_noreturn) { 2807 if (S.CheckNoReturnAttr(attr)) 2808 return true; 2809 2810 // Delay if this is not a function type. 2811 if (!unwrapped.isFunctionType()) 2812 return false; 2813 2814 // Otherwise we can process right away. 2815 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 2816 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 2817 return true; 2818 } 2819 2820 if (attr.getKind() == AttributeList::AT_regparm) { 2821 unsigned value; 2822 if (S.CheckRegparmAttr(attr, value)) 2823 return true; 2824 2825 // Delay if this is not a function type. 2826 if (!unwrapped.isFunctionType()) 2827 return false; 2828 2829 // Diagnose regparm with fastcall. 2830 const FunctionType *fn = unwrapped.get(); 2831 CallingConv CC = fn->getCallConv(); 2832 if (CC == CC_X86FastCall) { 2833 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 2834 << FunctionType::getNameForCallConv(CC) 2835 << "regparm"; 2836 attr.setInvalid(); 2837 return true; 2838 } 2839 2840 FunctionType::ExtInfo EI = 2841 unwrapped.get()->getExtInfo().withRegParm(value); 2842 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 2843 return true; 2844 } 2845 2846 // Otherwise, a calling convention. 2847 CallingConv CC; 2848 if (S.CheckCallingConvAttr(attr, CC)) 2849 return true; 2850 2851 // Delay if the type didn't work out to a function. 2852 if (!unwrapped.isFunctionType()) return false; 2853 2854 const FunctionType *fn = unwrapped.get(); 2855 CallingConv CCOld = fn->getCallConv(); 2856 if (S.Context.getCanonicalCallConv(CC) == 2857 S.Context.getCanonicalCallConv(CCOld)) { 2858 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC); 2859 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 2860 return true; 2861 } 2862 2863 if (CCOld != CC_Default) { 2864 // Should we diagnose reapplications of the same convention? 2865 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 2866 << FunctionType::getNameForCallConv(CC) 2867 << FunctionType::getNameForCallConv(CCOld); 2868 attr.setInvalid(); 2869 return true; 2870 } 2871 2872 // Diagnose the use of X86 fastcall on varargs or unprototyped functions. 2873 if (CC == CC_X86FastCall) { 2874 if (isa<FunctionNoProtoType>(fn)) { 2875 S.Diag(attr.getLoc(), diag::err_cconv_knr) 2876 << FunctionType::getNameForCallConv(CC); 2877 attr.setInvalid(); 2878 return true; 2879 } 2880 2881 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn); 2882 if (FnP->isVariadic()) { 2883 S.Diag(attr.getLoc(), diag::err_cconv_varargs) 2884 << FunctionType::getNameForCallConv(CC); 2885 attr.setInvalid(); 2886 return true; 2887 } 2888 2889 // Also diagnose fastcall with regparm. 2890 if (fn->getRegParmType()) { 2891 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 2892 << "regparm" 2893 << FunctionType::getNameForCallConv(CC); 2894 attr.setInvalid(); 2895 return true; 2896 } 2897 } 2898 2899 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 2900 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 2901 return true; 2902} 2903 2904/// HandleVectorSizeAttribute - this attribute is only applicable to integral 2905/// and float scalars, although arrays, pointers, and function return values are 2906/// allowed in conjunction with this construct. Aggregates with this attribute 2907/// are invalid, even if they are of the same size as a corresponding scalar. 2908/// The raw attribute should contain precisely 1 argument, the vector size for 2909/// the variable, measured in bytes. If curType and rawAttr are well formed, 2910/// this routine will return a new vector type. 2911static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 2912 Sema &S) { 2913 // Check the attribute arguments. 2914 if (Attr.getNumArgs() != 1) { 2915 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 2916 Attr.setInvalid(); 2917 return; 2918 } 2919 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 2920 llvm::APSInt vecSize(32); 2921 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 2922 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 2923 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 2924 << "vector_size" << sizeExpr->getSourceRange(); 2925 Attr.setInvalid(); 2926 return; 2927 } 2928 // the base type must be integer or float, and can't already be a vector. 2929 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) { 2930 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 2931 Attr.setInvalid(); 2932 return; 2933 } 2934 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 2935 // vecSize is specified in bytes - convert to bits. 2936 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 2937 2938 // the vector size needs to be an integral multiple of the type size. 2939 if (vectorSize % typeSize) { 2940 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 2941 << sizeExpr->getSourceRange(); 2942 Attr.setInvalid(); 2943 return; 2944 } 2945 if (vectorSize == 0) { 2946 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 2947 << sizeExpr->getSourceRange(); 2948 Attr.setInvalid(); 2949 return; 2950 } 2951 2952 // Success! Instantiate the vector type, the number of elements is > 0, and 2953 // not required to be a power of 2, unlike GCC. 2954 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 2955 VectorType::GenericVector); 2956} 2957 2958/// HandleNeonVectorTypeAttr - The "neon_vector_type" and 2959/// "neon_polyvector_type" attributes are used to create vector types that 2960/// are mangled according to ARM's ABI. Otherwise, these types are identical 2961/// to those created with the "vector_size" attribute. Unlike "vector_size" 2962/// the argument to these Neon attributes is the number of vector elements, 2963/// not the vector size in bytes. The vector width and element type must 2964/// match one of the standard Neon vector types. 2965static void HandleNeonVectorTypeAttr(QualType& CurType, 2966 const AttributeList &Attr, Sema &S, 2967 VectorType::VectorKind VecKind, 2968 const char *AttrName) { 2969 // Check the attribute arguments. 2970 if (Attr.getNumArgs() != 1) { 2971 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 2972 Attr.setInvalid(); 2973 return; 2974 } 2975 // The number of elements must be an ICE. 2976 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0)); 2977 llvm::APSInt numEltsInt(32); 2978 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 2979 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 2980 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 2981 << AttrName << numEltsExpr->getSourceRange(); 2982 Attr.setInvalid(); 2983 return; 2984 } 2985 // Only certain element types are supported for Neon vectors. 2986 const BuiltinType* BTy = CurType->getAs<BuiltinType>(); 2987 if (!BTy || 2988 (VecKind == VectorType::NeonPolyVector && 2989 BTy->getKind() != BuiltinType::SChar && 2990 BTy->getKind() != BuiltinType::Short) || 2991 (BTy->getKind() != BuiltinType::SChar && 2992 BTy->getKind() != BuiltinType::UChar && 2993 BTy->getKind() != BuiltinType::Short && 2994 BTy->getKind() != BuiltinType::UShort && 2995 BTy->getKind() != BuiltinType::Int && 2996 BTy->getKind() != BuiltinType::UInt && 2997 BTy->getKind() != BuiltinType::LongLong && 2998 BTy->getKind() != BuiltinType::ULongLong && 2999 BTy->getKind() != BuiltinType::Float)) { 3000 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType; 3001 Attr.setInvalid(); 3002 return; 3003 } 3004 // The total size of the vector must be 64 or 128 bits. 3005 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 3006 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 3007 unsigned vecSize = typeSize * numElts; 3008 if (vecSize != 64 && vecSize != 128) { 3009 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 3010 Attr.setInvalid(); 3011 return; 3012 } 3013 3014 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 3015} 3016 3017static void processTypeAttrs(TypeProcessingState &state, QualType &type, 3018 bool isDeclSpec, AttributeList *attrs) { 3019 // Scan through and apply attributes to this type where it makes sense. Some 3020 // attributes (such as __address_space__, __vector_size__, etc) apply to the 3021 // type, but others can be present in the type specifiers even though they 3022 // apply to the decl. Here we apply type attributes and ignore the rest. 3023 3024 AttributeList *next; 3025 do { 3026 AttributeList &attr = *attrs; 3027 next = attr.getNext(); 3028 3029 // Skip attributes that were marked to be invalid. 3030 if (attr.isInvalid()) 3031 continue; 3032 3033 // If this is an attribute we can handle, do so now, 3034 // otherwise, add it to the FnAttrs list for rechaining. 3035 switch (attr.getKind()) { 3036 default: break; 3037 3038 case AttributeList::AT_address_space: 3039 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 3040 break; 3041 OBJC_POINTER_TYPE_ATTRS_CASELIST: 3042 if (!handleObjCPointerTypeAttr(state, attr, type)) 3043 distributeObjCPointerTypeAttr(state, attr, type); 3044 break; 3045 case AttributeList::AT_vector_size: 3046 HandleVectorSizeAttr(type, attr, state.getSema()); 3047 break; 3048 case AttributeList::AT_neon_vector_type: 3049 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 3050 VectorType::NeonVector, "neon_vector_type"); 3051 break; 3052 case AttributeList::AT_neon_polyvector_type: 3053 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 3054 VectorType::NeonPolyVector, 3055 "neon_polyvector_type"); 3056 break; 3057 3058 FUNCTION_TYPE_ATTRS_CASELIST: 3059 // Never process function type attributes as part of the 3060 // declaration-specifiers. 3061 if (isDeclSpec) 3062 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 3063 3064 // Otherwise, handle the possible delays. 3065 else if (!handleFunctionTypeAttr(state, attr, type)) 3066 distributeFunctionTypeAttr(state, attr, type); 3067 break; 3068 } 3069 } while ((attrs = next)); 3070} 3071 3072/// @brief Ensure that the type T is a complete type. 3073/// 3074/// This routine checks whether the type @p T is complete in any 3075/// context where a complete type is required. If @p T is a complete 3076/// type, returns false. If @p T is a class template specialization, 3077/// this routine then attempts to perform class template 3078/// instantiation. If instantiation fails, or if @p T is incomplete 3079/// and cannot be completed, issues the diagnostic @p diag (giving it 3080/// the type @p T) and returns true. 3081/// 3082/// @param Loc The location in the source that the incomplete type 3083/// diagnostic should refer to. 3084/// 3085/// @param T The type that this routine is examining for completeness. 3086/// 3087/// @param PD The partial diagnostic that will be printed out if T is not a 3088/// complete type. 3089/// 3090/// @returns @c true if @p T is incomplete and a diagnostic was emitted, 3091/// @c false otherwise. 3092bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 3093 const PartialDiagnostic &PD, 3094 std::pair<SourceLocation, 3095 PartialDiagnostic> Note) { 3096 unsigned diag = PD.getDiagID(); 3097 3098 // FIXME: Add this assertion to make sure we always get instantiation points. 3099 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 3100 // FIXME: Add this assertion to help us flush out problems with 3101 // checking for dependent types and type-dependent expressions. 3102 // 3103 // assert(!T->isDependentType() && 3104 // "Can't ask whether a dependent type is complete"); 3105 3106 // If we have a complete type, we're done. 3107 if (!T->isIncompleteType()) 3108 return false; 3109 3110 // If we have a class template specialization or a class member of a 3111 // class template specialization, or an array with known size of such, 3112 // try to instantiate it. 3113 QualType MaybeTemplate = T; 3114 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T)) 3115 MaybeTemplate = Array->getElementType(); 3116 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 3117 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 3118 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 3119 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) 3120 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec, 3121 TSK_ImplicitInstantiation, 3122 /*Complain=*/diag != 0); 3123 } else if (CXXRecordDecl *Rec 3124 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 3125 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) { 3126 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo(); 3127 assert(MSInfo && "Missing member specialization information?"); 3128 // This record was instantiated from a class within a template. 3129 if (MSInfo->getTemplateSpecializationKind() 3130 != TSK_ExplicitSpecialization) 3131 return InstantiateClass(Loc, Rec, Pattern, 3132 getTemplateInstantiationArgs(Rec), 3133 TSK_ImplicitInstantiation, 3134 /*Complain=*/diag != 0); 3135 } 3136 } 3137 } 3138 3139 if (diag == 0) 3140 return true; 3141 3142 const TagType *Tag = T->getAs<TagType>(); 3143 3144 // Avoid diagnosing invalid decls as incomplete. 3145 if (Tag && Tag->getDecl()->isInvalidDecl()) 3146 return true; 3147 3148 // Give the external AST source a chance to complete the type. 3149 if (Tag && Tag->getDecl()->hasExternalLexicalStorage()) { 3150 Context.getExternalSource()->CompleteType(Tag->getDecl()); 3151 if (!Tag->isIncompleteType()) 3152 return false; 3153 } 3154 3155 // We have an incomplete type. Produce a diagnostic. 3156 Diag(Loc, PD) << T; 3157 3158 // If we have a note, produce it. 3159 if (!Note.first.isInvalid()) 3160 Diag(Note.first, Note.second); 3161 3162 // If the type was a forward declaration of a class/struct/union 3163 // type, produce a note. 3164 if (Tag && !Tag->getDecl()->isInvalidDecl()) 3165 Diag(Tag->getDecl()->getLocation(), 3166 Tag->isBeingDefined() ? diag::note_type_being_defined 3167 : diag::note_forward_declaration) 3168 << QualType(Tag, 0); 3169 3170 return true; 3171} 3172 3173bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 3174 const PartialDiagnostic &PD) { 3175 return RequireCompleteType(Loc, T, PD, 3176 std::make_pair(SourceLocation(), PDiag(0))); 3177} 3178 3179bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 3180 unsigned DiagID) { 3181 return RequireCompleteType(Loc, T, PDiag(DiagID), 3182 std::make_pair(SourceLocation(), PDiag(0))); 3183} 3184 3185/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 3186/// and qualified by the nested-name-specifier contained in SS. 3187QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 3188 const CXXScopeSpec &SS, QualType T) { 3189 if (T.isNull()) 3190 return T; 3191 NestedNameSpecifier *NNS; 3192 if (SS.isValid()) 3193 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3194 else { 3195 if (Keyword == ETK_None) 3196 return T; 3197 NNS = 0; 3198 } 3199 return Context.getElaboratedType(Keyword, NNS, T); 3200} 3201 3202QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 3203 ExprResult ER = CheckPlaceholderExpr(E, Loc); 3204 if (ER.isInvalid()) return QualType(); 3205 E = ER.take(); 3206 3207 if (!E->isTypeDependent()) { 3208 QualType T = E->getType(); 3209 if (const TagType *TT = T->getAs<TagType>()) 3210 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 3211 } 3212 return Context.getTypeOfExprType(E); 3213} 3214 3215QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) { 3216 ExprResult ER = CheckPlaceholderExpr(E, Loc); 3217 if (ER.isInvalid()) return QualType(); 3218 E = ER.take(); 3219 3220 return Context.getDecltypeType(E); 3221} 3222