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