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