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