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