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