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