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 "TypeLocBuilder.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/TypeLoc.h" 23 #include "clang/AST/TypeLocVisitor.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Lex/Preprocessor.h" 27 #include "clang/Sema/DeclSpec.h" 28 #include "clang/Sema/DelayedDiagnostic.h" 29 #include "clang/Sema/Lookup.h" 30 #include "clang/Sema/ScopeInfo.h" 31 #include "clang/Sema/SemaInternal.h" 32 #include "clang/Sema/Template.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include "llvm/ADT/StringSwitch.h" 36 #include "llvm/Support/ErrorHandling.h" 37 38 using namespace clang; 39 40 enum TypeDiagSelector { 41 TDS_Function, 42 TDS_Pointer, 43 TDS_ObjCObjOrBlock 44 }; 45 46 /// isOmittedBlockReturnType - Return true if this declarator is missing a 47 /// return type because this is a omitted return type on a block literal. 48 static bool isOmittedBlockReturnType(const Declarator &D) { 49 if (D.getContext() != Declarator::BlockLiteralContext || 50 D.getDeclSpec().hasTypeSpecifier()) 51 return false; 52 53 if (D.getNumTypeObjects() == 0) 54 return true; // ^{ ... } 55 56 if (D.getNumTypeObjects() == 1 && 57 D.getTypeObject(0).Kind == DeclaratorChunk::Function) 58 return true; // ^(int X, float Y) { ... } 59 60 return false; 61 } 62 63 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which 64 /// doesn't apply to the given type. 65 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr, 66 QualType type) { 67 TypeDiagSelector WhichType; 68 bool useExpansionLoc = true; 69 switch (attr.getKind()) { 70 case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break; 71 case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break; 72 default: 73 // Assume everything else was a function attribute. 74 WhichType = TDS_Function; 75 useExpansionLoc = false; 76 break; 77 } 78 79 SourceLocation loc = attr.getLoc(); 80 StringRef name = attr.getName()->getName(); 81 82 // The GC attributes are usually written with macros; special-case them. 83 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident 84 : nullptr; 85 if (useExpansionLoc && loc.isMacroID() && II) { 86 if (II->isStr("strong")) { 87 if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; 88 } else if (II->isStr("weak")) { 89 if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; 90 } 91 } 92 93 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType 94 << type; 95 } 96 97 // objc_gc applies to Objective-C pointers or, otherwise, to the 98 // smallest available pointer type (i.e. 'void*' in 'void**'). 99 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \ 100 case AttributeList::AT_ObjCGC: \ 101 case AttributeList::AT_ObjCOwnership 102 103 // Calling convention attributes. 104 #define CALLING_CONV_ATTRS_CASELIST \ 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_SwiftCall: \ 111 case AttributeList::AT_VectorCall: \ 112 case AttributeList::AT_MSABI: \ 113 case AttributeList::AT_SysVABI: \ 114 case AttributeList::AT_Pcs: \ 115 case AttributeList::AT_IntelOclBicc: \ 116 case AttributeList::AT_PreserveMost: \ 117 case AttributeList::AT_PreserveAll 118 119 // Function type attributes. 120 #define FUNCTION_TYPE_ATTRS_CASELIST \ 121 case AttributeList::AT_NoReturn: \ 122 case AttributeList::AT_Regparm: \ 123 CALLING_CONV_ATTRS_CASELIST 124 125 // Microsoft-specific type qualifiers. 126 #define MS_TYPE_ATTRS_CASELIST \ 127 case AttributeList::AT_Ptr32: \ 128 case AttributeList::AT_Ptr64: \ 129 case AttributeList::AT_SPtr: \ 130 case AttributeList::AT_UPtr 131 132 // Nullability qualifiers. 133 #define NULLABILITY_TYPE_ATTRS_CASELIST \ 134 case AttributeList::AT_TypeNonNull: \ 135 case AttributeList::AT_TypeNullable: \ 136 case AttributeList::AT_TypeNullUnspecified 137 138 namespace { 139 /// An object which stores processing state for the entire 140 /// GetTypeForDeclarator process. 141 class TypeProcessingState { 142 Sema &sema; 143 144 /// The declarator being processed. 145 Declarator &declarator; 146 147 /// The index of the declarator chunk we're currently processing. 148 /// May be the total number of valid chunks, indicating the 149 /// DeclSpec. 150 unsigned chunkIndex; 151 152 /// Whether there are non-trivial modifications to the decl spec. 153 bool trivial; 154 155 /// Whether we saved the attributes in the decl spec. 156 bool hasSavedAttrs; 157 158 /// The original set of attributes on the DeclSpec. 159 SmallVector<AttributeList*, 2> savedAttrs; 160 161 /// A list of attributes to diagnose the uselessness of when the 162 /// processing is complete. 163 SmallVector<AttributeList*, 2> ignoredTypeAttrs; 164 165 public: 166 TypeProcessingState(Sema &sema, Declarator &declarator) 167 : sema(sema), declarator(declarator), 168 chunkIndex(declarator.getNumTypeObjects()), 169 trivial(true), hasSavedAttrs(false) {} 170 171 Sema &getSema() const { 172 return sema; 173 } 174 175 Declarator &getDeclarator() const { 176 return declarator; 177 } 178 179 bool isProcessingDeclSpec() const { 180 return chunkIndex == declarator.getNumTypeObjects(); 181 } 182 183 unsigned getCurrentChunkIndex() const { 184 return chunkIndex; 185 } 186 187 void setCurrentChunkIndex(unsigned idx) { 188 assert(idx <= declarator.getNumTypeObjects()); 189 chunkIndex = idx; 190 } 191 192 AttributeList *&getCurrentAttrListRef() const { 193 if (isProcessingDeclSpec()) 194 return getMutableDeclSpec().getAttributes().getListRef(); 195 return declarator.getTypeObject(chunkIndex).getAttrListRef(); 196 } 197 198 /// Save the current set of attributes on the DeclSpec. 199 void saveDeclSpecAttrs() { 200 // Don't try to save them multiple times. 201 if (hasSavedAttrs) return; 202 203 DeclSpec &spec = getMutableDeclSpec(); 204 for (AttributeList *attr = spec.getAttributes().getList(); attr; 205 attr = attr->getNext()) 206 savedAttrs.push_back(attr); 207 trivial &= savedAttrs.empty(); 208 hasSavedAttrs = true; 209 } 210 211 /// Record that we had nowhere to put the given type attribute. 212 /// We will diagnose such attributes later. 213 void addIgnoredTypeAttr(AttributeList &attr) { 214 ignoredTypeAttrs.push_back(&attr); 215 } 216 217 /// Diagnose all the ignored type attributes, given that the 218 /// declarator worked out to the given type. 219 void diagnoseIgnoredTypeAttrs(QualType type) const { 220 for (auto *Attr : ignoredTypeAttrs) 221 diagnoseBadTypeAttribute(getSema(), *Attr, type); 222 } 223 224 ~TypeProcessingState() { 225 if (trivial) return; 226 227 restoreDeclSpecAttrs(); 228 } 229 230 private: 231 DeclSpec &getMutableDeclSpec() const { 232 return const_cast<DeclSpec&>(declarator.getDeclSpec()); 233 } 234 235 void restoreDeclSpecAttrs() { 236 assert(hasSavedAttrs); 237 238 if (savedAttrs.empty()) { 239 getMutableDeclSpec().getAttributes().set(nullptr); 240 return; 241 } 242 243 getMutableDeclSpec().getAttributes().set(savedAttrs[0]); 244 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i) 245 savedAttrs[i]->setNext(savedAttrs[i+1]); 246 savedAttrs.back()->setNext(nullptr); 247 } 248 }; 249 } // end anonymous namespace 250 251 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) { 252 attr.setNext(head); 253 head = &attr; 254 } 255 256 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) { 257 if (head == &attr) { 258 head = attr.getNext(); 259 return; 260 } 261 262 AttributeList *cur = head; 263 while (true) { 264 assert(cur && cur->getNext() && "ran out of attrs?"); 265 if (cur->getNext() == &attr) { 266 cur->setNext(attr.getNext()); 267 return; 268 } 269 cur = cur->getNext(); 270 } 271 } 272 273 static void moveAttrFromListToList(AttributeList &attr, 274 AttributeList *&fromList, 275 AttributeList *&toList) { 276 spliceAttrOutOfList(attr, fromList); 277 spliceAttrIntoList(attr, toList); 278 } 279 280 /// The location of a type attribute. 281 enum TypeAttrLocation { 282 /// The attribute is in the decl-specifier-seq. 283 TAL_DeclSpec, 284 /// The attribute is part of a DeclaratorChunk. 285 TAL_DeclChunk, 286 /// The attribute is immediately after the declaration's name. 287 TAL_DeclName 288 }; 289 290 static void processTypeAttrs(TypeProcessingState &state, 291 QualType &type, TypeAttrLocation TAL, 292 AttributeList *attrs); 293 294 static bool handleFunctionTypeAttr(TypeProcessingState &state, 295 AttributeList &attr, 296 QualType &type); 297 298 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, 299 AttributeList &attr, 300 QualType &type); 301 302 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 303 AttributeList &attr, QualType &type); 304 305 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 306 AttributeList &attr, QualType &type); 307 308 static bool handleObjCPointerTypeAttr(TypeProcessingState &state, 309 AttributeList &attr, QualType &type) { 310 if (attr.getKind() == AttributeList::AT_ObjCGC) 311 return handleObjCGCTypeAttr(state, attr, type); 312 assert(attr.getKind() == AttributeList::AT_ObjCOwnership); 313 return handleObjCOwnershipTypeAttr(state, attr, type); 314 } 315 316 /// Given the index of a declarator chunk, check whether that chunk 317 /// directly specifies the return type of a function and, if so, find 318 /// an appropriate place for it. 319 /// 320 /// \param i - a notional index which the search will start 321 /// immediately inside 322 /// 323 /// \param onlyBlockPointers Whether we should only look into block 324 /// pointer types (vs. all pointer types). 325 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, 326 unsigned i, 327 bool onlyBlockPointers) { 328 assert(i <= declarator.getNumTypeObjects()); 329 330 DeclaratorChunk *result = nullptr; 331 332 // First, look inwards past parens for a function declarator. 333 for (; i != 0; --i) { 334 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); 335 switch (fnChunk.Kind) { 336 case DeclaratorChunk::Paren: 337 continue; 338 339 // If we find anything except a function, bail out. 340 case DeclaratorChunk::Pointer: 341 case DeclaratorChunk::BlockPointer: 342 case DeclaratorChunk::Array: 343 case DeclaratorChunk::Reference: 344 case DeclaratorChunk::MemberPointer: 345 case DeclaratorChunk::Pipe: 346 return result; 347 348 // If we do find a function declarator, scan inwards from that, 349 // looking for a (block-)pointer declarator. 350 case DeclaratorChunk::Function: 351 for (--i; i != 0; --i) { 352 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1); 353 switch (ptrChunk.Kind) { 354 case DeclaratorChunk::Paren: 355 case DeclaratorChunk::Array: 356 case DeclaratorChunk::Function: 357 case DeclaratorChunk::Reference: 358 case DeclaratorChunk::Pipe: 359 continue; 360 361 case DeclaratorChunk::MemberPointer: 362 case DeclaratorChunk::Pointer: 363 if (onlyBlockPointers) 364 continue; 365 366 // fallthrough 367 368 case DeclaratorChunk::BlockPointer: 369 result = &ptrChunk; 370 goto continue_outer; 371 } 372 llvm_unreachable("bad declarator chunk kind"); 373 } 374 375 // If we run out of declarators doing that, we're done. 376 return result; 377 } 378 llvm_unreachable("bad declarator chunk kind"); 379 380 // Okay, reconsider from our new point. 381 continue_outer: ; 382 } 383 384 // Ran out of chunks, bail out. 385 return result; 386 } 387 388 /// Given that an objc_gc attribute was written somewhere on a 389 /// declaration *other* than on the declarator itself (for which, use 390 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it 391 /// didn't apply in whatever position it was written in, try to move 392 /// it to a more appropriate position. 393 static void distributeObjCPointerTypeAttr(TypeProcessingState &state, 394 AttributeList &attr, 395 QualType type) { 396 Declarator &declarator = state.getDeclarator(); 397 398 // Move it to the outermost normal or block pointer declarator. 399 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 400 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 401 switch (chunk.Kind) { 402 case DeclaratorChunk::Pointer: 403 case DeclaratorChunk::BlockPointer: { 404 // But don't move an ARC ownership attribute to the return type 405 // of a block. 406 DeclaratorChunk *destChunk = nullptr; 407 if (state.isProcessingDeclSpec() && 408 attr.getKind() == AttributeList::AT_ObjCOwnership) 409 destChunk = maybeMovePastReturnType(declarator, i - 1, 410 /*onlyBlockPointers=*/true); 411 if (!destChunk) destChunk = &chunk; 412 413 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 414 destChunk->getAttrListRef()); 415 return; 416 } 417 418 case DeclaratorChunk::Paren: 419 case DeclaratorChunk::Array: 420 continue; 421 422 // We may be starting at the return type of a block. 423 case DeclaratorChunk::Function: 424 if (state.isProcessingDeclSpec() && 425 attr.getKind() == AttributeList::AT_ObjCOwnership) { 426 if (DeclaratorChunk *dest = maybeMovePastReturnType( 427 declarator, i, 428 /*onlyBlockPointers=*/true)) { 429 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 430 dest->getAttrListRef()); 431 return; 432 } 433 } 434 goto error; 435 436 // Don't walk through these. 437 case DeclaratorChunk::Reference: 438 case DeclaratorChunk::MemberPointer: 439 case DeclaratorChunk::Pipe: 440 goto error; 441 } 442 } 443 error: 444 445 diagnoseBadTypeAttribute(state.getSema(), attr, type); 446 } 447 448 /// Distribute an objc_gc type attribute that was written on the 449 /// declarator. 450 static void 451 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, 452 AttributeList &attr, 453 QualType &declSpecType) { 454 Declarator &declarator = state.getDeclarator(); 455 456 // objc_gc goes on the innermost pointer to something that's not a 457 // pointer. 458 unsigned innermost = -1U; 459 bool considerDeclSpec = true; 460 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 461 DeclaratorChunk &chunk = declarator.getTypeObject(i); 462 switch (chunk.Kind) { 463 case DeclaratorChunk::Pointer: 464 case DeclaratorChunk::BlockPointer: 465 innermost = i; 466 continue; 467 468 case DeclaratorChunk::Reference: 469 case DeclaratorChunk::MemberPointer: 470 case DeclaratorChunk::Paren: 471 case DeclaratorChunk::Array: 472 case DeclaratorChunk::Pipe: 473 continue; 474 475 case DeclaratorChunk::Function: 476 considerDeclSpec = false; 477 goto done; 478 } 479 } 480 done: 481 482 // That might actually be the decl spec if we weren't blocked by 483 // anything in the declarator. 484 if (considerDeclSpec) { 485 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { 486 // Splice the attribute into the decl spec. Prevents the 487 // attribute from being applied multiple times and gives 488 // the source-location-filler something to work with. 489 state.saveDeclSpecAttrs(); 490 moveAttrFromListToList(attr, declarator.getAttrListRef(), 491 declarator.getMutableDeclSpec().getAttributes().getListRef()); 492 return; 493 } 494 } 495 496 // Otherwise, if we found an appropriate chunk, splice the attribute 497 // into it. 498 if (innermost != -1U) { 499 moveAttrFromListToList(attr, declarator.getAttrListRef(), 500 declarator.getTypeObject(innermost).getAttrListRef()); 501 return; 502 } 503 504 // Otherwise, diagnose when we're done building the type. 505 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 506 state.addIgnoredTypeAttr(attr); 507 } 508 509 /// A function type attribute was written somewhere in a declaration 510 /// *other* than on the declarator itself or in the decl spec. Given 511 /// that it didn't apply in whatever position it was written in, try 512 /// to move it to a more appropriate position. 513 static void distributeFunctionTypeAttr(TypeProcessingState &state, 514 AttributeList &attr, 515 QualType type) { 516 Declarator &declarator = state.getDeclarator(); 517 518 // Try to push the attribute from the return type of a function to 519 // the function itself. 520 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 521 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 522 switch (chunk.Kind) { 523 case DeclaratorChunk::Function: 524 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 525 chunk.getAttrListRef()); 526 return; 527 528 case DeclaratorChunk::Paren: 529 case DeclaratorChunk::Pointer: 530 case DeclaratorChunk::BlockPointer: 531 case DeclaratorChunk::Array: 532 case DeclaratorChunk::Reference: 533 case DeclaratorChunk::MemberPointer: 534 case DeclaratorChunk::Pipe: 535 continue; 536 } 537 } 538 539 diagnoseBadTypeAttribute(state.getSema(), attr, type); 540 } 541 542 /// Try to distribute a function type attribute to the innermost 543 /// function chunk or type. Returns true if the attribute was 544 /// distributed, false if no location was found. 545 static bool 546 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, 547 AttributeList &attr, 548 AttributeList *&attrList, 549 QualType &declSpecType) { 550 Declarator &declarator = state.getDeclarator(); 551 552 // Put it on the innermost function chunk, if there is one. 553 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 554 DeclaratorChunk &chunk = declarator.getTypeObject(i); 555 if (chunk.Kind != DeclaratorChunk::Function) continue; 556 557 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef()); 558 return true; 559 } 560 561 return handleFunctionTypeAttr(state, attr, declSpecType); 562 } 563 564 /// A function type attribute was written in the decl spec. Try to 565 /// apply it somewhere. 566 static void 567 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, 568 AttributeList &attr, 569 QualType &declSpecType) { 570 state.saveDeclSpecAttrs(); 571 572 // C++11 attributes before the decl specifiers actually appertain to 573 // the declarators. Move them straight there. We don't support the 574 // 'put them wherever you like' semantics we allow for GNU attributes. 575 if (attr.isCXX11Attribute()) { 576 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 577 state.getDeclarator().getAttrListRef()); 578 return; 579 } 580 581 // Try to distribute to the innermost. 582 if (distributeFunctionTypeAttrToInnermost(state, attr, 583 state.getCurrentAttrListRef(), 584 declSpecType)) 585 return; 586 587 // If that failed, diagnose the bad attribute when the declarator is 588 // fully built. 589 state.addIgnoredTypeAttr(attr); 590 } 591 592 /// A function type attribute was written on the declarator. Try to 593 /// apply it somewhere. 594 static void 595 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, 596 AttributeList &attr, 597 QualType &declSpecType) { 598 Declarator &declarator = state.getDeclarator(); 599 600 // Try to distribute to the innermost. 601 if (distributeFunctionTypeAttrToInnermost(state, attr, 602 declarator.getAttrListRef(), 603 declSpecType)) 604 return; 605 606 // If that failed, diagnose the bad attribute when the declarator is 607 // fully built. 608 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 609 state.addIgnoredTypeAttr(attr); 610 } 611 612 /// \brief Given that there are attributes written on the declarator 613 /// itself, try to distribute any type attributes to the appropriate 614 /// declarator chunk. 615 /// 616 /// These are attributes like the following: 617 /// int f ATTR; 618 /// int (f ATTR)(); 619 /// but not necessarily this: 620 /// int f() ATTR; 621 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, 622 QualType &declSpecType) { 623 // Collect all the type attributes from the declarator itself. 624 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!"); 625 AttributeList *attr = state.getDeclarator().getAttributes(); 626 AttributeList *next; 627 do { 628 next = attr->getNext(); 629 630 // Do not distribute C++11 attributes. They have strict rules for what 631 // they appertain to. 632 if (attr->isCXX11Attribute()) 633 continue; 634 635 switch (attr->getKind()) { 636 OBJC_POINTER_TYPE_ATTRS_CASELIST: 637 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType); 638 break; 639 640 case AttributeList::AT_NSReturnsRetained: 641 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 642 break; 643 // fallthrough 644 645 FUNCTION_TYPE_ATTRS_CASELIST: 646 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType); 647 break; 648 649 MS_TYPE_ATTRS_CASELIST: 650 // Microsoft type attributes cannot go after the declarator-id. 651 continue; 652 653 NULLABILITY_TYPE_ATTRS_CASELIST: 654 // Nullability specifiers cannot go after the declarator-id. 655 656 // Objective-C __kindof does not get distributed. 657 case AttributeList::AT_ObjCKindOf: 658 continue; 659 660 default: 661 break; 662 } 663 } while ((attr = next)); 664 } 665 666 /// Add a synthetic '()' to a block-literal declarator if it is 667 /// required, given the return type. 668 static void maybeSynthesizeBlockSignature(TypeProcessingState &state, 669 QualType declSpecType) { 670 Declarator &declarator = state.getDeclarator(); 671 672 // First, check whether the declarator would produce a function, 673 // i.e. whether the innermost semantic chunk is a function. 674 if (declarator.isFunctionDeclarator()) { 675 // If so, make that declarator a prototyped declarator. 676 declarator.getFunctionTypeInfo().hasPrototype = true; 677 return; 678 } 679 680 // If there are any type objects, the type as written won't name a 681 // function, regardless of the decl spec type. This is because a 682 // block signature declarator is always an abstract-declarator, and 683 // abstract-declarators can't just be parentheses chunks. Therefore 684 // we need to build a function chunk unless there are no type 685 // objects and the decl spec type is a function. 686 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) 687 return; 688 689 // Note that there *are* cases with invalid declarators where 690 // declarators consist solely of parentheses. In general, these 691 // occur only in failed efforts to make function declarators, so 692 // faking up the function chunk is still the right thing to do. 693 694 // Otherwise, we need to fake up a function declarator. 695 SourceLocation loc = declarator.getLocStart(); 696 697 // ...and *prepend* it to the declarator. 698 SourceLocation NoLoc; 699 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( 700 /*HasProto=*/true, 701 /*IsAmbiguous=*/false, 702 /*LParenLoc=*/NoLoc, 703 /*ArgInfo=*/nullptr, 704 /*NumArgs=*/0, 705 /*EllipsisLoc=*/NoLoc, 706 /*RParenLoc=*/NoLoc, 707 /*TypeQuals=*/0, 708 /*RefQualifierIsLvalueRef=*/true, 709 /*RefQualifierLoc=*/NoLoc, 710 /*ConstQualifierLoc=*/NoLoc, 711 /*VolatileQualifierLoc=*/NoLoc, 712 /*RestrictQualifierLoc=*/NoLoc, 713 /*MutableLoc=*/NoLoc, EST_None, 714 /*ESpecRange=*/SourceRange(), 715 /*Exceptions=*/nullptr, 716 /*ExceptionRanges=*/nullptr, 717 /*NumExceptions=*/0, 718 /*NoexceptExpr=*/nullptr, 719 /*ExceptionSpecTokens=*/nullptr, 720 loc, loc, declarator)); 721 722 // For consistency, make sure the state still has us as processing 723 // the decl spec. 724 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1); 725 state.setCurrentChunkIndex(declarator.getNumTypeObjects()); 726 } 727 728 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, 729 unsigned &TypeQuals, 730 QualType TypeSoFar, 731 unsigned RemoveTQs, 732 unsigned DiagID) { 733 // If this occurs outside a template instantiation, warn the user about 734 // it; they probably didn't mean to specify a redundant qualifier. 735 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc; 736 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()), 737 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()), 738 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()), 739 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) { 740 if (!(RemoveTQs & Qual.first)) 741 continue; 742 743 if (S.ActiveTemplateInstantiations.empty()) { 744 if (TypeQuals & Qual.first) 745 S.Diag(Qual.second, DiagID) 746 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar 747 << FixItHint::CreateRemoval(Qual.second); 748 } 749 750 TypeQuals &= ~Qual.first; 751 } 752 } 753 754 /// Return true if this is omitted block return type. Also check type 755 /// attributes and type qualifiers when returning true. 756 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, 757 QualType Result) { 758 if (!isOmittedBlockReturnType(declarator)) 759 return false; 760 761 // Warn if we see type attributes for omitted return type on a block literal. 762 AttributeList *&attrs = 763 declarator.getMutableDeclSpec().getAttributes().getListRef(); 764 AttributeList *prev = nullptr; 765 for (AttributeList *cur = attrs; cur; cur = cur->getNext()) { 766 AttributeList &attr = *cur; 767 // Skip attributes that were marked to be invalid or non-type 768 // attributes. 769 if (attr.isInvalid() || !attr.isTypeAttr()) { 770 prev = cur; 771 continue; 772 } 773 S.Diag(attr.getLoc(), 774 diag::warn_block_literal_attributes_on_omitted_return_type) 775 << attr.getName(); 776 // Remove cur from the list. 777 if (prev) { 778 prev->setNext(cur->getNext()); 779 prev = cur; 780 } else { 781 attrs = cur->getNext(); 782 } 783 } 784 785 // Warn if we see type qualifiers for omitted return type on a block literal. 786 const DeclSpec &DS = declarator.getDeclSpec(); 787 unsigned TypeQuals = DS.getTypeQualifiers(); 788 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1, 789 diag::warn_block_literal_qualifiers_on_omitted_return_type); 790 declarator.getMutableDeclSpec().ClearTypeQualifiers(); 791 792 return true; 793 } 794 795 /// Apply Objective-C type arguments to the given type. 796 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type, 797 ArrayRef<TypeSourceInfo *> typeArgs, 798 SourceRange typeArgsRange, 799 bool failOnError = false) { 800 // We can only apply type arguments to an Objective-C class type. 801 const auto *objcObjectType = type->getAs<ObjCObjectType>(); 802 if (!objcObjectType || !objcObjectType->getInterface()) { 803 S.Diag(loc, diag::err_objc_type_args_non_class) 804 << type 805 << typeArgsRange; 806 807 if (failOnError) 808 return QualType(); 809 return type; 810 } 811 812 // The class type must be parameterized. 813 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface(); 814 ObjCTypeParamList *typeParams = objcClass->getTypeParamList(); 815 if (!typeParams) { 816 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class) 817 << objcClass->getDeclName() 818 << FixItHint::CreateRemoval(typeArgsRange); 819 820 if (failOnError) 821 return QualType(); 822 823 return type; 824 } 825 826 // The type must not already be specialized. 827 if (objcObjectType->isSpecialized()) { 828 S.Diag(loc, diag::err_objc_type_args_specialized_class) 829 << type 830 << FixItHint::CreateRemoval(typeArgsRange); 831 832 if (failOnError) 833 return QualType(); 834 835 return type; 836 } 837 838 // Check the type arguments. 839 SmallVector<QualType, 4> finalTypeArgs; 840 unsigned numTypeParams = typeParams->size(); 841 bool anyPackExpansions = false; 842 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) { 843 TypeSourceInfo *typeArgInfo = typeArgs[i]; 844 QualType typeArg = typeArgInfo->getType(); 845 846 // Type arguments cannot have explicit qualifiers or nullability. 847 // We ignore indirect sources of these, e.g. behind typedefs or 848 // template arguments. 849 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) { 850 bool diagnosed = false; 851 SourceRange rangeToRemove; 852 if (auto attr = qual.getAs<AttributedTypeLoc>()) { 853 rangeToRemove = attr.getLocalSourceRange(); 854 if (attr.getTypePtr()->getImmediateNullability()) { 855 typeArg = attr.getTypePtr()->getModifiedType(); 856 S.Diag(attr.getLocStart(), 857 diag::err_objc_type_arg_explicit_nullability) 858 << typeArg << FixItHint::CreateRemoval(rangeToRemove); 859 diagnosed = true; 860 } 861 } 862 863 if (!diagnosed) { 864 S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified) 865 << typeArg << typeArg.getQualifiers().getAsString() 866 << FixItHint::CreateRemoval(rangeToRemove); 867 } 868 } 869 870 // Remove qualifiers even if they're non-local. 871 typeArg = typeArg.getUnqualifiedType(); 872 873 finalTypeArgs.push_back(typeArg); 874 875 if (typeArg->getAs<PackExpansionType>()) 876 anyPackExpansions = true; 877 878 // Find the corresponding type parameter, if there is one. 879 ObjCTypeParamDecl *typeParam = nullptr; 880 if (!anyPackExpansions) { 881 if (i < numTypeParams) { 882 typeParam = typeParams->begin()[i]; 883 } else { 884 // Too many arguments. 885 S.Diag(loc, diag::err_objc_type_args_wrong_arity) 886 << false 887 << objcClass->getDeclName() 888 << (unsigned)typeArgs.size() 889 << numTypeParams; 890 S.Diag(objcClass->getLocation(), diag::note_previous_decl) 891 << objcClass; 892 893 if (failOnError) 894 return QualType(); 895 896 return type; 897 } 898 } 899 900 // Objective-C object pointer types must be substitutable for the bounds. 901 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) { 902 // If we don't have a type parameter to match against, assume 903 // everything is fine. There was a prior pack expansion that 904 // means we won't be able to match anything. 905 if (!typeParam) { 906 assert(anyPackExpansions && "Too many arguments?"); 907 continue; 908 } 909 910 // Retrieve the bound. 911 QualType bound = typeParam->getUnderlyingType(); 912 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>(); 913 914 // Determine whether the type argument is substitutable for the bound. 915 if (typeArgObjC->isObjCIdType()) { 916 // When the type argument is 'id', the only acceptable type 917 // parameter bound is 'id'. 918 if (boundObjC->isObjCIdType()) 919 continue; 920 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) { 921 // Otherwise, we follow the assignability rules. 922 continue; 923 } 924 925 // Diagnose the mismatch. 926 S.Diag(typeArgInfo->getTypeLoc().getLocStart(), 927 diag::err_objc_type_arg_does_not_match_bound) 928 << typeArg << bound << typeParam->getDeclName(); 929 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) 930 << typeParam->getDeclName(); 931 932 if (failOnError) 933 return QualType(); 934 935 return type; 936 } 937 938 // Block pointer types are permitted for unqualified 'id' bounds. 939 if (typeArg->isBlockPointerType()) { 940 // If we don't have a type parameter to match against, assume 941 // everything is fine. There was a prior pack expansion that 942 // means we won't be able to match anything. 943 if (!typeParam) { 944 assert(anyPackExpansions && "Too many arguments?"); 945 continue; 946 } 947 948 // Retrieve the bound. 949 QualType bound = typeParam->getUnderlyingType(); 950 if (bound->isBlockCompatibleObjCPointerType(S.Context)) 951 continue; 952 953 // Diagnose the mismatch. 954 S.Diag(typeArgInfo->getTypeLoc().getLocStart(), 955 diag::err_objc_type_arg_does_not_match_bound) 956 << typeArg << bound << typeParam->getDeclName(); 957 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) 958 << typeParam->getDeclName(); 959 960 if (failOnError) 961 return QualType(); 962 963 return type; 964 } 965 966 // Dependent types will be checked at instantiation time. 967 if (typeArg->isDependentType()) { 968 continue; 969 } 970 971 // Diagnose non-id-compatible type arguments. 972 S.Diag(typeArgInfo->getTypeLoc().getLocStart(), 973 diag::err_objc_type_arg_not_id_compatible) 974 << typeArg 975 << typeArgInfo->getTypeLoc().getSourceRange(); 976 977 if (failOnError) 978 return QualType(); 979 980 return type; 981 } 982 983 // Make sure we didn't have the wrong number of arguments. 984 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) { 985 S.Diag(loc, diag::err_objc_type_args_wrong_arity) 986 << (typeArgs.size() < typeParams->size()) 987 << objcClass->getDeclName() 988 << (unsigned)finalTypeArgs.size() 989 << (unsigned)numTypeParams; 990 S.Diag(objcClass->getLocation(), diag::note_previous_decl) 991 << objcClass; 992 993 if (failOnError) 994 return QualType(); 995 996 return type; 997 } 998 999 // Success. Form the specialized type. 1000 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false); 1001 } 1002 1003 /// Apply Objective-C protocol qualifiers to the given type. 1004 static QualType applyObjCProtocolQualifiers( 1005 Sema &S, SourceLocation loc, SourceRange range, QualType type, 1006 ArrayRef<ObjCProtocolDecl *> protocols, 1007 const SourceLocation *protocolLocs, 1008 bool failOnError = false) { 1009 ASTContext &ctx = S.Context; 1010 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){ 1011 // FIXME: Check for protocols to which the class type is already 1012 // known to conform. 1013 1014 return ctx.getObjCObjectType(objT->getBaseType(), 1015 objT->getTypeArgsAsWritten(), 1016 protocols, 1017 objT->isKindOfTypeAsWritten()); 1018 } 1019 1020 if (type->isObjCObjectType()) { 1021 // Silently overwrite any existing protocol qualifiers. 1022 // TODO: determine whether that's the right thing to do. 1023 1024 // FIXME: Check for protocols to which the class type is already 1025 // known to conform. 1026 return ctx.getObjCObjectType(type, { }, protocols, false); 1027 } 1028 1029 // id<protocol-list> 1030 if (type->isObjCIdType()) { 1031 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>(); 1032 type = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, { }, protocols, 1033 objPtr->isKindOfType()); 1034 return ctx.getObjCObjectPointerType(type); 1035 } 1036 1037 // Class<protocol-list> 1038 if (type->isObjCClassType()) { 1039 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>(); 1040 type = ctx.getObjCObjectType(ctx.ObjCBuiltinClassTy, { }, protocols, 1041 objPtr->isKindOfType()); 1042 return ctx.getObjCObjectPointerType(type); 1043 } 1044 1045 S.Diag(loc, diag::err_invalid_protocol_qualifiers) 1046 << range; 1047 1048 if (failOnError) 1049 return QualType(); 1050 1051 return type; 1052 } 1053 1054 QualType Sema::BuildObjCObjectType(QualType BaseType, 1055 SourceLocation Loc, 1056 SourceLocation TypeArgsLAngleLoc, 1057 ArrayRef<TypeSourceInfo *> TypeArgs, 1058 SourceLocation TypeArgsRAngleLoc, 1059 SourceLocation ProtocolLAngleLoc, 1060 ArrayRef<ObjCProtocolDecl *> Protocols, 1061 ArrayRef<SourceLocation> ProtocolLocs, 1062 SourceLocation ProtocolRAngleLoc, 1063 bool FailOnError) { 1064 QualType Result = BaseType; 1065 if (!TypeArgs.empty()) { 1066 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs, 1067 SourceRange(TypeArgsLAngleLoc, 1068 TypeArgsRAngleLoc), 1069 FailOnError); 1070 if (FailOnError && Result.isNull()) 1071 return QualType(); 1072 } 1073 1074 if (!Protocols.empty()) { 1075 Result = applyObjCProtocolQualifiers(*this, Loc, 1076 SourceRange(ProtocolLAngleLoc, 1077 ProtocolRAngleLoc), 1078 Result, Protocols, 1079 ProtocolLocs.data(), 1080 FailOnError); 1081 if (FailOnError && Result.isNull()) 1082 return QualType(); 1083 } 1084 1085 return Result; 1086 } 1087 1088 TypeResult Sema::actOnObjCProtocolQualifierType( 1089 SourceLocation lAngleLoc, 1090 ArrayRef<Decl *> protocols, 1091 ArrayRef<SourceLocation> protocolLocs, 1092 SourceLocation rAngleLoc) { 1093 // Form id<protocol-list>. 1094 QualType Result = Context.getObjCObjectType( 1095 Context.ObjCBuiltinIdTy, { }, 1096 llvm::makeArrayRef( 1097 (ObjCProtocolDecl * const *)protocols.data(), 1098 protocols.size()), 1099 false); 1100 Result = Context.getObjCObjectPointerType(Result); 1101 1102 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); 1103 TypeLoc ResultTL = ResultTInfo->getTypeLoc(); 1104 1105 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>(); 1106 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit 1107 1108 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc() 1109 .castAs<ObjCObjectTypeLoc>(); 1110 ObjCObjectTL.setHasBaseTypeAsWritten(false); 1111 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation()); 1112 1113 // No type arguments. 1114 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); 1115 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); 1116 1117 // Fill in protocol qualifiers. 1118 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc); 1119 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc); 1120 for (unsigned i = 0, n = protocols.size(); i != n; ++i) 1121 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]); 1122 1123 // We're done. Return the completed type to the parser. 1124 return CreateParsedType(Result, ResultTInfo); 1125 } 1126 1127 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers( 1128 Scope *S, 1129 SourceLocation Loc, 1130 ParsedType BaseType, 1131 SourceLocation TypeArgsLAngleLoc, 1132 ArrayRef<ParsedType> TypeArgs, 1133 SourceLocation TypeArgsRAngleLoc, 1134 SourceLocation ProtocolLAngleLoc, 1135 ArrayRef<Decl *> Protocols, 1136 ArrayRef<SourceLocation> ProtocolLocs, 1137 SourceLocation ProtocolRAngleLoc) { 1138 TypeSourceInfo *BaseTypeInfo = nullptr; 1139 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo); 1140 if (T.isNull()) 1141 return true; 1142 1143 // Handle missing type-source info. 1144 if (!BaseTypeInfo) 1145 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc); 1146 1147 // Extract type arguments. 1148 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos; 1149 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) { 1150 TypeSourceInfo *TypeArgInfo = nullptr; 1151 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo); 1152 if (TypeArg.isNull()) { 1153 ActualTypeArgInfos.clear(); 1154 break; 1155 } 1156 1157 assert(TypeArgInfo && "No type source info?"); 1158 ActualTypeArgInfos.push_back(TypeArgInfo); 1159 } 1160 1161 // Build the object type. 1162 QualType Result = BuildObjCObjectType( 1163 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(), 1164 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc, 1165 ProtocolLAngleLoc, 1166 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(), 1167 Protocols.size()), 1168 ProtocolLocs, ProtocolRAngleLoc, 1169 /*FailOnError=*/false); 1170 1171 if (Result == T) 1172 return BaseType; 1173 1174 // Create source information for this type. 1175 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); 1176 TypeLoc ResultTL = ResultTInfo->getTypeLoc(); 1177 1178 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an 1179 // object pointer type. Fill in source information for it. 1180 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) { 1181 // The '*' is implicit. 1182 ObjCObjectPointerTL.setStarLoc(SourceLocation()); 1183 ResultTL = ObjCObjectPointerTL.getPointeeLoc(); 1184 } 1185 1186 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>(); 1187 1188 // Type argument information. 1189 if (ObjCObjectTL.getNumTypeArgs() > 0) { 1190 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()); 1191 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc); 1192 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc); 1193 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i) 1194 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]); 1195 } else { 1196 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); 1197 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); 1198 } 1199 1200 // Protocol qualifier information. 1201 if (ObjCObjectTL.getNumProtocols() > 0) { 1202 assert(ObjCObjectTL.getNumProtocols() == Protocols.size()); 1203 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc); 1204 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc); 1205 for (unsigned i = 0, n = Protocols.size(); i != n; ++i) 1206 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]); 1207 } else { 1208 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation()); 1209 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation()); 1210 } 1211 1212 // Base type. 1213 ObjCObjectTL.setHasBaseTypeAsWritten(true); 1214 if (ObjCObjectTL.getType() == T) 1215 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc()); 1216 else 1217 ObjCObjectTL.getBaseLoc().initialize(Context, Loc); 1218 1219 // We're done. Return the completed type to the parser. 1220 return CreateParsedType(Result, ResultTInfo); 1221 } 1222 1223 static StringRef getImageAccessAttrStr(AttributeList *attrs) { 1224 if (attrs) { 1225 1226 AttributeList *Next; 1227 do { 1228 AttributeList &Attr = *attrs; 1229 Next = Attr.getNext(); 1230 if (Attr.getKind() == AttributeList::AT_OpenCLAccess) { 1231 return Attr.getName()->getName(); 1232 } 1233 } while (Next); 1234 } 1235 return ""; 1236 } 1237 1238 /// \brief Convert the specified declspec to the appropriate type 1239 /// object. 1240 /// \param state Specifies the declarator containing the declaration specifier 1241 /// to be converted, along with other associated processing state. 1242 /// \returns The type described by the declaration specifiers. This function 1243 /// never returns null. 1244 static QualType ConvertDeclSpecToType(TypeProcessingState &state) { 1245 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 1246 // checking. 1247 1248 Sema &S = state.getSema(); 1249 Declarator &declarator = state.getDeclarator(); 1250 const DeclSpec &DS = declarator.getDeclSpec(); 1251 SourceLocation DeclLoc = declarator.getIdentifierLoc(); 1252 if (DeclLoc.isInvalid()) 1253 DeclLoc = DS.getLocStart(); 1254 1255 ASTContext &Context = S.Context; 1256 1257 QualType Result; 1258 switch (DS.getTypeSpecType()) { 1259 case DeclSpec::TST_void: 1260 Result = Context.VoidTy; 1261 break; 1262 case DeclSpec::TST_char: 1263 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 1264 Result = Context.CharTy; 1265 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 1266 Result = Context.SignedCharTy; 1267 else { 1268 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 1269 "Unknown TSS value"); 1270 Result = Context.UnsignedCharTy; 1271 } 1272 break; 1273 case DeclSpec::TST_wchar: 1274 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 1275 Result = Context.WCharTy; 1276 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 1277 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 1278 << DS.getSpecifierName(DS.getTypeSpecType(), 1279 Context.getPrintingPolicy()); 1280 Result = Context.getSignedWCharType(); 1281 } else { 1282 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 1283 "Unknown TSS value"); 1284 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 1285 << DS.getSpecifierName(DS.getTypeSpecType(), 1286 Context.getPrintingPolicy()); 1287 Result = Context.getUnsignedWCharType(); 1288 } 1289 break; 1290 case DeclSpec::TST_char16: 1291 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 1292 "Unknown TSS value"); 1293 Result = Context.Char16Ty; 1294 break; 1295 case DeclSpec::TST_char32: 1296 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 1297 "Unknown TSS value"); 1298 Result = Context.Char32Ty; 1299 break; 1300 case DeclSpec::TST_unspecified: 1301 // If this is a missing declspec in a block literal return context, then it 1302 // is inferred from the return statements inside the block. 1303 // The declspec is always missing in a lambda expr context; it is either 1304 // specified with a trailing return type or inferred. 1305 if (S.getLangOpts().CPlusPlus14 && 1306 declarator.getContext() == Declarator::LambdaExprContext) { 1307 // In C++1y, a lambda's implicit return type is 'auto'. 1308 Result = Context.getAutoDeductType(); 1309 break; 1310 } else if (declarator.getContext() == Declarator::LambdaExprContext || 1311 checkOmittedBlockReturnType(S, declarator, 1312 Context.DependentTy)) { 1313 Result = Context.DependentTy; 1314 break; 1315 } 1316 1317 // Unspecified typespec defaults to int in C90. However, the C90 grammar 1318 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 1319 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 1320 // Note that the one exception to this is function definitions, which are 1321 // allowed to be completely missing a declspec. This is handled in the 1322 // parser already though by it pretending to have seen an 'int' in this 1323 // case. 1324 if (S.getLangOpts().ImplicitInt) { 1325 // In C89 mode, we only warn if there is a completely missing declspec 1326 // when one is not allowed. 1327 if (DS.isEmpty()) { 1328 S.Diag(DeclLoc, diag::ext_missing_declspec) 1329 << DS.getSourceRange() 1330 << FixItHint::CreateInsertion(DS.getLocStart(), "int"); 1331 } 1332 } else if (!DS.hasTypeSpecifier()) { 1333 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 1334 // "At least one type specifier shall be given in the declaration 1335 // specifiers in each declaration, and in the specifier-qualifier list in 1336 // each struct declaration and type name." 1337 if (S.getLangOpts().CPlusPlus) { 1338 S.Diag(DeclLoc, diag::err_missing_type_specifier) 1339 << DS.getSourceRange(); 1340 1341 // When this occurs in C++ code, often something is very broken with the 1342 // value being declared, poison it as invalid so we don't get chains of 1343 // errors. 1344 declarator.setInvalidType(true); 1345 } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){ 1346 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type) 1347 << DS.getSourceRange(); 1348 declarator.setInvalidType(true); 1349 } else { 1350 S.Diag(DeclLoc, diag::ext_missing_type_specifier) 1351 << DS.getSourceRange(); 1352 } 1353 } 1354 1355 // FALL THROUGH. 1356 case DeclSpec::TST_int: { 1357 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 1358 switch (DS.getTypeSpecWidth()) { 1359 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 1360 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 1361 case DeclSpec::TSW_long: Result = Context.LongTy; break; 1362 case DeclSpec::TSW_longlong: 1363 Result = Context.LongLongTy; 1364 1365 // 'long long' is a C99 or C++11 feature. 1366 if (!S.getLangOpts().C99) { 1367 if (S.getLangOpts().CPlusPlus) 1368 S.Diag(DS.getTypeSpecWidthLoc(), 1369 S.getLangOpts().CPlusPlus11 ? 1370 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 1371 else 1372 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 1373 } 1374 break; 1375 } 1376 } else { 1377 switch (DS.getTypeSpecWidth()) { 1378 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 1379 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 1380 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 1381 case DeclSpec::TSW_longlong: 1382 Result = Context.UnsignedLongLongTy; 1383 1384 // 'long long' is a C99 or C++11 feature. 1385 if (!S.getLangOpts().C99) { 1386 if (S.getLangOpts().CPlusPlus) 1387 S.Diag(DS.getTypeSpecWidthLoc(), 1388 S.getLangOpts().CPlusPlus11 ? 1389 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 1390 else 1391 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 1392 } 1393 break; 1394 } 1395 } 1396 break; 1397 } 1398 case DeclSpec::TST_int128: 1399 if (!S.Context.getTargetInfo().hasInt128Type()) 1400 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported); 1401 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) 1402 Result = Context.UnsignedInt128Ty; 1403 else 1404 Result = Context.Int128Ty; 1405 break; 1406 case DeclSpec::TST_half: Result = Context.HalfTy; break; 1407 case DeclSpec::TST_float: Result = Context.FloatTy; break; 1408 case DeclSpec::TST_double: 1409 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 1410 Result = Context.LongDoubleTy; 1411 else 1412 Result = Context.DoubleTy; 1413 1414 if (S.getLangOpts().OpenCL && 1415 !((S.getLangOpts().OpenCLVersion >= 120) || 1416 S.getOpenCLOptions().cl_khr_fp64)) { 1417 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension) 1418 << Result << "cl_khr_fp64"; 1419 declarator.setInvalidType(true); 1420 } 1421 break; 1422 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 1423 break; 1424 case DeclSpec::TST_decimal32: // _Decimal32 1425 case DeclSpec::TST_decimal64: // _Decimal64 1426 case DeclSpec::TST_decimal128: // _Decimal128 1427 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 1428 Result = Context.IntTy; 1429 declarator.setInvalidType(true); 1430 break; 1431 case DeclSpec::TST_class: 1432 case DeclSpec::TST_enum: 1433 case DeclSpec::TST_union: 1434 case DeclSpec::TST_struct: 1435 case DeclSpec::TST_interface: { 1436 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl()); 1437 if (!D) { 1438 // This can happen in C++ with ambiguous lookups. 1439 Result = Context.IntTy; 1440 declarator.setInvalidType(true); 1441 break; 1442 } 1443 1444 // If the type is deprecated or unavailable, diagnose it. 1445 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); 1446 1447 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 1448 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!"); 1449 1450 // TypeQuals handled by caller. 1451 Result = Context.getTypeDeclType(D); 1452 1453 // In both C and C++, make an ElaboratedType. 1454 ElaboratedTypeKeyword Keyword 1455 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); 1456 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result); 1457 break; 1458 } 1459 case DeclSpec::TST_typename: { 1460 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 1461 DS.getTypeSpecSign() == 0 && 1462 "Can't handle qualifiers on typedef names yet!"); 1463 Result = S.GetTypeFromParser(DS.getRepAsType()); 1464 if (Result.isNull()) { 1465 declarator.setInvalidType(true); 1466 } else if (S.getLangOpts().OpenCL) { 1467 if (Result->getAs<AtomicType>()) { 1468 StringRef TypeName = Result.getBaseTypeIdentifier()->getName(); 1469 bool NoExtTypes = 1470 llvm::StringSwitch<bool>(TypeName) 1471 .Cases("atomic_int", "atomic_uint", "atomic_float", 1472 "atomic_flag", true) 1473 .Default(false); 1474 if (!S.getOpenCLOptions().cl_khr_int64_base_atomics && !NoExtTypes) { 1475 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension) 1476 << Result << "cl_khr_int64_base_atomics"; 1477 declarator.setInvalidType(true); 1478 } 1479 if (!S.getOpenCLOptions().cl_khr_int64_extended_atomics && 1480 !NoExtTypes) { 1481 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension) 1482 << Result << "cl_khr_int64_extended_atomics"; 1483 declarator.setInvalidType(true); 1484 } 1485 if (!S.getOpenCLOptions().cl_khr_fp64 && 1486 !TypeName.compare("atomic_double")) { 1487 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension) 1488 << Result << "cl_khr_fp64"; 1489 declarator.setInvalidType(true); 1490 } 1491 } else if (!S.getOpenCLOptions().cl_khr_gl_msaa_sharing && 1492 (Result->isOCLImage2dArrayMSAADepthROType() || 1493 Result->isOCLImage2dArrayMSAADepthWOType() || 1494 Result->isOCLImage2dArrayMSAADepthRWType() || 1495 Result->isOCLImage2dArrayMSAAROType() || 1496 Result->isOCLImage2dArrayMSAARWType() || 1497 Result->isOCLImage2dArrayMSAAWOType() || 1498 Result->isOCLImage2dMSAADepthROType() || 1499 Result->isOCLImage2dMSAADepthRWType() || 1500 Result->isOCLImage2dMSAADepthWOType() || 1501 Result->isOCLImage2dMSAAROType() || 1502 Result->isOCLImage2dMSAARWType() || 1503 Result->isOCLImage2dMSAAWOType())) { 1504 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension) 1505 << Result << "cl_khr_gl_msaa_sharing"; 1506 declarator.setInvalidType(true); 1507 } 1508 } 1509 1510 // TypeQuals handled by caller. 1511 break; 1512 } 1513 case DeclSpec::TST_typeofType: 1514 // FIXME: Preserve type source info. 1515 Result = S.GetTypeFromParser(DS.getRepAsType()); 1516 assert(!Result.isNull() && "Didn't get a type for typeof?"); 1517 if (!Result->isDependentType()) 1518 if (const TagType *TT = Result->getAs<TagType>()) 1519 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); 1520 // TypeQuals handled by caller. 1521 Result = Context.getTypeOfType(Result); 1522 break; 1523 case DeclSpec::TST_typeofExpr: { 1524 Expr *E = DS.getRepAsExpr(); 1525 assert(E && "Didn't get an expression for typeof?"); 1526 // TypeQuals handled by caller. 1527 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); 1528 if (Result.isNull()) { 1529 Result = Context.IntTy; 1530 declarator.setInvalidType(true); 1531 } 1532 break; 1533 } 1534 case DeclSpec::TST_decltype: { 1535 Expr *E = DS.getRepAsExpr(); 1536 assert(E && "Didn't get an expression for decltype?"); 1537 // TypeQuals handled by caller. 1538 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); 1539 if (Result.isNull()) { 1540 Result = Context.IntTy; 1541 declarator.setInvalidType(true); 1542 } 1543 break; 1544 } 1545 case DeclSpec::TST_underlyingType: 1546 Result = S.GetTypeFromParser(DS.getRepAsType()); 1547 assert(!Result.isNull() && "Didn't get a type for __underlying_type?"); 1548 Result = S.BuildUnaryTransformType(Result, 1549 UnaryTransformType::EnumUnderlyingType, 1550 DS.getTypeSpecTypeLoc()); 1551 if (Result.isNull()) { 1552 Result = Context.IntTy; 1553 declarator.setInvalidType(true); 1554 } 1555 break; 1556 1557 case DeclSpec::TST_auto: 1558 // TypeQuals handled by caller. 1559 // If auto is mentioned in a lambda parameter context, convert it to a 1560 // template parameter type immediately, with the appropriate depth and 1561 // index, and update sema's state (LambdaScopeInfo) for the current lambda 1562 // being analyzed (which tracks the invented type template parameter). 1563 if (declarator.getContext() == Declarator::LambdaExprParameterContext) { 1564 sema::LambdaScopeInfo *LSI = S.getCurLambda(); 1565 assert(LSI && "No LambdaScopeInfo on the stack!"); 1566 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth; 1567 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size(); 1568 const bool IsParameterPack = declarator.hasEllipsis(); 1569 1570 // Turns out we must create the TemplateTypeParmDecl here to 1571 // retrieve the corresponding template parameter type. 1572 TemplateTypeParmDecl *CorrespondingTemplateParam = 1573 TemplateTypeParmDecl::Create(Context, 1574 // Temporarily add to the TranslationUnit DeclContext. When the 1575 // associated TemplateParameterList is attached to a template 1576 // declaration (such as FunctionTemplateDecl), the DeclContext 1577 // for each template parameter gets updated appropriately via 1578 // a call to AdoptTemplateParameterList. 1579 Context.getTranslationUnitDecl(), 1580 /*KeyLoc*/ SourceLocation(), 1581 /*NameLoc*/ declarator.getLocStart(), 1582 TemplateParameterDepth, 1583 AutoParameterPosition, // our template param index 1584 /* Identifier*/ nullptr, false, IsParameterPack); 1585 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam); 1586 // Replace the 'auto' in the function parameter with this invented 1587 // template type parameter. 1588 Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0); 1589 } else { 1590 Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false); 1591 } 1592 break; 1593 1594 case DeclSpec::TST_auto_type: 1595 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false); 1596 break; 1597 1598 case DeclSpec::TST_decltype_auto: 1599 Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto, 1600 /*IsDependent*/ false); 1601 break; 1602 1603 case DeclSpec::TST_unknown_anytype: 1604 Result = Context.UnknownAnyTy; 1605 break; 1606 1607 case DeclSpec::TST_atomic: 1608 Result = S.GetTypeFromParser(DS.getRepAsType()); 1609 assert(!Result.isNull() && "Didn't get a type for _Atomic?"); 1610 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); 1611 if (Result.isNull()) { 1612 Result = Context.IntTy; 1613 declarator.setInvalidType(true); 1614 } 1615 break; 1616 1617 #define GENERIC_IMAGE_TYPE(ImgType, Id) \ 1618 case DeclSpec::TST_##ImgType##_t: \ 1619 Result = llvm::StringSwitch<QualType>( \ 1620 getImageAccessAttrStr(DS.getAttributes().getList())) \ 1621 .Cases("write_only", "__write_only", Context.Id##WOTy) \ 1622 .Cases("read_write", "__read_write", Context.Id##RWTy) \ 1623 .Default(Context.Id##ROTy); \ 1624 break; 1625 #include "clang/Basic/OpenCLImageTypes.def" 1626 1627 case DeclSpec::TST_error: 1628 Result = Context.IntTy; 1629 declarator.setInvalidType(true); 1630 break; 1631 } 1632 1633 // Handle complex types. 1634 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 1635 if (S.getLangOpts().Freestanding) 1636 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 1637 Result = Context.getComplexType(Result); 1638 } else if (DS.isTypeAltiVecVector()) { 1639 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); 1640 assert(typeSize > 0 && "type size for vector must be greater than 0 bits"); 1641 VectorType::VectorKind VecKind = VectorType::AltiVecVector; 1642 if (DS.isTypeAltiVecPixel()) 1643 VecKind = VectorType::AltiVecPixel; 1644 else if (DS.isTypeAltiVecBool()) 1645 VecKind = VectorType::AltiVecBool; 1646 Result = Context.getVectorType(Result, 128/typeSize, VecKind); 1647 } 1648 1649 // FIXME: Imaginary. 1650 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) 1651 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); 1652 1653 // Before we process any type attributes, synthesize a block literal 1654 // function declarator if necessary. 1655 if (declarator.getContext() == Declarator::BlockLiteralContext) 1656 maybeSynthesizeBlockSignature(state, Result); 1657 1658 // Apply any type attributes from the decl spec. This may cause the 1659 // list of type attributes to be temporarily saved while the type 1660 // attributes are pushed around. 1661 // pipe attributes will be handled later ( at GetFullTypeForDeclarator ) 1662 if (!DS.isTypeSpecPipe()) 1663 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList()); 1664 1665 // Apply const/volatile/restrict qualifiers to T. 1666 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 1667 // Warn about CV qualifiers on function types. 1668 // C99 6.7.3p8: 1669 // If the specification of a function type includes any type qualifiers, 1670 // the behavior is undefined. 1671 // C++11 [dcl.fct]p7: 1672 // The effect of a cv-qualifier-seq in a function declarator is not the 1673 // same as adding cv-qualification on top of the function type. In the 1674 // latter case, the cv-qualifiers are ignored. 1675 if (TypeQuals && Result->isFunctionType()) { 1676 diagnoseAndRemoveTypeQualifiers( 1677 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile, 1678 S.getLangOpts().CPlusPlus 1679 ? diag::warn_typecheck_function_qualifiers_ignored 1680 : diag::warn_typecheck_function_qualifiers_unspecified); 1681 // No diagnostic for 'restrict' or '_Atomic' applied to a 1682 // function type; we'll diagnose those later, in BuildQualifiedType. 1683 } 1684 1685 // C++11 [dcl.ref]p1: 1686 // Cv-qualified references are ill-formed except when the 1687 // cv-qualifiers are introduced through the use of a typedef-name 1688 // or decltype-specifier, in which case the cv-qualifiers are ignored. 1689 // 1690 // There don't appear to be any other contexts in which a cv-qualified 1691 // reference type could be formed, so the 'ill-formed' clause here appears 1692 // to never happen. 1693 if (TypeQuals && Result->isReferenceType()) { 1694 diagnoseAndRemoveTypeQualifiers( 1695 S, DS, TypeQuals, Result, 1696 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic, 1697 diag::warn_typecheck_reference_qualifiers); 1698 } 1699 1700 // C90 6.5.3 constraints: "The same type qualifier shall not appear more 1701 // than once in the same specifier-list or qualifier-list, either directly 1702 // or via one or more typedefs." 1703 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus 1704 && TypeQuals & Result.getCVRQualifiers()) { 1705 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { 1706 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) 1707 << "const"; 1708 } 1709 1710 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { 1711 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) 1712 << "volatile"; 1713 } 1714 1715 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to 1716 // produce a warning in this case. 1717 } 1718 1719 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS); 1720 1721 // If adding qualifiers fails, just use the unqualified type. 1722 if (Qualified.isNull()) 1723 declarator.setInvalidType(true); 1724 else 1725 Result = Qualified; 1726 } 1727 1728 assert(!Result.isNull() && "This function should not return a null type"); 1729 return Result; 1730 } 1731 1732 static std::string getPrintableNameForEntity(DeclarationName Entity) { 1733 if (Entity) 1734 return Entity.getAsString(); 1735 1736 return "type name"; 1737 } 1738 1739 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 1740 Qualifiers Qs, const DeclSpec *DS) { 1741 if (T.isNull()) 1742 return QualType(); 1743 1744 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 1745 // object or incomplete types shall not be restrict-qualified." 1746 if (Qs.hasRestrict()) { 1747 unsigned DiagID = 0; 1748 QualType ProblemTy; 1749 1750 if (T->isAnyPointerType() || T->isReferenceType() || 1751 T->isMemberPointerType()) { 1752 QualType EltTy; 1753 if (T->isObjCObjectPointerType()) 1754 EltTy = T; 1755 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) 1756 EltTy = PTy->getPointeeType(); 1757 else 1758 EltTy = T->getPointeeType(); 1759 1760 // If we have a pointer or reference, the pointee must have an object 1761 // incomplete type. 1762 if (!EltTy->isIncompleteOrObjectType()) { 1763 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 1764 ProblemTy = EltTy; 1765 } 1766 } else if (!T->isDependentType()) { 1767 DiagID = diag::err_typecheck_invalid_restrict_not_pointer; 1768 ProblemTy = T; 1769 } 1770 1771 if (DiagID) { 1772 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; 1773 Qs.removeRestrict(); 1774 } 1775 } 1776 1777 return Context.getQualifiedType(T, Qs); 1778 } 1779 1780 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 1781 unsigned CVRA, const DeclSpec *DS) { 1782 if (T.isNull()) 1783 return QualType(); 1784 1785 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic. 1786 unsigned CVR = CVRA & ~DeclSpec::TQ_atomic; 1787 1788 // C11 6.7.3/5: 1789 // If the same qualifier appears more than once in the same 1790 // specifier-qualifier-list, either directly or via one or more typedefs, 1791 // the behavior is the same as if it appeared only once. 1792 // 1793 // It's not specified what happens when the _Atomic qualifier is applied to 1794 // a type specified with the _Atomic specifier, but we assume that this 1795 // should be treated as if the _Atomic qualifier appeared multiple times. 1796 if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) { 1797 // C11 6.7.3/5: 1798 // If other qualifiers appear along with the _Atomic qualifier in a 1799 // specifier-qualifier-list, the resulting type is the so-qualified 1800 // atomic type. 1801 // 1802 // Don't need to worry about array types here, since _Atomic can't be 1803 // applied to such types. 1804 SplitQualType Split = T.getSplitUnqualifiedType(); 1805 T = BuildAtomicType(QualType(Split.Ty, 0), 1806 DS ? DS->getAtomicSpecLoc() : Loc); 1807 if (T.isNull()) 1808 return T; 1809 Split.Quals.addCVRQualifiers(CVR); 1810 return BuildQualifiedType(T, Loc, Split.Quals); 1811 } 1812 1813 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS); 1814 } 1815 1816 /// \brief Build a paren type including \p T. 1817 QualType Sema::BuildParenType(QualType T) { 1818 return Context.getParenType(T); 1819 } 1820 1821 /// Given that we're building a pointer or reference to the given 1822 static QualType inferARCLifetimeForPointee(Sema &S, QualType type, 1823 SourceLocation loc, 1824 bool isReference) { 1825 // Bail out if retention is unrequired or already specified. 1826 if (!type->isObjCLifetimeType() || 1827 type.getObjCLifetime() != Qualifiers::OCL_None) 1828 return type; 1829 1830 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; 1831 1832 // If the object type is const-qualified, we can safely use 1833 // __unsafe_unretained. This is safe (because there are no read 1834 // barriers), and it'll be safe to coerce anything but __weak* to 1835 // the resulting type. 1836 if (type.isConstQualified()) { 1837 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1838 1839 // Otherwise, check whether the static type does not require 1840 // retaining. This currently only triggers for Class (possibly 1841 // protocol-qualifed, and arrays thereof). 1842 } else if (type->isObjCARCImplicitlyUnretainedType()) { 1843 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1844 1845 // If we are in an unevaluated context, like sizeof, skip adding a 1846 // qualification. 1847 } else if (S.isUnevaluatedContext()) { 1848 return type; 1849 1850 // If that failed, give an error and recover using __strong. __strong 1851 // is the option most likely to prevent spurious second-order diagnostics, 1852 // like when binding a reference to a field. 1853 } else { 1854 // These types can show up in private ivars in system headers, so 1855 // we need this to not be an error in those cases. Instead we 1856 // want to delay. 1857 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 1858 S.DelayedDiagnostics.add( 1859 sema::DelayedDiagnostic::makeForbiddenType(loc, 1860 diag::err_arc_indirect_no_ownership, type, isReference)); 1861 } else { 1862 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; 1863 } 1864 implicitLifetime = Qualifiers::OCL_Strong; 1865 } 1866 assert(implicitLifetime && "didn't infer any lifetime!"); 1867 1868 Qualifiers qs; 1869 qs.addObjCLifetime(implicitLifetime); 1870 return S.Context.getQualifiedType(type, qs); 1871 } 1872 1873 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ 1874 std::string Quals = 1875 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString(); 1876 1877 switch (FnTy->getRefQualifier()) { 1878 case RQ_None: 1879 break; 1880 1881 case RQ_LValue: 1882 if (!Quals.empty()) 1883 Quals += ' '; 1884 Quals += '&'; 1885 break; 1886 1887 case RQ_RValue: 1888 if (!Quals.empty()) 1889 Quals += ' '; 1890 Quals += "&&"; 1891 break; 1892 } 1893 1894 return Quals; 1895 } 1896 1897 namespace { 1898 /// Kinds of declarator that cannot contain a qualified function type. 1899 /// 1900 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: 1901 /// a function type with a cv-qualifier or a ref-qualifier can only appear 1902 /// at the topmost level of a type. 1903 /// 1904 /// Parens and member pointers are permitted. We don't diagnose array and 1905 /// function declarators, because they don't allow function types at all. 1906 /// 1907 /// The values of this enum are used in diagnostics. 1908 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference }; 1909 } // end anonymous namespace 1910 1911 /// Check whether the type T is a qualified function type, and if it is, 1912 /// diagnose that it cannot be contained within the given kind of declarator. 1913 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, 1914 QualifiedFunctionKind QFK) { 1915 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 1916 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); 1917 if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None)) 1918 return false; 1919 1920 S.Diag(Loc, diag::err_compound_qualified_function_type) 1921 << QFK << isa<FunctionType>(T.IgnoreParens()) << T 1922 << getFunctionQualifiersAsString(FPT); 1923 return true; 1924 } 1925 1926 /// \brief Build a pointer type. 1927 /// 1928 /// \param T The type to which we'll be building a pointer. 1929 /// 1930 /// \param Loc The location of the entity whose type involves this 1931 /// pointer type or, if there is no such entity, the location of the 1932 /// type that will have pointer type. 1933 /// 1934 /// \param Entity The name of the entity that involves the pointer 1935 /// type, if known. 1936 /// 1937 /// \returns A suitable pointer type, if there are no 1938 /// errors. Otherwise, returns a NULL type. 1939 QualType Sema::BuildPointerType(QualType T, 1940 SourceLocation Loc, DeclarationName Entity) { 1941 if (T->isReferenceType()) { 1942 // C++ 8.3.2p4: There shall be no ... pointers to references ... 1943 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 1944 << getPrintableNameForEntity(Entity) << T; 1945 return QualType(); 1946 } 1947 1948 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer)) 1949 return QualType(); 1950 1951 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType"); 1952 1953 // In ARC, it is forbidden to build pointers to unqualified pointers. 1954 if (getLangOpts().ObjCAutoRefCount) 1955 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); 1956 1957 // Build the pointer type. 1958 return Context.getPointerType(T); 1959 } 1960 1961 /// \brief Build a reference type. 1962 /// 1963 /// \param T The type to which we'll be building a reference. 1964 /// 1965 /// \param Loc The location of the entity whose type involves this 1966 /// reference type or, if there is no such entity, the location of the 1967 /// type that will have reference type. 1968 /// 1969 /// \param Entity The name of the entity that involves the reference 1970 /// type, if known. 1971 /// 1972 /// \returns A suitable reference type, if there are no 1973 /// errors. Otherwise, returns a NULL type. 1974 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, 1975 SourceLocation Loc, 1976 DeclarationName Entity) { 1977 assert(Context.getCanonicalType(T) != Context.OverloadTy && 1978 "Unresolved overloaded function type"); 1979 1980 // C++0x [dcl.ref]p6: 1981 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a 1982 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a 1983 // type T, an attempt to create the type "lvalue reference to cv TR" creates 1984 // the type "lvalue reference to T", while an attempt to create the type 1985 // "rvalue reference to cv TR" creates the type TR. 1986 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); 1987 1988 // C++ [dcl.ref]p4: There shall be no references to references. 1989 // 1990 // According to C++ DR 106, references to references are only 1991 // diagnosed when they are written directly (e.g., "int & &"), 1992 // but not when they happen via a typedef: 1993 // 1994 // typedef int& intref; 1995 // typedef intref& intref2; 1996 // 1997 // Parser::ParseDeclaratorInternal diagnoses the case where 1998 // references are written directly; here, we handle the 1999 // collapsing of references-to-references as described in C++0x. 2000 // DR 106 and 540 introduce reference-collapsing into C++98/03. 2001 2002 // C++ [dcl.ref]p1: 2003 // A declarator that specifies the type "reference to cv void" 2004 // is ill-formed. 2005 if (T->isVoidType()) { 2006 Diag(Loc, diag::err_reference_to_void); 2007 return QualType(); 2008 } 2009 2010 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference)) 2011 return QualType(); 2012 2013 // In ARC, it is forbidden to build references to unqualified pointers. 2014 if (getLangOpts().ObjCAutoRefCount) 2015 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); 2016 2017 // Handle restrict on references. 2018 if (LValueRef) 2019 return Context.getLValueReferenceType(T, SpelledAsLValue); 2020 return Context.getRValueReferenceType(T); 2021 } 2022 2023 /// \brief Build a Pipe type. 2024 /// 2025 /// \param T The type to which we'll be building a Pipe. 2026 /// 2027 /// \param Loc We do not use it for now. 2028 /// 2029 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a 2030 /// NULL type. 2031 QualType Sema::BuildPipeType(QualType T, SourceLocation Loc) { 2032 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType"); 2033 2034 // Build the pipe type. 2035 return Context.getPipeType(T); 2036 } 2037 2038 /// Check whether the specified array size makes the array type a VLA. If so, 2039 /// return true, if not, return the size of the array in SizeVal. 2040 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) { 2041 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode 2042 // (like gnu99, but not c99) accept any evaluatable value as an extension. 2043 class VLADiagnoser : public Sema::VerifyICEDiagnoser { 2044 public: 2045 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {} 2046 2047 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 2048 } 2049 2050 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override { 2051 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR; 2052 } 2053 } Diagnoser; 2054 2055 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser, 2056 S.LangOpts.GNUMode).isInvalid(); 2057 } 2058 2059 /// \brief Build an array type. 2060 /// 2061 /// \param T The type of each element in the array. 2062 /// 2063 /// \param ASM C99 array size modifier (e.g., '*', 'static'). 2064 /// 2065 /// \param ArraySize Expression describing the size of the array. 2066 /// 2067 /// \param Brackets The range from the opening '[' to the closing ']'. 2068 /// 2069 /// \param Entity The name of the entity that involves the array 2070 /// type, if known. 2071 /// 2072 /// \returns A suitable array type, if there are no errors. Otherwise, 2073 /// returns a NULL type. 2074 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 2075 Expr *ArraySize, unsigned Quals, 2076 SourceRange Brackets, DeclarationName Entity) { 2077 2078 SourceLocation Loc = Brackets.getBegin(); 2079 if (getLangOpts().CPlusPlus) { 2080 // C++ [dcl.array]p1: 2081 // T is called the array element type; this type shall not be a reference 2082 // type, the (possibly cv-qualified) type void, a function type or an 2083 // abstract class type. 2084 // 2085 // C++ [dcl.array]p3: 2086 // When several "array of" specifications are adjacent, [...] only the 2087 // first of the constant expressions that specify the bounds of the arrays 2088 // may be omitted. 2089 // 2090 // Note: function types are handled in the common path with C. 2091 if (T->isReferenceType()) { 2092 Diag(Loc, diag::err_illegal_decl_array_of_references) 2093 << getPrintableNameForEntity(Entity) << T; 2094 return QualType(); 2095 } 2096 2097 if (T->isVoidType() || T->isIncompleteArrayType()) { 2098 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; 2099 return QualType(); 2100 } 2101 2102 if (RequireNonAbstractType(Brackets.getBegin(), T, 2103 diag::err_array_of_abstract_type)) 2104 return QualType(); 2105 2106 // Mentioning a member pointer type for an array type causes us to lock in 2107 // an inheritance model, even if it's inside an unused typedef. 2108 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 2109 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) 2110 if (!MPTy->getClass()->isDependentType()) 2111 (void)isCompleteType(Loc, T); 2112 2113 } else { 2114 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 2115 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 2116 if (RequireCompleteType(Loc, T, 2117 diag::err_illegal_decl_array_incomplete_type)) 2118 return QualType(); 2119 } 2120 2121 if (T->isFunctionType()) { 2122 Diag(Loc, diag::err_illegal_decl_array_of_functions) 2123 << getPrintableNameForEntity(Entity) << T; 2124 return QualType(); 2125 } 2126 2127 if (const RecordType *EltTy = T->getAs<RecordType>()) { 2128 // If the element type is a struct or union that contains a variadic 2129 // array, accept it as a GNU extension: C99 6.7.2.1p2. 2130 if (EltTy->getDecl()->hasFlexibleArrayMember()) 2131 Diag(Loc, diag::ext_flexible_array_in_array) << T; 2132 } else if (T->isObjCObjectType()) { 2133 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 2134 return QualType(); 2135 } 2136 2137 // Do placeholder conversions on the array size expression. 2138 if (ArraySize && ArraySize->hasPlaceholderType()) { 2139 ExprResult Result = CheckPlaceholderExpr(ArraySize); 2140 if (Result.isInvalid()) return QualType(); 2141 ArraySize = Result.get(); 2142 } 2143 2144 // Do lvalue-to-rvalue conversions on the array size expression. 2145 if (ArraySize && !ArraySize->isRValue()) { 2146 ExprResult Result = DefaultLvalueConversion(ArraySize); 2147 if (Result.isInvalid()) 2148 return QualType(); 2149 2150 ArraySize = Result.get(); 2151 } 2152 2153 // C99 6.7.5.2p1: The size expression shall have integer type. 2154 // C++11 allows contextual conversions to such types. 2155 if (!getLangOpts().CPlusPlus11 && 2156 ArraySize && !ArraySize->isTypeDependent() && 2157 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 2158 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 2159 << ArraySize->getType() << ArraySize->getSourceRange(); 2160 return QualType(); 2161 } 2162 2163 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); 2164 if (!ArraySize) { 2165 if (ASM == ArrayType::Star) 2166 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets); 2167 else 2168 T = Context.getIncompleteArrayType(T, ASM, Quals); 2169 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { 2170 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 2171 } else if ((!T->isDependentType() && !T->isIncompleteType() && 2172 !T->isConstantSizeType()) || 2173 isArraySizeVLA(*this, ArraySize, ConstVal)) { 2174 // Even in C++11, don't allow contextual conversions in the array bound 2175 // of a VLA. 2176 if (getLangOpts().CPlusPlus11 && 2177 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 2178 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 2179 << ArraySize->getType() << ArraySize->getSourceRange(); 2180 return QualType(); 2181 } 2182 2183 // C99: an array with an element type that has a non-constant-size is a VLA. 2184 // C99: an array with a non-ICE size is a VLA. We accept any expression 2185 // that we can fold to a non-zero positive value as an extension. 2186 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 2187 } else { 2188 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 2189 // have a value greater than zero. 2190 if (ConstVal.isSigned() && ConstVal.isNegative()) { 2191 if (Entity) 2192 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size) 2193 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange(); 2194 else 2195 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size) 2196 << ArraySize->getSourceRange(); 2197 return QualType(); 2198 } 2199 if (ConstVal == 0) { 2200 // GCC accepts zero sized static arrays. We allow them when 2201 // we're not in a SFINAE context. 2202 Diag(ArraySize->getLocStart(), 2203 isSFINAEContext()? diag::err_typecheck_zero_array_size 2204 : diag::ext_typecheck_zero_array_size) 2205 << ArraySize->getSourceRange(); 2206 2207 if (ASM == ArrayType::Static) { 2208 Diag(ArraySize->getLocStart(), 2209 diag::warn_typecheck_zero_static_array_size) 2210 << ArraySize->getSourceRange(); 2211 ASM = ArrayType::Normal; 2212 } 2213 } else if (!T->isDependentType() && !T->isVariablyModifiedType() && 2214 !T->isIncompleteType() && !T->isUndeducedType()) { 2215 // Is the array too large? 2216 unsigned ActiveSizeBits 2217 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal); 2218 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 2219 Diag(ArraySize->getLocStart(), diag::err_array_too_large) 2220 << ConstVal.toString(10) 2221 << ArraySize->getSourceRange(); 2222 return QualType(); 2223 } 2224 } 2225 2226 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); 2227 } 2228 2229 // OpenCL v1.2 s6.9.d: variable length arrays are not supported. 2230 if (getLangOpts().OpenCL && T->isVariableArrayType()) { 2231 Diag(Loc, diag::err_opencl_vla); 2232 return QualType(); 2233 } 2234 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 2235 if (!getLangOpts().C99) { 2236 if (T->isVariableArrayType()) { 2237 // Prohibit the use of VLAs during template argument deduction. 2238 if (isSFINAEContext()) { 2239 Diag(Loc, diag::err_vla_in_sfinae); 2240 return QualType(); 2241 } 2242 // Just extwarn about VLAs. 2243 else 2244 Diag(Loc, diag::ext_vla); 2245 } else if (ASM != ArrayType::Normal || Quals != 0) 2246 Diag(Loc, 2247 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx 2248 : diag::ext_c99_array_usage) << ASM; 2249 } 2250 2251 if (T->isVariableArrayType()) { 2252 // Warn about VLAs for -Wvla. 2253 Diag(Loc, diag::warn_vla_used); 2254 } 2255 2256 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported. 2257 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported. 2258 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported. 2259 if (getLangOpts().OpenCL) { 2260 const QualType ArrType = Context.getBaseElementType(T); 2261 if (ArrType->isBlockPointerType() || ArrType->isPipeType() || 2262 ArrType->isSamplerT() || ArrType->isImageType()) { 2263 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType; 2264 return QualType(); 2265 } 2266 } 2267 2268 return T; 2269 } 2270 2271 /// \brief Build an ext-vector type. 2272 /// 2273 /// Run the required checks for the extended vector type. 2274 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, 2275 SourceLocation AttrLoc) { 2276 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined 2277 // in conjunction with complex types (pointers, arrays, functions, etc.). 2278 // 2279 // Additionally, OpenCL prohibits vectors of booleans (they're considered a 2280 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects 2281 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors 2282 // of bool aren't allowed. 2283 if ((!T->isDependentType() && !T->isIntegerType() && 2284 !T->isRealFloatingType()) || 2285 T->isBooleanType()) { 2286 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 2287 return QualType(); 2288 } 2289 2290 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { 2291 llvm::APSInt vecSize(32); 2292 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { 2293 Diag(AttrLoc, diag::err_attribute_argument_type) 2294 << "ext_vector_type" << AANT_ArgumentIntegerConstant 2295 << ArraySize->getSourceRange(); 2296 return QualType(); 2297 } 2298 2299 // Unlike gcc's vector_size attribute, the size is specified as the 2300 // number of elements, not the number of bytes. 2301 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 2302 2303 if (vectorSize == 0) { 2304 Diag(AttrLoc, diag::err_attribute_zero_size) 2305 << ArraySize->getSourceRange(); 2306 return QualType(); 2307 } 2308 2309 if (VectorType::isVectorSizeTooLarge(vectorSize)) { 2310 Diag(AttrLoc, diag::err_attribute_size_too_large) 2311 << ArraySize->getSourceRange(); 2312 return QualType(); 2313 } 2314 2315 return Context.getExtVectorType(T, vectorSize); 2316 } 2317 2318 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); 2319 } 2320 2321 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { 2322 if (T->isArrayType() || T->isFunctionType()) { 2323 Diag(Loc, diag::err_func_returning_array_function) 2324 << T->isFunctionType() << T; 2325 return true; 2326 } 2327 2328 // Functions cannot return half FP. 2329 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) { 2330 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << 2331 FixItHint::CreateInsertion(Loc, "*"); 2332 return true; 2333 } 2334 2335 // Methods cannot return interface types. All ObjC objects are 2336 // passed by reference. 2337 if (T->isObjCObjectType()) { 2338 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T; 2339 return 0; 2340 } 2341 2342 return false; 2343 } 2344 2345 /// Check the extended parameter information. Most of the necessary 2346 /// checking should occur when applying the parameter attribute; the 2347 /// only other checks required are positional restrictions. 2348 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes, 2349 const FunctionProtoType::ExtProtoInfo &EPI, 2350 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) { 2351 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos"); 2352 2353 bool hasCheckedSwiftCall = false; 2354 auto checkForSwiftCC = [&](unsigned paramIndex) { 2355 // Only do this once. 2356 if (hasCheckedSwiftCall) return; 2357 hasCheckedSwiftCall = true; 2358 if (EPI.ExtInfo.getCC() == CC_Swift) return; 2359 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall) 2360 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI()); 2361 }; 2362 2363 for (size_t paramIndex = 0, numParams = paramTypes.size(); 2364 paramIndex != numParams; ++paramIndex) { 2365 switch (EPI.ExtParameterInfos[paramIndex].getABI()) { 2366 // Nothing interesting to check for orindary-ABI parameters. 2367 case ParameterABI::Ordinary: 2368 continue; 2369 2370 // swift_indirect_result parameters must be a prefix of the function 2371 // arguments. 2372 case ParameterABI::SwiftIndirectResult: 2373 checkForSwiftCC(paramIndex); 2374 if (paramIndex != 0 && 2375 EPI.ExtParameterInfos[paramIndex - 1].getABI() 2376 != ParameterABI::SwiftIndirectResult) { 2377 S.Diag(getParamLoc(paramIndex), 2378 diag::err_swift_indirect_result_not_first); 2379 } 2380 continue; 2381 2382 // swift_context parameters must be the last parameter except for 2383 // a possible swift_error parameter. 2384 case ParameterABI::SwiftContext: 2385 checkForSwiftCC(paramIndex); 2386 if (!(paramIndex == numParams - 1 || 2387 (paramIndex == numParams - 2 && 2388 EPI.ExtParameterInfos[numParams - 1].getABI() 2389 == ParameterABI::SwiftErrorResult))) { 2390 S.Diag(getParamLoc(paramIndex), 2391 diag::err_swift_context_not_before_swift_error_result); 2392 } 2393 continue; 2394 2395 // swift_error parameters must be the last parameter. 2396 case ParameterABI::SwiftErrorResult: 2397 checkForSwiftCC(paramIndex); 2398 if (paramIndex != numParams - 1) { 2399 S.Diag(getParamLoc(paramIndex), 2400 diag::err_swift_error_result_not_last); 2401 } else if (paramIndex == 0 || 2402 EPI.ExtParameterInfos[paramIndex - 1].getABI() 2403 != ParameterABI::SwiftContext) { 2404 S.Diag(getParamLoc(paramIndex), 2405 diag::err_swift_error_result_not_after_swift_context); 2406 } 2407 continue; 2408 } 2409 llvm_unreachable("bad ABI kind"); 2410 } 2411 } 2412 2413 QualType Sema::BuildFunctionType(QualType T, 2414 MutableArrayRef<QualType> ParamTypes, 2415 SourceLocation Loc, DeclarationName Entity, 2416 const FunctionProtoType::ExtProtoInfo &EPI) { 2417 bool Invalid = false; 2418 2419 Invalid |= CheckFunctionReturnType(T, Loc); 2420 2421 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { 2422 // FIXME: Loc is too inprecise here, should use proper locations for args. 2423 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); 2424 if (ParamType->isVoidType()) { 2425 Diag(Loc, diag::err_param_with_void_type); 2426 Invalid = true; 2427 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) { 2428 // Disallow half FP arguments. 2429 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << 2430 FixItHint::CreateInsertion(Loc, "*"); 2431 Invalid = true; 2432 } 2433 2434 ParamTypes[Idx] = ParamType; 2435 } 2436 2437 if (EPI.ExtParameterInfos) { 2438 checkExtParameterInfos(*this, ParamTypes, EPI, 2439 [=](unsigned i) { return Loc; }); 2440 } 2441 2442 if (Invalid) 2443 return QualType(); 2444 2445 return Context.getFunctionType(T, ParamTypes, EPI); 2446 } 2447 2448 /// \brief Build a member pointer type \c T Class::*. 2449 /// 2450 /// \param T the type to which the member pointer refers. 2451 /// \param Class the class type into which the member pointer points. 2452 /// \param Loc the location where this type begins 2453 /// \param Entity the name of the entity that will have this member pointer type 2454 /// 2455 /// \returns a member pointer type, if successful, or a NULL type if there was 2456 /// an error. 2457 QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 2458 SourceLocation Loc, 2459 DeclarationName Entity) { 2460 // Verify that we're not building a pointer to pointer to function with 2461 // exception specification. 2462 if (CheckDistantExceptionSpec(T)) { 2463 Diag(Loc, diag::err_distant_exception_spec); 2464 return QualType(); 2465 } 2466 2467 // C++ 8.3.3p3: A pointer to member shall not point to ... a member 2468 // with reference type, or "cv void." 2469 if (T->isReferenceType()) { 2470 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 2471 << getPrintableNameForEntity(Entity) << T; 2472 return QualType(); 2473 } 2474 2475 if (T->isVoidType()) { 2476 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 2477 << getPrintableNameForEntity(Entity); 2478 return QualType(); 2479 } 2480 2481 if (!Class->isDependentType() && !Class->isRecordType()) { 2482 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 2483 return QualType(); 2484 } 2485 2486 // Adjust the default free function calling convention to the default method 2487 // calling convention. 2488 bool IsCtorOrDtor = 2489 (Entity.getNameKind() == DeclarationName::CXXConstructorName) || 2490 (Entity.getNameKind() == DeclarationName::CXXDestructorName); 2491 if (T->isFunctionType()) 2492 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc); 2493 2494 return Context.getMemberPointerType(T, Class.getTypePtr()); 2495 } 2496 2497 /// \brief Build a block pointer type. 2498 /// 2499 /// \param T The type to which we'll be building a block pointer. 2500 /// 2501 /// \param Loc The source location, used for diagnostics. 2502 /// 2503 /// \param Entity The name of the entity that involves the block pointer 2504 /// type, if known. 2505 /// 2506 /// \returns A suitable block pointer type, if there are no 2507 /// errors. Otherwise, returns a NULL type. 2508 QualType Sema::BuildBlockPointerType(QualType T, 2509 SourceLocation Loc, 2510 DeclarationName Entity) { 2511 if (!T->isFunctionType()) { 2512 Diag(Loc, diag::err_nonfunction_block_type); 2513 return QualType(); 2514 } 2515 2516 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer)) 2517 return QualType(); 2518 2519 return Context.getBlockPointerType(T); 2520 } 2521 2522 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { 2523 QualType QT = Ty.get(); 2524 if (QT.isNull()) { 2525 if (TInfo) *TInfo = nullptr; 2526 return QualType(); 2527 } 2528 2529 TypeSourceInfo *DI = nullptr; 2530 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 2531 QT = LIT->getType(); 2532 DI = LIT->getTypeSourceInfo(); 2533 } 2534 2535 if (TInfo) *TInfo = DI; 2536 return QT; 2537 } 2538 2539 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 2540 Qualifiers::ObjCLifetime ownership, 2541 unsigned chunkIndex); 2542 2543 /// Given that this is the declaration of a parameter under ARC, 2544 /// attempt to infer attributes and such for pointer-to-whatever 2545 /// types. 2546 static void inferARCWriteback(TypeProcessingState &state, 2547 QualType &declSpecType) { 2548 Sema &S = state.getSema(); 2549 Declarator &declarator = state.getDeclarator(); 2550 2551 // TODO: should we care about decl qualifiers? 2552 2553 // Check whether the declarator has the expected form. We walk 2554 // from the inside out in order to make the block logic work. 2555 unsigned outermostPointerIndex = 0; 2556 bool isBlockPointer = false; 2557 unsigned numPointers = 0; 2558 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 2559 unsigned chunkIndex = i; 2560 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); 2561 switch (chunk.Kind) { 2562 case DeclaratorChunk::Paren: 2563 // Ignore parens. 2564 break; 2565 2566 case DeclaratorChunk::Reference: 2567 case DeclaratorChunk::Pointer: 2568 // Count the number of pointers. Treat references 2569 // interchangeably as pointers; if they're mis-ordered, normal 2570 // type building will discover that. 2571 outermostPointerIndex = chunkIndex; 2572 numPointers++; 2573 break; 2574 2575 case DeclaratorChunk::BlockPointer: 2576 // If we have a pointer to block pointer, that's an acceptable 2577 // indirect reference; anything else is not an application of 2578 // the rules. 2579 if (numPointers != 1) return; 2580 numPointers++; 2581 outermostPointerIndex = chunkIndex; 2582 isBlockPointer = true; 2583 2584 // We don't care about pointer structure in return values here. 2585 goto done; 2586 2587 case DeclaratorChunk::Array: // suppress if written (id[])? 2588 case DeclaratorChunk::Function: 2589 case DeclaratorChunk::MemberPointer: 2590 case DeclaratorChunk::Pipe: 2591 return; 2592 } 2593 } 2594 done: 2595 2596 // If we have *one* pointer, then we want to throw the qualifier on 2597 // the declaration-specifiers, which means that it needs to be a 2598 // retainable object type. 2599 if (numPointers == 1) { 2600 // If it's not a retainable object type, the rule doesn't apply. 2601 if (!declSpecType->isObjCRetainableType()) return; 2602 2603 // If it already has lifetime, don't do anything. 2604 if (declSpecType.getObjCLifetime()) return; 2605 2606 // Otherwise, modify the type in-place. 2607 Qualifiers qs; 2608 2609 if (declSpecType->isObjCARCImplicitlyUnretainedType()) 2610 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); 2611 else 2612 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); 2613 declSpecType = S.Context.getQualifiedType(declSpecType, qs); 2614 2615 // If we have *two* pointers, then we want to throw the qualifier on 2616 // the outermost pointer. 2617 } else if (numPointers == 2) { 2618 // If we don't have a block pointer, we need to check whether the 2619 // declaration-specifiers gave us something that will turn into a 2620 // retainable object pointer after we slap the first pointer on it. 2621 if (!isBlockPointer && !declSpecType->isObjCObjectType()) 2622 return; 2623 2624 // Look for an explicit lifetime attribute there. 2625 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); 2626 if (chunk.Kind != DeclaratorChunk::Pointer && 2627 chunk.Kind != DeclaratorChunk::BlockPointer) 2628 return; 2629 for (const AttributeList *attr = chunk.getAttrs(); attr; 2630 attr = attr->getNext()) 2631 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 2632 return; 2633 2634 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, 2635 outermostPointerIndex); 2636 2637 // Any other number of pointers/references does not trigger the rule. 2638 } else return; 2639 2640 // TODO: mark whether we did this inference? 2641 } 2642 2643 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 2644 SourceLocation FallbackLoc, 2645 SourceLocation ConstQualLoc, 2646 SourceLocation VolatileQualLoc, 2647 SourceLocation RestrictQualLoc, 2648 SourceLocation AtomicQualLoc) { 2649 if (!Quals) 2650 return; 2651 2652 struct Qual { 2653 const char *Name; 2654 unsigned Mask; 2655 SourceLocation Loc; 2656 } const QualKinds[4] = { 2657 { "const", DeclSpec::TQ_const, ConstQualLoc }, 2658 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc }, 2659 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc }, 2660 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc } 2661 }; 2662 2663 SmallString<32> QualStr; 2664 unsigned NumQuals = 0; 2665 SourceLocation Loc; 2666 FixItHint FixIts[4]; 2667 2668 // Build a string naming the redundant qualifiers. 2669 for (unsigned I = 0; I != 4; ++I) { 2670 if (Quals & QualKinds[I].Mask) { 2671 if (!QualStr.empty()) QualStr += ' '; 2672 QualStr += QualKinds[I].Name; 2673 2674 // If we have a location for the qualifier, offer a fixit. 2675 SourceLocation QualLoc = QualKinds[I].Loc; 2676 if (QualLoc.isValid()) { 2677 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); 2678 if (Loc.isInvalid() || 2679 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)) 2680 Loc = QualLoc; 2681 } 2682 2683 ++NumQuals; 2684 } 2685 } 2686 2687 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID) 2688 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; 2689 } 2690 2691 // Diagnose pointless type qualifiers on the return type of a function. 2692 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, 2693 Declarator &D, 2694 unsigned FunctionChunkIndex) { 2695 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) { 2696 // FIXME: TypeSourceInfo doesn't preserve location information for 2697 // qualifiers. 2698 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2699 RetTy.getLocalCVRQualifiers(), 2700 D.getIdentifierLoc()); 2701 return; 2702 } 2703 2704 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, 2705 End = D.getNumTypeObjects(); 2706 OuterChunkIndex != End; ++OuterChunkIndex) { 2707 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); 2708 switch (OuterChunk.Kind) { 2709 case DeclaratorChunk::Paren: 2710 continue; 2711 2712 case DeclaratorChunk::Pointer: { 2713 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; 2714 S.diagnoseIgnoredQualifiers( 2715 diag::warn_qual_return_type, 2716 PTI.TypeQuals, 2717 SourceLocation(), 2718 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), 2719 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), 2720 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), 2721 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc)); 2722 return; 2723 } 2724 2725 case DeclaratorChunk::Function: 2726 case DeclaratorChunk::BlockPointer: 2727 case DeclaratorChunk::Reference: 2728 case DeclaratorChunk::Array: 2729 case DeclaratorChunk::MemberPointer: 2730 case DeclaratorChunk::Pipe: 2731 // FIXME: We can't currently provide an accurate source location and a 2732 // fix-it hint for these. 2733 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; 2734 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2735 RetTy.getCVRQualifiers() | AtomicQual, 2736 D.getIdentifierLoc()); 2737 return; 2738 } 2739 2740 llvm_unreachable("unknown declarator chunk kind"); 2741 } 2742 2743 // If the qualifiers come from a conversion function type, don't diagnose 2744 // them -- they're not necessarily redundant, since such a conversion 2745 // operator can be explicitly called as "x.operator const int()". 2746 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 2747 return; 2748 2749 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers 2750 // which are present there. 2751 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2752 D.getDeclSpec().getTypeQualifiers(), 2753 D.getIdentifierLoc(), 2754 D.getDeclSpec().getConstSpecLoc(), 2755 D.getDeclSpec().getVolatileSpecLoc(), 2756 D.getDeclSpec().getRestrictSpecLoc(), 2757 D.getDeclSpec().getAtomicSpecLoc()); 2758 } 2759 2760 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, 2761 TypeSourceInfo *&ReturnTypeInfo) { 2762 Sema &SemaRef = state.getSema(); 2763 Declarator &D = state.getDeclarator(); 2764 QualType T; 2765 ReturnTypeInfo = nullptr; 2766 2767 // The TagDecl owned by the DeclSpec. 2768 TagDecl *OwnedTagDecl = nullptr; 2769 2770 switch (D.getName().getKind()) { 2771 case UnqualifiedId::IK_ImplicitSelfParam: 2772 case UnqualifiedId::IK_OperatorFunctionId: 2773 case UnqualifiedId::IK_Identifier: 2774 case UnqualifiedId::IK_LiteralOperatorId: 2775 case UnqualifiedId::IK_TemplateId: 2776 T = ConvertDeclSpecToType(state); 2777 2778 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 2779 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 2780 // Owned declaration is embedded in declarator. 2781 OwnedTagDecl->setEmbeddedInDeclarator(true); 2782 } 2783 break; 2784 2785 case UnqualifiedId::IK_ConstructorName: 2786 case UnqualifiedId::IK_ConstructorTemplateId: 2787 case UnqualifiedId::IK_DestructorName: 2788 // Constructors and destructors don't have return types. Use 2789 // "void" instead. 2790 T = SemaRef.Context.VoidTy; 2791 processTypeAttrs(state, T, TAL_DeclSpec, 2792 D.getDeclSpec().getAttributes().getList()); 2793 break; 2794 2795 case UnqualifiedId::IK_ConversionFunctionId: 2796 // The result type of a conversion function is the type that it 2797 // converts to. 2798 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, 2799 &ReturnTypeInfo); 2800 break; 2801 } 2802 2803 if (D.getAttributes()) 2804 distributeTypeAttrsFromDeclarator(state, T); 2805 2806 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. 2807 if (D.getDeclSpec().containsPlaceholderType()) { 2808 int Error = -1; 2809 2810 switch (D.getContext()) { 2811 case Declarator::LambdaExprContext: 2812 llvm_unreachable("Can't specify a type specifier in lambda grammar"); 2813 case Declarator::ObjCParameterContext: 2814 case Declarator::ObjCResultContext: 2815 case Declarator::PrototypeContext: 2816 Error = 0; 2817 break; 2818 case Declarator::LambdaExprParameterContext: 2819 // In C++14, generic lambdas allow 'auto' in their parameters. 2820 if (!(SemaRef.getLangOpts().CPlusPlus14 2821 && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto)) 2822 Error = 16; 2823 break; 2824 case Declarator::MemberContext: { 2825 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || 2826 D.isFunctionDeclarator()) 2827 break; 2828 bool Cxx = SemaRef.getLangOpts().CPlusPlus; 2829 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { 2830 case TTK_Enum: llvm_unreachable("unhandled tag kind"); 2831 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break; 2832 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break; 2833 case TTK_Class: Error = 5; /* Class member */ break; 2834 case TTK_Interface: Error = 6; /* Interface member */ break; 2835 } 2836 break; 2837 } 2838 case Declarator::CXXCatchContext: 2839 case Declarator::ObjCCatchContext: 2840 Error = 7; // Exception declaration 2841 break; 2842 case Declarator::TemplateParamContext: 2843 Error = 8; // Template parameter 2844 break; 2845 case Declarator::BlockLiteralContext: 2846 Error = 9; // Block literal 2847 break; 2848 case Declarator::TemplateTypeArgContext: 2849 Error = 10; // Template type argument 2850 break; 2851 case Declarator::AliasDeclContext: 2852 case Declarator::AliasTemplateContext: 2853 Error = 12; // Type alias 2854 break; 2855 case Declarator::TrailingReturnContext: 2856 if (!SemaRef.getLangOpts().CPlusPlus14 || 2857 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type) 2858 Error = 13; // Function return type 2859 break; 2860 case Declarator::ConversionIdContext: 2861 if (!SemaRef.getLangOpts().CPlusPlus14 || 2862 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type) 2863 Error = 14; // conversion-type-id 2864 break; 2865 case Declarator::TypeNameContext: 2866 Error = 15; // Generic 2867 break; 2868 case Declarator::FileContext: 2869 case Declarator::BlockContext: 2870 case Declarator::ForContext: 2871 case Declarator::ConditionContext: 2872 break; 2873 case Declarator::CXXNewContext: 2874 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type) 2875 Error = 17; // 'new' type 2876 break; 2877 case Declarator::KNRTypeListContext: 2878 Error = 18; // K&R function parameter 2879 break; 2880 } 2881 2882 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 2883 Error = 11; 2884 2885 // In Objective-C it is an error to use 'auto' on a function declarator 2886 // (and everywhere for '__auto_type'). 2887 if (D.isFunctionDeclarator() && 2888 (!SemaRef.getLangOpts().CPlusPlus11 || 2889 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)) 2890 Error = 13; 2891 2892 bool HaveTrailing = false; 2893 2894 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator 2895 // contains a trailing return type. That is only legal at the outermost 2896 // level. Check all declarator chunks (outermost first) anyway, to give 2897 // better diagnostics. 2898 // We don't support '__auto_type' with trailing return types. 2899 if (SemaRef.getLangOpts().CPlusPlus11 && 2900 D.getDeclSpec().getTypeSpecType() != DeclSpec::TST_auto_type) { 2901 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2902 unsigned chunkIndex = e - i - 1; 2903 state.setCurrentChunkIndex(chunkIndex); 2904 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 2905 if (DeclType.Kind == DeclaratorChunk::Function) { 2906 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2907 if (FTI.hasTrailingReturnType()) { 2908 HaveTrailing = true; 2909 Error = -1; 2910 break; 2911 } 2912 } 2913 } 2914 } 2915 2916 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); 2917 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 2918 AutoRange = D.getName().getSourceRange(); 2919 2920 if (Error != -1) { 2921 unsigned Keyword; 2922 switch (D.getDeclSpec().getTypeSpecType()) { 2923 case DeclSpec::TST_auto: Keyword = 0; break; 2924 case DeclSpec::TST_decltype_auto: Keyword = 1; break; 2925 case DeclSpec::TST_auto_type: Keyword = 2; break; 2926 default: llvm_unreachable("unknown auto TypeSpecType"); 2927 } 2928 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) 2929 << Keyword << Error << AutoRange; 2930 T = SemaRef.Context.IntTy; 2931 D.setInvalidType(true); 2932 } else if (!HaveTrailing) { 2933 // If there was a trailing return type, we already got 2934 // warn_cxx98_compat_trailing_return_type in the parser. 2935 SemaRef.Diag(AutoRange.getBegin(), 2936 diag::warn_cxx98_compat_auto_type_specifier) 2937 << AutoRange; 2938 } 2939 } 2940 2941 if (SemaRef.getLangOpts().CPlusPlus && 2942 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { 2943 // Check the contexts where C++ forbids the declaration of a new class 2944 // or enumeration in a type-specifier-seq. 2945 unsigned DiagID = 0; 2946 switch (D.getContext()) { 2947 case Declarator::TrailingReturnContext: 2948 // Class and enumeration definitions are syntactically not allowed in 2949 // trailing return types. 2950 llvm_unreachable("parser should not have allowed this"); 2951 break; 2952 case Declarator::FileContext: 2953 case Declarator::MemberContext: 2954 case Declarator::BlockContext: 2955 case Declarator::ForContext: 2956 case Declarator::BlockLiteralContext: 2957 case Declarator::LambdaExprContext: 2958 // C++11 [dcl.type]p3: 2959 // A type-specifier-seq shall not define a class or enumeration unless 2960 // it appears in the type-id of an alias-declaration (7.1.3) that is not 2961 // the declaration of a template-declaration. 2962 case Declarator::AliasDeclContext: 2963 break; 2964 case Declarator::AliasTemplateContext: 2965 DiagID = diag::err_type_defined_in_alias_template; 2966 break; 2967 case Declarator::TypeNameContext: 2968 case Declarator::ConversionIdContext: 2969 case Declarator::TemplateParamContext: 2970 case Declarator::CXXNewContext: 2971 case Declarator::CXXCatchContext: 2972 case Declarator::ObjCCatchContext: 2973 case Declarator::TemplateTypeArgContext: 2974 DiagID = diag::err_type_defined_in_type_specifier; 2975 break; 2976 case Declarator::PrototypeContext: 2977 case Declarator::LambdaExprParameterContext: 2978 case Declarator::ObjCParameterContext: 2979 case Declarator::ObjCResultContext: 2980 case Declarator::KNRTypeListContext: 2981 // C++ [dcl.fct]p6: 2982 // Types shall not be defined in return or parameter types. 2983 DiagID = diag::err_type_defined_in_param_type; 2984 break; 2985 case Declarator::ConditionContext: 2986 // C++ 6.4p2: 2987 // The type-specifier-seq shall not contain typedef and shall not declare 2988 // a new class or enumeration. 2989 DiagID = diag::err_type_defined_in_condition; 2990 break; 2991 } 2992 2993 if (DiagID != 0) { 2994 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID) 2995 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2996 D.setInvalidType(true); 2997 } 2998 } 2999 3000 assert(!T.isNull() && "This function should not return a null type"); 3001 return T; 3002 } 3003 3004 /// Produce an appropriate diagnostic for an ambiguity between a function 3005 /// declarator and a C++ direct-initializer. 3006 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, 3007 DeclaratorChunk &DeclType, QualType RT) { 3008 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 3009 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity"); 3010 3011 // If the return type is void there is no ambiguity. 3012 if (RT->isVoidType()) 3013 return; 3014 3015 // An initializer for a non-class type can have at most one argument. 3016 if (!RT->isRecordType() && FTI.NumParams > 1) 3017 return; 3018 3019 // An initializer for a reference must have exactly one argument. 3020 if (RT->isReferenceType() && FTI.NumParams != 1) 3021 return; 3022 3023 // Only warn if this declarator is declaring a function at block scope, and 3024 // doesn't have a storage class (such as 'extern') specified. 3025 if (!D.isFunctionDeclarator() || 3026 D.getFunctionDefinitionKind() != FDK_Declaration || 3027 !S.CurContext->isFunctionOrMethod() || 3028 D.getDeclSpec().getStorageClassSpec() 3029 != DeclSpec::SCS_unspecified) 3030 return; 3031 3032 // Inside a condition, a direct initializer is not permitted. We allow one to 3033 // be parsed in order to give better diagnostics in condition parsing. 3034 if (D.getContext() == Declarator::ConditionContext) 3035 return; 3036 3037 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); 3038 3039 S.Diag(DeclType.Loc, 3040 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration 3041 : diag::warn_empty_parens_are_function_decl) 3042 << ParenRange; 3043 3044 // If the declaration looks like: 3045 // T var1, 3046 // f(); 3047 // and name lookup finds a function named 'f', then the ',' was 3048 // probably intended to be a ';'. 3049 if (!D.isFirstDeclarator() && D.getIdentifier()) { 3050 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); 3051 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); 3052 if (Comma.getFileID() != Name.getFileID() || 3053 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { 3054 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 3055 Sema::LookupOrdinaryName); 3056 if (S.LookupName(Result, S.getCurScope())) 3057 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) 3058 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") 3059 << D.getIdentifier(); 3060 } 3061 } 3062 3063 if (FTI.NumParams > 0) { 3064 // For a declaration with parameters, eg. "T var(T());", suggest adding 3065 // parens around the first parameter to turn the declaration into a 3066 // variable declaration. 3067 SourceRange Range = FTI.Params[0].Param->getSourceRange(); 3068 SourceLocation B = Range.getBegin(); 3069 SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); 3070 // FIXME: Maybe we should suggest adding braces instead of parens 3071 // in C++11 for classes that don't have an initializer_list constructor. 3072 S.Diag(B, diag::note_additional_parens_for_variable_declaration) 3073 << FixItHint::CreateInsertion(B, "(") 3074 << FixItHint::CreateInsertion(E, ")"); 3075 } else { 3076 // For a declaration without parameters, eg. "T var();", suggest replacing 3077 // the parens with an initializer to turn the declaration into a variable 3078 // declaration. 3079 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); 3080 3081 // Empty parens mean value-initialization, and no parens mean 3082 // default initialization. These are equivalent if the default 3083 // constructor is user-provided or if zero-initialization is a 3084 // no-op. 3085 if (RD && RD->hasDefinition() && 3086 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) 3087 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) 3088 << FixItHint::CreateRemoval(ParenRange); 3089 else { 3090 std::string Init = 3091 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); 3092 if (Init.empty() && S.LangOpts.CPlusPlus11) 3093 Init = "{}"; 3094 if (!Init.empty()) 3095 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) 3096 << FixItHint::CreateReplacement(ParenRange, Init); 3097 } 3098 } 3099 } 3100 3101 /// Helper for figuring out the default CC for a function declarator type. If 3102 /// this is the outermost chunk, then we can determine the CC from the 3103 /// declarator context. If not, then this could be either a member function 3104 /// type or normal function type. 3105 static CallingConv 3106 getCCForDeclaratorChunk(Sema &S, Declarator &D, 3107 const DeclaratorChunk::FunctionTypeInfo &FTI, 3108 unsigned ChunkIndex) { 3109 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function); 3110 3111 // Check for an explicit CC attribute. 3112 for (auto Attr = FTI.AttrList; Attr; Attr = Attr->getNext()) { 3113 switch (Attr->getKind()) { 3114 CALLING_CONV_ATTRS_CASELIST: { 3115 // Ignore attributes that don't validate or can't apply to the 3116 // function type. We'll diagnose the failure to apply them in 3117 // handleFunctionTypeAttr. 3118 CallingConv CC; 3119 if (!S.CheckCallingConvAttr(*Attr, CC) && 3120 (!FTI.isVariadic || supportsVariadicCall(CC))) { 3121 return CC; 3122 } 3123 break; 3124 } 3125 3126 default: 3127 break; 3128 } 3129 } 3130 3131 bool IsCXXInstanceMethod = false; 3132 3133 if (S.getLangOpts().CPlusPlus) { 3134 // Look inwards through parentheses to see if this chunk will form a 3135 // member pointer type or if we're the declarator. Any type attributes 3136 // between here and there will override the CC we choose here. 3137 unsigned I = ChunkIndex; 3138 bool FoundNonParen = false; 3139 while (I && !FoundNonParen) { 3140 --I; 3141 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) 3142 FoundNonParen = true; 3143 } 3144 3145 if (FoundNonParen) { 3146 // If we're not the declarator, we're a regular function type unless we're 3147 // in a member pointer. 3148 IsCXXInstanceMethod = 3149 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; 3150 } else if (D.getContext() == Declarator::LambdaExprContext) { 3151 // This can only be a call operator for a lambda, which is an instance 3152 // method. 3153 IsCXXInstanceMethod = true; 3154 } else { 3155 // We're the innermost decl chunk, so must be a function declarator. 3156 assert(D.isFunctionDeclarator()); 3157 3158 // If we're inside a record, we're declaring a method, but it could be 3159 // explicitly or implicitly static. 3160 IsCXXInstanceMethod = 3161 D.isFirstDeclarationOfMember() && 3162 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 3163 !D.isStaticMember(); 3164 } 3165 } 3166 3167 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic, 3168 IsCXXInstanceMethod); 3169 3170 // Attribute AT_OpenCLKernel affects the calling convention only on 3171 // the SPIR target, hence it cannot be treated as a calling 3172 // convention attribute. This is the simplest place to infer 3173 // "spir_kernel" for OpenCL kernels on SPIR. 3174 if (CC == CC_SpirFunction) { 3175 for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList(); 3176 Attr; Attr = Attr->getNext()) { 3177 if (Attr->getKind() == AttributeList::AT_OpenCLKernel) { 3178 CC = CC_SpirKernel; 3179 break; 3180 } 3181 } 3182 } 3183 3184 return CC; 3185 } 3186 3187 namespace { 3188 /// A simple notion of pointer kinds, which matches up with the various 3189 /// pointer declarators. 3190 enum class SimplePointerKind { 3191 Pointer, 3192 BlockPointer, 3193 MemberPointer, 3194 }; 3195 } // end anonymous namespace 3196 3197 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { 3198 switch (nullability) { 3199 case NullabilityKind::NonNull: 3200 if (!Ident__Nonnull) 3201 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull"); 3202 return Ident__Nonnull; 3203 3204 case NullabilityKind::Nullable: 3205 if (!Ident__Nullable) 3206 Ident__Nullable = PP.getIdentifierInfo("_Nullable"); 3207 return Ident__Nullable; 3208 3209 case NullabilityKind::Unspecified: 3210 if (!Ident__Null_unspecified) 3211 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified"); 3212 return Ident__Null_unspecified; 3213 } 3214 llvm_unreachable("Unknown nullability kind."); 3215 } 3216 3217 /// Retrieve the identifier "NSError". 3218 IdentifierInfo *Sema::getNSErrorIdent() { 3219 if (!Ident_NSError) 3220 Ident_NSError = PP.getIdentifierInfo("NSError"); 3221 3222 return Ident_NSError; 3223 } 3224 3225 /// Check whether there is a nullability attribute of any kind in the given 3226 /// attribute list. 3227 static bool hasNullabilityAttr(const AttributeList *attrs) { 3228 for (const AttributeList *attr = attrs; attr; 3229 attr = attr->getNext()) { 3230 if (attr->getKind() == AttributeList::AT_TypeNonNull || 3231 attr->getKind() == AttributeList::AT_TypeNullable || 3232 attr->getKind() == AttributeList::AT_TypeNullUnspecified) 3233 return true; 3234 } 3235 3236 return false; 3237 } 3238 3239 namespace { 3240 /// Describes the kind of a pointer a declarator describes. 3241 enum class PointerDeclaratorKind { 3242 // Not a pointer. 3243 NonPointer, 3244 // Single-level pointer. 3245 SingleLevelPointer, 3246 // Multi-level pointer (of any pointer kind). 3247 MultiLevelPointer, 3248 // CFFooRef* 3249 MaybePointerToCFRef, 3250 // CFErrorRef* 3251 CFErrorRefPointer, 3252 // NSError** 3253 NSErrorPointerPointer, 3254 }; 3255 } // end anonymous namespace 3256 3257 /// Classify the given declarator, whose type-specified is \c type, based on 3258 /// what kind of pointer it refers to. 3259 /// 3260 /// This is used to determine the default nullability. 3261 static PointerDeclaratorKind classifyPointerDeclarator(Sema &S, 3262 QualType type, 3263 Declarator &declarator) { 3264 unsigned numNormalPointers = 0; 3265 3266 // For any dependent type, we consider it a non-pointer. 3267 if (type->isDependentType()) 3268 return PointerDeclaratorKind::NonPointer; 3269 3270 // Look through the declarator chunks to identify pointers. 3271 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { 3272 DeclaratorChunk &chunk = declarator.getTypeObject(i); 3273 switch (chunk.Kind) { 3274 case DeclaratorChunk::Array: 3275 case DeclaratorChunk::Function: 3276 case DeclaratorChunk::Pipe: 3277 break; 3278 3279 case DeclaratorChunk::BlockPointer: 3280 case DeclaratorChunk::MemberPointer: 3281 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3282 : PointerDeclaratorKind::SingleLevelPointer; 3283 3284 case DeclaratorChunk::Paren: 3285 case DeclaratorChunk::Reference: 3286 continue; 3287 3288 case DeclaratorChunk::Pointer: 3289 ++numNormalPointers; 3290 if (numNormalPointers > 2) 3291 return PointerDeclaratorKind::MultiLevelPointer; 3292 continue; 3293 } 3294 } 3295 3296 // Then, dig into the type specifier itself. 3297 unsigned numTypeSpecifierPointers = 0; 3298 do { 3299 // Decompose normal pointers. 3300 if (auto ptrType = type->getAs<PointerType>()) { 3301 ++numNormalPointers; 3302 3303 if (numNormalPointers > 2) 3304 return PointerDeclaratorKind::MultiLevelPointer; 3305 3306 type = ptrType->getPointeeType(); 3307 ++numTypeSpecifierPointers; 3308 continue; 3309 } 3310 3311 // Decompose block pointers. 3312 if (type->getAs<BlockPointerType>()) { 3313 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3314 : PointerDeclaratorKind::SingleLevelPointer; 3315 } 3316 3317 // Decompose member pointers. 3318 if (type->getAs<MemberPointerType>()) { 3319 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3320 : PointerDeclaratorKind::SingleLevelPointer; 3321 } 3322 3323 // Look at Objective-C object pointers. 3324 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { 3325 ++numNormalPointers; 3326 ++numTypeSpecifierPointers; 3327 3328 // If this is NSError**, report that. 3329 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { 3330 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() && 3331 numNormalPointers == 2 && numTypeSpecifierPointers < 2) { 3332 return PointerDeclaratorKind::NSErrorPointerPointer; 3333 } 3334 } 3335 3336 break; 3337 } 3338 3339 // Look at Objective-C class types. 3340 if (auto objcClass = type->getAs<ObjCInterfaceType>()) { 3341 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) { 3342 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) 3343 return PointerDeclaratorKind::NSErrorPointerPointer;; 3344 } 3345 3346 break; 3347 } 3348 3349 // If at this point we haven't seen a pointer, we won't see one. 3350 if (numNormalPointers == 0) 3351 return PointerDeclaratorKind::NonPointer; 3352 3353 if (auto recordType = type->getAs<RecordType>()) { 3354 RecordDecl *recordDecl = recordType->getDecl(); 3355 3356 bool isCFError = false; 3357 if (S.CFError) { 3358 // If we already know about CFError, test it directly. 3359 isCFError = (S.CFError == recordDecl); 3360 } else { 3361 // Check whether this is CFError, which we identify based on its bridge 3362 // to NSError. 3363 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) { 3364 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) { 3365 if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) { 3366 S.CFError = recordDecl; 3367 isCFError = true; 3368 } 3369 } 3370 } 3371 } 3372 3373 // If this is CFErrorRef*, report it as such. 3374 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) { 3375 return PointerDeclaratorKind::CFErrorRefPointer; 3376 } 3377 break; 3378 } 3379 3380 break; 3381 } while (true); 3382 3383 switch (numNormalPointers) { 3384 case 0: 3385 return PointerDeclaratorKind::NonPointer; 3386 3387 case 1: 3388 return PointerDeclaratorKind::SingleLevelPointer; 3389 3390 case 2: 3391 return PointerDeclaratorKind::MaybePointerToCFRef; 3392 3393 default: 3394 return PointerDeclaratorKind::MultiLevelPointer; 3395 } 3396 } 3397 3398 static FileID getNullabilityCompletenessCheckFileID(Sema &S, 3399 SourceLocation loc) { 3400 // If we're anywhere in a function, method, or closure context, don't perform 3401 // completeness checks. 3402 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { 3403 if (ctx->isFunctionOrMethod()) 3404 return FileID(); 3405 3406 if (ctx->isFileContext()) 3407 break; 3408 } 3409 3410 // We only care about the expansion location. 3411 loc = S.SourceMgr.getExpansionLoc(loc); 3412 FileID file = S.SourceMgr.getFileID(loc); 3413 if (file.isInvalid()) 3414 return FileID(); 3415 3416 // Retrieve file information. 3417 bool invalid = false; 3418 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid); 3419 if (invalid || !sloc.isFile()) 3420 return FileID(); 3421 3422 // We don't want to perform completeness checks on the main file or in 3423 // system headers. 3424 const SrcMgr::FileInfo &fileInfo = sloc.getFile(); 3425 if (fileInfo.getIncludeLoc().isInvalid()) 3426 return FileID(); 3427 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && 3428 S.Diags.getSuppressSystemWarnings()) { 3429 return FileID(); 3430 } 3431 3432 return file; 3433 } 3434 3435 /// Check for consistent use of nullability. 3436 static void checkNullabilityConsistency(TypeProcessingState &state, 3437 SimplePointerKind pointerKind, 3438 SourceLocation pointerLoc) { 3439 Sema &S = state.getSema(); 3440 3441 // Determine which file we're performing consistency checking for. 3442 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc); 3443 if (file.isInvalid()) 3444 return; 3445 3446 // If we haven't seen any type nullability in this file, we won't warn now 3447 // about anything. 3448 FileNullability &fileNullability = S.NullabilityMap[file]; 3449 if (!fileNullability.SawTypeNullability) { 3450 // If this is the first pointer declarator in the file, record it. 3451 if (fileNullability.PointerLoc.isInvalid() && 3452 !S.Context.getDiagnostics().isIgnored(diag::warn_nullability_missing, 3453 pointerLoc)) { 3454 fileNullability.PointerLoc = pointerLoc; 3455 fileNullability.PointerKind = static_cast<unsigned>(pointerKind); 3456 } 3457 3458 return; 3459 } 3460 3461 // Complain about missing nullability. 3462 S.Diag(pointerLoc, diag::warn_nullability_missing) 3463 << static_cast<unsigned>(pointerKind); 3464 } 3465 3466 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 3467 QualType declSpecType, 3468 TypeSourceInfo *TInfo) { 3469 // The TypeSourceInfo that this function returns will not be a null type. 3470 // If there is an error, this function will fill in a dummy type as fallback. 3471 QualType T = declSpecType; 3472 Declarator &D = state.getDeclarator(); 3473 Sema &S = state.getSema(); 3474 ASTContext &Context = S.Context; 3475 const LangOptions &LangOpts = S.getLangOpts(); 3476 3477 // The name we're declaring, if any. 3478 DeclarationName Name; 3479 if (D.getIdentifier()) 3480 Name = D.getIdentifier(); 3481 3482 // Does this declaration declare a typedef-name? 3483 bool IsTypedefName = 3484 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 3485 D.getContext() == Declarator::AliasDeclContext || 3486 D.getContext() == Declarator::AliasTemplateContext; 3487 3488 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 3489 bool IsQualifiedFunction = T->isFunctionProtoType() && 3490 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 || 3491 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); 3492 3493 // If T is 'decltype(auto)', the only declarators we can have are parens 3494 // and at most one function declarator if this is a function declaration. 3495 if (const AutoType *AT = T->getAs<AutoType>()) { 3496 if (AT->isDecltypeAuto()) { 3497 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3498 unsigned Index = E - I - 1; 3499 DeclaratorChunk &DeclChunk = D.getTypeObject(Index); 3500 unsigned DiagId = diag::err_decltype_auto_compound_type; 3501 unsigned DiagKind = 0; 3502 switch (DeclChunk.Kind) { 3503 case DeclaratorChunk::Paren: 3504 continue; 3505 case DeclaratorChunk::Function: { 3506 unsigned FnIndex; 3507 if (D.isFunctionDeclarationContext() && 3508 D.isFunctionDeclarator(FnIndex) && FnIndex == Index) 3509 continue; 3510 DiagId = diag::err_decltype_auto_function_declarator_not_declaration; 3511 break; 3512 } 3513 case DeclaratorChunk::Pointer: 3514 case DeclaratorChunk::BlockPointer: 3515 case DeclaratorChunk::MemberPointer: 3516 DiagKind = 0; 3517 break; 3518 case DeclaratorChunk::Reference: 3519 DiagKind = 1; 3520 break; 3521 case DeclaratorChunk::Array: 3522 DiagKind = 2; 3523 break; 3524 case DeclaratorChunk::Pipe: 3525 break; 3526 } 3527 3528 S.Diag(DeclChunk.Loc, DiagId) << DiagKind; 3529 D.setInvalidType(true); 3530 break; 3531 } 3532 } 3533 } 3534 3535 // Determine whether we should infer _Nonnull on pointer types. 3536 Optional<NullabilityKind> inferNullability; 3537 bool inferNullabilityCS = false; 3538 bool inferNullabilityInnerOnly = false; 3539 bool inferNullabilityInnerOnlyComplete = false; 3540 3541 // Are we in an assume-nonnull region? 3542 bool inAssumeNonNullRegion = false; 3543 if (S.PP.getPragmaAssumeNonNullLoc().isValid()) { 3544 inAssumeNonNullRegion = true; 3545 // Determine which file we saw the assume-nonnull region in. 3546 FileID file = getNullabilityCompletenessCheckFileID( 3547 S, S.PP.getPragmaAssumeNonNullLoc()); 3548 if (file.isValid()) { 3549 FileNullability &fileNullability = S.NullabilityMap[file]; 3550 3551 // If we haven't seen any type nullability before, now we have. 3552 if (!fileNullability.SawTypeNullability) { 3553 if (fileNullability.PointerLoc.isValid()) { 3554 S.Diag(fileNullability.PointerLoc, diag::warn_nullability_missing) 3555 << static_cast<unsigned>(fileNullability.PointerKind); 3556 } 3557 3558 fileNullability.SawTypeNullability = true; 3559 } 3560 } 3561 } 3562 3563 // Whether to complain about missing nullability specifiers or not. 3564 enum { 3565 /// Never complain. 3566 CAMN_No, 3567 /// Complain on the inner pointers (but not the outermost 3568 /// pointer). 3569 CAMN_InnerPointers, 3570 /// Complain about any pointers that don't have nullability 3571 /// specified or inferred. 3572 CAMN_Yes 3573 } complainAboutMissingNullability = CAMN_No; 3574 unsigned NumPointersRemaining = 0; 3575 3576 if (IsTypedefName) { 3577 // For typedefs, we do not infer any nullability (the default), 3578 // and we only complain about missing nullability specifiers on 3579 // inner pointers. 3580 complainAboutMissingNullability = CAMN_InnerPointers; 3581 3582 if (T->canHaveNullability() && !T->getNullability(S.Context)) { 3583 ++NumPointersRemaining; 3584 } 3585 3586 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { 3587 DeclaratorChunk &chunk = D.getTypeObject(i); 3588 switch (chunk.Kind) { 3589 case DeclaratorChunk::Array: 3590 case DeclaratorChunk::Function: 3591 case DeclaratorChunk::Pipe: 3592 break; 3593 3594 case DeclaratorChunk::BlockPointer: 3595 case DeclaratorChunk::MemberPointer: 3596 ++NumPointersRemaining; 3597 break; 3598 3599 case DeclaratorChunk::Paren: 3600 case DeclaratorChunk::Reference: 3601 continue; 3602 3603 case DeclaratorChunk::Pointer: 3604 ++NumPointersRemaining; 3605 continue; 3606 } 3607 } 3608 } else { 3609 bool isFunctionOrMethod = false; 3610 switch (auto context = state.getDeclarator().getContext()) { 3611 case Declarator::ObjCParameterContext: 3612 case Declarator::ObjCResultContext: 3613 case Declarator::PrototypeContext: 3614 case Declarator::TrailingReturnContext: 3615 isFunctionOrMethod = true; 3616 // fallthrough 3617 3618 case Declarator::MemberContext: 3619 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { 3620 complainAboutMissingNullability = CAMN_No; 3621 break; 3622 } 3623 3624 // Weak properties are inferred to be nullable. 3625 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) { 3626 inferNullability = NullabilityKind::Nullable; 3627 break; 3628 } 3629 3630 // fallthrough 3631 3632 case Declarator::FileContext: 3633 case Declarator::KNRTypeListContext: 3634 complainAboutMissingNullability = CAMN_Yes; 3635 3636 // Nullability inference depends on the type and declarator. 3637 switch (classifyPointerDeclarator(S, T, D)) { 3638 case PointerDeclaratorKind::NonPointer: 3639 case PointerDeclaratorKind::MultiLevelPointer: 3640 // Cannot infer nullability. 3641 break; 3642 3643 case PointerDeclaratorKind::SingleLevelPointer: 3644 // Infer _Nonnull if we are in an assumes-nonnull region. 3645 if (inAssumeNonNullRegion) { 3646 inferNullability = NullabilityKind::NonNull; 3647 inferNullabilityCS = (context == Declarator::ObjCParameterContext || 3648 context == Declarator::ObjCResultContext); 3649 } 3650 break; 3651 3652 case PointerDeclaratorKind::CFErrorRefPointer: 3653 case PointerDeclaratorKind::NSErrorPointerPointer: 3654 // Within a function or method signature, infer _Nullable at both 3655 // levels. 3656 if (isFunctionOrMethod && inAssumeNonNullRegion) 3657 inferNullability = NullabilityKind::Nullable; 3658 break; 3659 3660 case PointerDeclaratorKind::MaybePointerToCFRef: 3661 if (isFunctionOrMethod) { 3662 // On pointer-to-pointer parameters marked cf_returns_retained or 3663 // cf_returns_not_retained, if the outer pointer is explicit then 3664 // infer the inner pointer as _Nullable. 3665 auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool { 3666 while (NextAttr) { 3667 if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained || 3668 NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained) 3669 return true; 3670 NextAttr = NextAttr->getNext(); 3671 } 3672 return false; 3673 }; 3674 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { 3675 if (hasCFReturnsAttr(D.getAttributes()) || 3676 hasCFReturnsAttr(InnermostChunk->getAttrs()) || 3677 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) { 3678 inferNullability = NullabilityKind::Nullable; 3679 inferNullabilityInnerOnly = true; 3680 } 3681 } 3682 } 3683 break; 3684 } 3685 break; 3686 3687 case Declarator::ConversionIdContext: 3688 complainAboutMissingNullability = CAMN_Yes; 3689 break; 3690 3691 case Declarator::AliasDeclContext: 3692 case Declarator::AliasTemplateContext: 3693 case Declarator::BlockContext: 3694 case Declarator::BlockLiteralContext: 3695 case Declarator::ConditionContext: 3696 case Declarator::CXXCatchContext: 3697 case Declarator::CXXNewContext: 3698 case Declarator::ForContext: 3699 case Declarator::LambdaExprContext: 3700 case Declarator::LambdaExprParameterContext: 3701 case Declarator::ObjCCatchContext: 3702 case Declarator::TemplateParamContext: 3703 case Declarator::TemplateTypeArgContext: 3704 case Declarator::TypeNameContext: 3705 // Don't infer in these contexts. 3706 break; 3707 } 3708 } 3709 3710 // Local function that checks the nullability for a given pointer declarator. 3711 // Returns true if _Nonnull was inferred. 3712 auto inferPointerNullability = [&](SimplePointerKind pointerKind, 3713 SourceLocation pointerLoc, 3714 AttributeList *&attrs) -> AttributeList * { 3715 // We've seen a pointer. 3716 if (NumPointersRemaining > 0) 3717 --NumPointersRemaining; 3718 3719 // If a nullability attribute is present, there's nothing to do. 3720 if (hasNullabilityAttr(attrs)) 3721 return nullptr; 3722 3723 // If we're supposed to infer nullability, do so now. 3724 if (inferNullability && !inferNullabilityInnerOnlyComplete) { 3725 AttributeList::Syntax syntax 3726 = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword 3727 : AttributeList::AS_Keyword; 3728 AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool() 3729 .create( 3730 S.getNullabilityKeyword( 3731 *inferNullability), 3732 SourceRange(pointerLoc), 3733 nullptr, SourceLocation(), 3734 nullptr, 0, syntax); 3735 3736 spliceAttrIntoList(*nullabilityAttr, attrs); 3737 3738 if (inferNullabilityCS) { 3739 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() 3740 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); 3741 } 3742 3743 if (inferNullabilityInnerOnly) 3744 inferNullabilityInnerOnlyComplete = true; 3745 return nullabilityAttr; 3746 } 3747 3748 // If we're supposed to complain about missing nullability, do so 3749 // now if it's truly missing. 3750 switch (complainAboutMissingNullability) { 3751 case CAMN_No: 3752 break; 3753 3754 case CAMN_InnerPointers: 3755 if (NumPointersRemaining == 0) 3756 break; 3757 // Fallthrough. 3758 3759 case CAMN_Yes: 3760 checkNullabilityConsistency(state, pointerKind, pointerLoc); 3761 } 3762 return nullptr; 3763 }; 3764 3765 // If the type itself could have nullability but does not, infer pointer 3766 // nullability and perform consistency checking. 3767 if (T->canHaveNullability() && S.ActiveTemplateInstantiations.empty() && 3768 !T->getNullability(S.Context)) { 3769 SimplePointerKind pointerKind = SimplePointerKind::Pointer; 3770 if (T->isBlockPointerType()) 3771 pointerKind = SimplePointerKind::BlockPointer; 3772 else if (T->isMemberPointerType()) 3773 pointerKind = SimplePointerKind::MemberPointer; 3774 3775 if (auto *attr = inferPointerNullability( 3776 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), 3777 D.getMutableDeclSpec().getAttributes().getListRef())) { 3778 T = Context.getAttributedType( 3779 AttributedType::getNullabilityAttrKind(*inferNullability), T, T); 3780 attr->setUsedAsTypeAttr(); 3781 } 3782 } 3783 3784 // Walk the DeclTypeInfo, building the recursive type as we go. 3785 // DeclTypeInfos are ordered from the identifier out, which is 3786 // opposite of what we want :). 3787 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3788 unsigned chunkIndex = e - i - 1; 3789 state.setCurrentChunkIndex(chunkIndex); 3790 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 3791 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; 3792 switch (DeclType.Kind) { 3793 case DeclaratorChunk::Paren: 3794 T = S.BuildParenType(T); 3795 break; 3796 case DeclaratorChunk::BlockPointer: 3797 // If blocks are disabled, emit an error. 3798 if (!LangOpts.Blocks) 3799 S.Diag(DeclType.Loc, diag::err_blocks_disable); 3800 3801 // Handle pointer nullability. 3802 inferPointerNullability(SimplePointerKind::BlockPointer, 3803 DeclType.Loc, DeclType.getAttrListRef()); 3804 3805 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 3806 if (DeclType.Cls.TypeQuals) 3807 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 3808 break; 3809 case DeclaratorChunk::Pointer: 3810 // Verify that we're not building a pointer to pointer to function with 3811 // exception specification. 3812 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 3813 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 3814 D.setInvalidType(true); 3815 // Build the type anyway. 3816 } 3817 3818 // Handle pointer nullability 3819 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, 3820 DeclType.getAttrListRef()); 3821 3822 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) { 3823 T = Context.getObjCObjectPointerType(T); 3824 if (DeclType.Ptr.TypeQuals) 3825 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 3826 break; 3827 } 3828 T = S.BuildPointerType(T, DeclType.Loc, Name); 3829 if (DeclType.Ptr.TypeQuals) 3830 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 3831 break; 3832 case DeclaratorChunk::Reference: { 3833 // Verify that we're not building a reference to pointer to function with 3834 // exception specification. 3835 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 3836 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 3837 D.setInvalidType(true); 3838 // Build the type anyway. 3839 } 3840 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 3841 3842 if (DeclType.Ref.HasRestrict) 3843 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 3844 break; 3845 } 3846 case DeclaratorChunk::Array: { 3847 // Verify that we're not building an array of pointers to function with 3848 // exception specification. 3849 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 3850 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 3851 D.setInvalidType(true); 3852 // Build the type anyway. 3853 } 3854 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 3855 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 3856 ArrayType::ArraySizeModifier ASM; 3857 if (ATI.isStar) 3858 ASM = ArrayType::Star; 3859 else if (ATI.hasStatic) 3860 ASM = ArrayType::Static; 3861 else 3862 ASM = ArrayType::Normal; 3863 if (ASM == ArrayType::Star && !D.isPrototypeContext()) { 3864 // FIXME: This check isn't quite right: it allows star in prototypes 3865 // for function definitions, and disallows some edge cases detailed 3866 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 3867 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 3868 ASM = ArrayType::Normal; 3869 D.setInvalidType(true); 3870 } 3871 3872 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static 3873 // shall appear only in a declaration of a function parameter with an 3874 // array type, ... 3875 if (ASM == ArrayType::Static || ATI.TypeQuals) { 3876 if (!(D.isPrototypeContext() || 3877 D.getContext() == Declarator::KNRTypeListContext)) { 3878 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << 3879 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 3880 // Remove the 'static' and the type qualifiers. 3881 if (ASM == ArrayType::Static) 3882 ASM = ArrayType::Normal; 3883 ATI.TypeQuals = 0; 3884 D.setInvalidType(true); 3885 } 3886 3887 // C99 6.7.5.2p1: ... and then only in the outermost array type 3888 // derivation. 3889 unsigned x = chunkIndex; 3890 while (x != 0) { 3891 // Walk outwards along the declarator chunks. 3892 x--; 3893 const DeclaratorChunk &DC = D.getTypeObject(x); 3894 switch (DC.Kind) { 3895 case DeclaratorChunk::Paren: 3896 continue; 3897 case DeclaratorChunk::Array: 3898 case DeclaratorChunk::Pointer: 3899 case DeclaratorChunk::Reference: 3900 case DeclaratorChunk::MemberPointer: 3901 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << 3902 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 3903 if (ASM == ArrayType::Static) 3904 ASM = ArrayType::Normal; 3905 ATI.TypeQuals = 0; 3906 D.setInvalidType(true); 3907 break; 3908 case DeclaratorChunk::Function: 3909 case DeclaratorChunk::BlockPointer: 3910 case DeclaratorChunk::Pipe: 3911 // These are invalid anyway, so just ignore. 3912 break; 3913 } 3914 } 3915 } 3916 const AutoType *AT = T->getContainedAutoType(); 3917 // Allow arrays of auto if we are a generic lambda parameter. 3918 // i.e. [](auto (&array)[5]) { return array[0]; }; OK 3919 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) { 3920 // We've already diagnosed this for decltype(auto). 3921 if (!AT->isDecltypeAuto()) 3922 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) 3923 << getPrintableNameForEntity(Name) << T; 3924 T = QualType(); 3925 break; 3926 } 3927 3928 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 3929 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 3930 break; 3931 } 3932 case DeclaratorChunk::Function: { 3933 // If the function declarator has a prototype (i.e. it is not () and 3934 // does not have a K&R-style identifier list), then the arguments are part 3935 // of the type, otherwise the argument list is (). 3936 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 3937 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier(); 3938 3939 // Check for auto functions and trailing return type and adjust the 3940 // return type accordingly. 3941 if (!D.isInvalidType()) { 3942 // trailing-return-type is only required if we're declaring a function, 3943 // and not, for instance, a pointer to a function. 3944 if (D.getDeclSpec().containsPlaceholderType() && 3945 !FTI.hasTrailingReturnType() && chunkIndex == 0 && 3946 !S.getLangOpts().CPlusPlus14) { 3947 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 3948 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto 3949 ? diag::err_auto_missing_trailing_return 3950 : diag::err_deduced_return_type); 3951 T = Context.IntTy; 3952 D.setInvalidType(true); 3953 } else if (FTI.hasTrailingReturnType()) { 3954 // T must be exactly 'auto' at this point. See CWG issue 681. 3955 if (isa<ParenType>(T)) { 3956 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 3957 diag::err_trailing_return_in_parens) 3958 << T << D.getDeclSpec().getSourceRange(); 3959 D.setInvalidType(true); 3960 } else if (D.getContext() != Declarator::LambdaExprContext && 3961 (T.hasQualifiers() || !isa<AutoType>(T) || 3962 cast<AutoType>(T)->getKeyword() != AutoTypeKeyword::Auto)) { 3963 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 3964 diag::err_trailing_return_without_auto) 3965 << T << D.getDeclSpec().getSourceRange(); 3966 D.setInvalidType(true); 3967 } 3968 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); 3969 if (T.isNull()) { 3970 // An error occurred parsing the trailing return type. 3971 T = Context.IntTy; 3972 D.setInvalidType(true); 3973 } 3974 } 3975 } 3976 3977 // C99 6.7.5.3p1: The return type may not be a function or array type. 3978 // For conversion functions, we'll diagnose this particular error later. 3979 if ((T->isArrayType() || T->isFunctionType()) && 3980 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 3981 unsigned diagID = diag::err_func_returning_array_function; 3982 // Last processing chunk in block context means this function chunk 3983 // represents the block. 3984 if (chunkIndex == 0 && 3985 D.getContext() == Declarator::BlockLiteralContext) 3986 diagID = diag::err_block_returning_array_function; 3987 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 3988 T = Context.IntTy; 3989 D.setInvalidType(true); 3990 } 3991 3992 // Do not allow returning half FP value. 3993 // FIXME: This really should be in BuildFunctionType. 3994 if (T->isHalfType()) { 3995 if (S.getLangOpts().OpenCL) { 3996 if (!S.getOpenCLOptions().cl_khr_fp16) { 3997 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) 3998 << T << 0 /*pointer hint*/; 3999 D.setInvalidType(true); 4000 } 4001 } else if (!S.getLangOpts().HalfArgsAndReturns) { 4002 S.Diag(D.getIdentifierLoc(), 4003 diag::err_parameters_retval_cannot_have_fp16_type) << 1; 4004 D.setInvalidType(true); 4005 } 4006 } 4007 4008 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a 4009 // function. 4010 if (LangOpts.OpenCL && T->isBlockPointerType()) { 4011 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) 4012 << T << 1 /*hint off*/; 4013 D.setInvalidType(true); 4014 } 4015 4016 // Methods cannot return interface types. All ObjC objects are 4017 // passed by reference. 4018 if (T->isObjCObjectType()) { 4019 SourceLocation DiagLoc, FixitLoc; 4020 if (TInfo) { 4021 DiagLoc = TInfo->getTypeLoc().getLocStart(); 4022 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd()); 4023 } else { 4024 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 4025 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd()); 4026 } 4027 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) 4028 << 0 << T 4029 << FixItHint::CreateInsertion(FixitLoc, "*"); 4030 4031 T = Context.getObjCObjectPointerType(T); 4032 if (TInfo) { 4033 TypeLocBuilder TLB; 4034 TLB.pushFullCopy(TInfo->getTypeLoc()); 4035 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); 4036 TLoc.setStarLoc(FixitLoc); 4037 TInfo = TLB.getTypeSourceInfo(Context, T); 4038 } 4039 4040 D.setInvalidType(true); 4041 } 4042 4043 // cv-qualifiers on return types are pointless except when the type is a 4044 // class type in C++. 4045 if ((T.getCVRQualifiers() || T->isAtomicType()) && 4046 !(S.getLangOpts().CPlusPlus && 4047 (T->isDependentType() || T->isRecordType()))) { 4048 if (T->isVoidType() && !S.getLangOpts().CPlusPlus && 4049 D.getFunctionDefinitionKind() == FDK_Definition) { 4050 // [6.9.1/3] qualified void return is invalid on a C 4051 // function definition. Apparently ok on declarations and 4052 // in C++ though (!) 4053 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; 4054 } else 4055 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); 4056 } 4057 4058 // Objective-C ARC ownership qualifiers are ignored on the function 4059 // return type (by type canonicalization). Complain if this attribute 4060 // was written here. 4061 if (T.getQualifiers().hasObjCLifetime()) { 4062 SourceLocation AttrLoc; 4063 if (chunkIndex + 1 < D.getNumTypeObjects()) { 4064 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 4065 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs(); 4066 Attr; Attr = Attr->getNext()) { 4067 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 4068 AttrLoc = Attr->getLoc(); 4069 break; 4070 } 4071 } 4072 } 4073 if (AttrLoc.isInvalid()) { 4074 for (const AttributeList *Attr 4075 = D.getDeclSpec().getAttributes().getList(); 4076 Attr; Attr = Attr->getNext()) { 4077 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 4078 AttrLoc = Attr->getLoc(); 4079 break; 4080 } 4081 } 4082 } 4083 4084 if (AttrLoc.isValid()) { 4085 // The ownership attributes are almost always written via 4086 // the predefined 4087 // __strong/__weak/__autoreleasing/__unsafe_unretained. 4088 if (AttrLoc.isMacroID()) 4089 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first; 4090 4091 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 4092 << T.getQualifiers().getObjCLifetime(); 4093 } 4094 } 4095 4096 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { 4097 // C++ [dcl.fct]p6: 4098 // Types shall not be defined in return or parameter types. 4099 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 4100 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 4101 << Context.getTypeDeclType(Tag); 4102 } 4103 4104 // Exception specs are not allowed in typedefs. Complain, but add it 4105 // anyway. 4106 if (IsTypedefName && FTI.getExceptionSpecType()) 4107 S.Diag(FTI.getExceptionSpecLocBeg(), 4108 diag::err_exception_spec_in_typedef) 4109 << (D.getContext() == Declarator::AliasDeclContext || 4110 D.getContext() == Declarator::AliasTemplateContext); 4111 4112 // If we see "T var();" or "T var(T());" at block scope, it is probably 4113 // an attempt to initialize a variable, not a function declaration. 4114 if (FTI.isAmbiguous) 4115 warnAboutAmbiguousFunction(S, D, DeclType, T); 4116 4117 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex)); 4118 4119 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) { 4120 // Simple void foo(), where the incoming T is the result type. 4121 T = Context.getFunctionNoProtoType(T, EI); 4122 } else { 4123 // We allow a zero-parameter variadic function in C if the 4124 // function is marked with the "overloadable" attribute. Scan 4125 // for this attribute now. 4126 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) { 4127 bool Overloadable = false; 4128 for (const AttributeList *Attrs = D.getAttributes(); 4129 Attrs; Attrs = Attrs->getNext()) { 4130 if (Attrs->getKind() == AttributeList::AT_Overloadable) { 4131 Overloadable = true; 4132 break; 4133 } 4134 } 4135 4136 if (!Overloadable) 4137 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); 4138 } 4139 4140 if (FTI.NumParams && FTI.Params[0].Param == nullptr) { 4141 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 4142 // definition. 4143 S.Diag(FTI.Params[0].IdentLoc, 4144 diag::err_ident_list_in_fn_declaration); 4145 D.setInvalidType(true); 4146 // Recover by creating a K&R-style function type. 4147 T = Context.getFunctionNoProtoType(T, EI); 4148 break; 4149 } 4150 4151 FunctionProtoType::ExtProtoInfo EPI; 4152 EPI.ExtInfo = EI; 4153 EPI.Variadic = FTI.isVariadic; 4154 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 4155 EPI.TypeQuals = FTI.TypeQuals; 4156 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 4157 : FTI.RefQualifierIsLValueRef? RQ_LValue 4158 : RQ_RValue; 4159 4160 // Otherwise, we have a function with a parameter list that is 4161 // potentially variadic. 4162 SmallVector<QualType, 16> ParamTys; 4163 ParamTys.reserve(FTI.NumParams); 4164 4165 SmallVector<FunctionProtoType::ExtParameterInfo, 16> 4166 ExtParameterInfos(FTI.NumParams); 4167 bool HasAnyInterestingExtParameterInfos = false; 4168 4169 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 4170 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 4171 QualType ParamTy = Param->getType(); 4172 assert(!ParamTy.isNull() && "Couldn't parse type?"); 4173 4174 // Look for 'void'. void is allowed only as a single parameter to a 4175 // function with no other parameters (C99 6.7.5.3p10). We record 4176 // int(void) as a FunctionProtoType with an empty parameter list. 4177 if (ParamTy->isVoidType()) { 4178 // If this is something like 'float(int, void)', reject it. 'void' 4179 // is an incomplete type (C99 6.2.5p19) and function decls cannot 4180 // have parameters of incomplete type. 4181 if (FTI.NumParams != 1 || FTI.isVariadic) { 4182 S.Diag(DeclType.Loc, diag::err_void_only_param); 4183 ParamTy = Context.IntTy; 4184 Param->setType(ParamTy); 4185 } else if (FTI.Params[i].Ident) { 4186 // Reject, but continue to parse 'int(void abc)'. 4187 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); 4188 ParamTy = Context.IntTy; 4189 Param->setType(ParamTy); 4190 } else { 4191 // Reject, but continue to parse 'float(const void)'. 4192 if (ParamTy.hasQualifiers()) 4193 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 4194 4195 // Do not add 'void' to the list. 4196 break; 4197 } 4198 } else if (ParamTy->isHalfType()) { 4199 // Disallow half FP parameters. 4200 // FIXME: This really should be in BuildFunctionType. 4201 if (S.getLangOpts().OpenCL) { 4202 if (!S.getOpenCLOptions().cl_khr_fp16) { 4203 S.Diag(Param->getLocation(), 4204 diag::err_opencl_half_param) << ParamTy; 4205 D.setInvalidType(); 4206 Param->setInvalidDecl(); 4207 } 4208 } else if (!S.getLangOpts().HalfArgsAndReturns) { 4209 S.Diag(Param->getLocation(), 4210 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 4211 D.setInvalidType(); 4212 } 4213 } else if (!FTI.hasPrototype) { 4214 if (ParamTy->isPromotableIntegerType()) { 4215 ParamTy = Context.getPromotedIntegerType(ParamTy); 4216 Param->setKNRPromoted(true); 4217 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { 4218 if (BTy->getKind() == BuiltinType::Float) { 4219 ParamTy = Context.DoubleTy; 4220 Param->setKNRPromoted(true); 4221 } 4222 } 4223 } 4224 4225 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { 4226 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); 4227 HasAnyInterestingExtParameterInfos = true; 4228 } 4229 4230 if (auto attr = Param->getAttr<ParameterABIAttr>()) { 4231 ExtParameterInfos[i] = 4232 ExtParameterInfos[i].withABI(attr->getABI()); 4233 HasAnyInterestingExtParameterInfos = true; 4234 } 4235 4236 ParamTys.push_back(ParamTy); 4237 } 4238 4239 if (HasAnyInterestingExtParameterInfos) { 4240 EPI.ExtParameterInfos = ExtParameterInfos.data(); 4241 checkExtParameterInfos(S, ParamTys, EPI, 4242 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); 4243 } 4244 4245 SmallVector<QualType, 4> Exceptions; 4246 SmallVector<ParsedType, 2> DynamicExceptions; 4247 SmallVector<SourceRange, 2> DynamicExceptionRanges; 4248 Expr *NoexceptExpr = nullptr; 4249 4250 if (FTI.getExceptionSpecType() == EST_Dynamic) { 4251 // FIXME: It's rather inefficient to have to split into two vectors 4252 // here. 4253 unsigned N = FTI.NumExceptions; 4254 DynamicExceptions.reserve(N); 4255 DynamicExceptionRanges.reserve(N); 4256 for (unsigned I = 0; I != N; ++I) { 4257 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 4258 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 4259 } 4260 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 4261 NoexceptExpr = FTI.NoexceptExpr; 4262 } 4263 4264 S.checkExceptionSpecification(D.isFunctionDeclarationContext(), 4265 FTI.getExceptionSpecType(), 4266 DynamicExceptions, 4267 DynamicExceptionRanges, 4268 NoexceptExpr, 4269 Exceptions, 4270 EPI.ExceptionSpec); 4271 4272 T = Context.getFunctionType(T, ParamTys, EPI); 4273 } 4274 break; 4275 } 4276 case DeclaratorChunk::MemberPointer: { 4277 // The scope spec must refer to a class, or be dependent. 4278 CXXScopeSpec &SS = DeclType.Mem.Scope(); 4279 QualType ClsType; 4280 4281 // Handle pointer nullability. 4282 inferPointerNullability(SimplePointerKind::MemberPointer, 4283 DeclType.Loc, DeclType.getAttrListRef()); 4284 4285 if (SS.isInvalid()) { 4286 // Avoid emitting extra errors if we already errored on the scope. 4287 D.setInvalidType(true); 4288 } else if (S.isDependentScopeSpecifier(SS) || 4289 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 4290 NestedNameSpecifier *NNS = SS.getScopeRep(); 4291 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 4292 switch (NNS->getKind()) { 4293 case NestedNameSpecifier::Identifier: 4294 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 4295 NNS->getAsIdentifier()); 4296 break; 4297 4298 case NestedNameSpecifier::Namespace: 4299 case NestedNameSpecifier::NamespaceAlias: 4300 case NestedNameSpecifier::Global: 4301 case NestedNameSpecifier::Super: 4302 llvm_unreachable("Nested-name-specifier must name a type"); 4303 4304 case NestedNameSpecifier::TypeSpec: 4305 case NestedNameSpecifier::TypeSpecWithTemplate: 4306 ClsType = QualType(NNS->getAsType(), 0); 4307 // Note: if the NNS has a prefix and ClsType is a nondependent 4308 // TemplateSpecializationType, then the NNS prefix is NOT included 4309 // in ClsType; hence we wrap ClsType into an ElaboratedType. 4310 // NOTE: in particular, no wrap occurs if ClsType already is an 4311 // Elaborated, DependentName, or DependentTemplateSpecialization. 4312 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 4313 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 4314 break; 4315 } 4316 } else { 4317 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 4318 diag::err_illegal_decl_mempointer_in_nonclass) 4319 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 4320 << DeclType.Mem.Scope().getRange(); 4321 D.setInvalidType(true); 4322 } 4323 4324 if (!ClsType.isNull()) 4325 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, 4326 D.getIdentifier()); 4327 if (T.isNull()) { 4328 T = Context.IntTy; 4329 D.setInvalidType(true); 4330 } else if (DeclType.Mem.TypeQuals) { 4331 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 4332 } 4333 break; 4334 } 4335 4336 case DeclaratorChunk::Pipe: { 4337 T = S.BuildPipeType(T, DeclType.Loc ); 4338 break; 4339 } 4340 } 4341 4342 if (T.isNull()) { 4343 D.setInvalidType(true); 4344 T = Context.IntTy; 4345 } 4346 4347 // See if there are any attributes on this declarator chunk. 4348 processTypeAttrs(state, T, TAL_DeclChunk, 4349 const_cast<AttributeList *>(DeclType.getAttrs())); 4350 } 4351 4352 assert(!T.isNull() && "T must not be null after this point"); 4353 4354 if (LangOpts.CPlusPlus && T->isFunctionType()) { 4355 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 4356 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 4357 4358 // C++ 8.3.5p4: 4359 // A cv-qualifier-seq shall only be part of the function type 4360 // for a nonstatic member function, the function type to which a pointer 4361 // to member refers, or the top-level function type of a function typedef 4362 // declaration. 4363 // 4364 // Core issue 547 also allows cv-qualifiers on function types that are 4365 // top-level template type arguments. 4366 bool FreeFunction; 4367 if (!D.getCXXScopeSpec().isSet()) { 4368 FreeFunction = ((D.getContext() != Declarator::MemberContext && 4369 D.getContext() != Declarator::LambdaExprContext) || 4370 D.getDeclSpec().isFriendSpecified()); 4371 } else { 4372 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 4373 FreeFunction = (DC && !DC->isRecord()); 4374 } 4375 4376 // C++11 [dcl.fct]p6 (w/DR1417): 4377 // An attempt to specify a function type with a cv-qualifier-seq or a 4378 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 4379 // - the function type for a non-static member function, 4380 // - the function type to which a pointer to member refers, 4381 // - the top-level function type of a function typedef declaration or 4382 // alias-declaration, 4383 // - the type-id in the default argument of a type-parameter, or 4384 // - the type-id of a template-argument for a type-parameter 4385 // 4386 // FIXME: Checking this here is insufficient. We accept-invalid on: 4387 // 4388 // template<typename T> struct S { void f(T); }; 4389 // S<int() const> s; 4390 // 4391 // ... for instance. 4392 if (IsQualifiedFunction && 4393 !(!FreeFunction && 4394 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 4395 !IsTypedefName && 4396 D.getContext() != Declarator::TemplateTypeArgContext) { 4397 SourceLocation Loc = D.getLocStart(); 4398 SourceRange RemovalRange; 4399 unsigned I; 4400 if (D.isFunctionDeclarator(I)) { 4401 SmallVector<SourceLocation, 4> RemovalLocs; 4402 const DeclaratorChunk &Chunk = D.getTypeObject(I); 4403 assert(Chunk.Kind == DeclaratorChunk::Function); 4404 if (Chunk.Fun.hasRefQualifier()) 4405 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 4406 if (Chunk.Fun.TypeQuals & Qualifiers::Const) 4407 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); 4408 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) 4409 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); 4410 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) 4411 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); 4412 if (!RemovalLocs.empty()) { 4413 std::sort(RemovalLocs.begin(), RemovalLocs.end(), 4414 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 4415 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 4416 Loc = RemovalLocs.front(); 4417 } 4418 } 4419 4420 S.Diag(Loc, diag::err_invalid_qualified_function_type) 4421 << FreeFunction << D.isFunctionDeclarator() << T 4422 << getFunctionQualifiersAsString(FnTy) 4423 << FixItHint::CreateRemoval(RemovalRange); 4424 4425 // Strip the cv-qualifiers and ref-qualifiers from the type. 4426 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 4427 EPI.TypeQuals = 0; 4428 EPI.RefQualifier = RQ_None; 4429 4430 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), 4431 EPI); 4432 // Rebuild any parens around the identifier in the function type. 4433 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4434 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 4435 break; 4436 T = S.BuildParenType(T); 4437 } 4438 } 4439 } 4440 4441 // Apply any undistributed attributes from the declarator. 4442 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); 4443 4444 // Diagnose any ignored type attributes. 4445 state.diagnoseIgnoredTypeAttrs(T); 4446 4447 // C++0x [dcl.constexpr]p9: 4448 // A constexpr specifier used in an object declaration declares the object 4449 // as const. 4450 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 4451 T.addConst(); 4452 } 4453 4454 // If there was an ellipsis in the declarator, the declaration declares a 4455 // parameter pack whose type may be a pack expansion type. 4456 if (D.hasEllipsis()) { 4457 // C++0x [dcl.fct]p13: 4458 // A declarator-id or abstract-declarator containing an ellipsis shall 4459 // only be used in a parameter-declaration. Such a parameter-declaration 4460 // is a parameter pack (14.5.3). [...] 4461 switch (D.getContext()) { 4462 case Declarator::PrototypeContext: 4463 case Declarator::LambdaExprParameterContext: 4464 // C++0x [dcl.fct]p13: 4465 // [...] When it is part of a parameter-declaration-clause, the 4466 // parameter pack is a function parameter pack (14.5.3). The type T 4467 // of the declarator-id of the function parameter pack shall contain 4468 // a template parameter pack; each template parameter pack in T is 4469 // expanded by the function parameter pack. 4470 // 4471 // We represent function parameter packs as function parameters whose 4472 // type is a pack expansion. 4473 if (!T->containsUnexpandedParameterPack()) { 4474 S.Diag(D.getEllipsisLoc(), 4475 diag::err_function_parameter_pack_without_parameter_packs) 4476 << T << D.getSourceRange(); 4477 D.setEllipsisLoc(SourceLocation()); 4478 } else { 4479 T = Context.getPackExpansionType(T, None); 4480 } 4481 break; 4482 case Declarator::TemplateParamContext: 4483 // C++0x [temp.param]p15: 4484 // If a template-parameter is a [...] is a parameter-declaration that 4485 // declares a parameter pack (8.3.5), then the template-parameter is a 4486 // template parameter pack (14.5.3). 4487 // 4488 // Note: core issue 778 clarifies that, if there are any unexpanded 4489 // parameter packs in the type of the non-type template parameter, then 4490 // it expands those parameter packs. 4491 if (T->containsUnexpandedParameterPack()) 4492 T = Context.getPackExpansionType(T, None); 4493 else 4494 S.Diag(D.getEllipsisLoc(), 4495 LangOpts.CPlusPlus11 4496 ? diag::warn_cxx98_compat_variadic_templates 4497 : diag::ext_variadic_templates); 4498 break; 4499 4500 case Declarator::FileContext: 4501 case Declarator::KNRTypeListContext: 4502 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here? 4503 case Declarator::ObjCResultContext: // FIXME: special diagnostic here? 4504 case Declarator::TypeNameContext: 4505 case Declarator::CXXNewContext: 4506 case Declarator::AliasDeclContext: 4507 case Declarator::AliasTemplateContext: 4508 case Declarator::MemberContext: 4509 case Declarator::BlockContext: 4510 case Declarator::ForContext: 4511 case Declarator::ConditionContext: 4512 case Declarator::CXXCatchContext: 4513 case Declarator::ObjCCatchContext: 4514 case Declarator::BlockLiteralContext: 4515 case Declarator::LambdaExprContext: 4516 case Declarator::ConversionIdContext: 4517 case Declarator::TrailingReturnContext: 4518 case Declarator::TemplateTypeArgContext: 4519 // FIXME: We may want to allow parameter packs in block-literal contexts 4520 // in the future. 4521 S.Diag(D.getEllipsisLoc(), 4522 diag::err_ellipsis_in_declarator_not_parameter); 4523 D.setEllipsisLoc(SourceLocation()); 4524 break; 4525 } 4526 } 4527 4528 assert(!T.isNull() && "T must not be null at the end of this function"); 4529 if (D.isInvalidType()) 4530 return Context.getTrivialTypeSourceInfo(T); 4531 4532 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); 4533 } 4534 4535 /// GetTypeForDeclarator - Convert the type for the specified 4536 /// declarator to Type instances. 4537 /// 4538 /// The result of this call will never be null, but the associated 4539 /// type may be a null type if there's an unrecoverable error. 4540 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 4541 // Determine the type of the declarator. Not all forms of declarator 4542 // have a type. 4543 4544 TypeProcessingState state(*this, D); 4545 4546 TypeSourceInfo *ReturnTypeInfo = nullptr; 4547 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 4548 4549 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 4550 inferARCWriteback(state, T); 4551 4552 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 4553 } 4554 4555 static void transferARCOwnershipToDeclSpec(Sema &S, 4556 QualType &declSpecTy, 4557 Qualifiers::ObjCLifetime ownership) { 4558 if (declSpecTy->isObjCRetainableType() && 4559 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 4560 Qualifiers qs; 4561 qs.addObjCLifetime(ownership); 4562 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 4563 } 4564 } 4565 4566 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 4567 Qualifiers::ObjCLifetime ownership, 4568 unsigned chunkIndex) { 4569 Sema &S = state.getSema(); 4570 Declarator &D = state.getDeclarator(); 4571 4572 // Look for an explicit lifetime attribute. 4573 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 4574 for (const AttributeList *attr = chunk.getAttrs(); attr; 4575 attr = attr->getNext()) 4576 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 4577 return; 4578 4579 const char *attrStr = nullptr; 4580 switch (ownership) { 4581 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 4582 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 4583 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 4584 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 4585 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 4586 } 4587 4588 IdentifierLoc *Arg = new (S.Context) IdentifierLoc; 4589 Arg->Ident = &S.Context.Idents.get(attrStr); 4590 Arg->Loc = SourceLocation(); 4591 4592 ArgsUnion Args(Arg); 4593 4594 // If there wasn't one, add one (with an invalid source location 4595 // so that we don't make an AttributedType for it). 4596 AttributeList *attr = D.getAttributePool() 4597 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), 4598 /*scope*/ nullptr, SourceLocation(), 4599 /*args*/ &Args, 1, AttributeList::AS_GNU); 4600 spliceAttrIntoList(*attr, chunk.getAttrListRef()); 4601 4602 // TODO: mark whether we did this inference? 4603 } 4604 4605 /// \brief Used for transferring ownership in casts resulting in l-values. 4606 static void transferARCOwnership(TypeProcessingState &state, 4607 QualType &declSpecTy, 4608 Qualifiers::ObjCLifetime ownership) { 4609 Sema &S = state.getSema(); 4610 Declarator &D = state.getDeclarator(); 4611 4612 int inner = -1; 4613 bool hasIndirection = false; 4614 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4615 DeclaratorChunk &chunk = D.getTypeObject(i); 4616 switch (chunk.Kind) { 4617 case DeclaratorChunk::Paren: 4618 // Ignore parens. 4619 break; 4620 4621 case DeclaratorChunk::Array: 4622 case DeclaratorChunk::Reference: 4623 case DeclaratorChunk::Pointer: 4624 if (inner != -1) 4625 hasIndirection = true; 4626 inner = i; 4627 break; 4628 4629 case DeclaratorChunk::BlockPointer: 4630 if (inner != -1) 4631 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 4632 return; 4633 4634 case DeclaratorChunk::Function: 4635 case DeclaratorChunk::MemberPointer: 4636 case DeclaratorChunk::Pipe: 4637 return; 4638 } 4639 } 4640 4641 if (inner == -1) 4642 return; 4643 4644 DeclaratorChunk &chunk = D.getTypeObject(inner); 4645 if (chunk.Kind == DeclaratorChunk::Pointer) { 4646 if (declSpecTy->isObjCRetainableType()) 4647 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 4648 if (declSpecTy->isObjCObjectType() && hasIndirection) 4649 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 4650 } else { 4651 assert(chunk.Kind == DeclaratorChunk::Array || 4652 chunk.Kind == DeclaratorChunk::Reference); 4653 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 4654 } 4655 } 4656 4657 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 4658 TypeProcessingState state(*this, D); 4659 4660 TypeSourceInfo *ReturnTypeInfo = nullptr; 4661 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 4662 4663 if (getLangOpts().ObjC1) { 4664 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 4665 if (ownership != Qualifiers::OCL_None) 4666 transferARCOwnership(state, declSpecTy, ownership); 4667 } 4668 4669 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 4670 } 4671 4672 /// Map an AttributedType::Kind to an AttributeList::Kind. 4673 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 4674 switch (kind) { 4675 case AttributedType::attr_address_space: 4676 return AttributeList::AT_AddressSpace; 4677 case AttributedType::attr_regparm: 4678 return AttributeList::AT_Regparm; 4679 case AttributedType::attr_vector_size: 4680 return AttributeList::AT_VectorSize; 4681 case AttributedType::attr_neon_vector_type: 4682 return AttributeList::AT_NeonVectorType; 4683 case AttributedType::attr_neon_polyvector_type: 4684 return AttributeList::AT_NeonPolyVectorType; 4685 case AttributedType::attr_objc_gc: 4686 return AttributeList::AT_ObjCGC; 4687 case AttributedType::attr_objc_ownership: 4688 case AttributedType::attr_objc_inert_unsafe_unretained: 4689 return AttributeList::AT_ObjCOwnership; 4690 case AttributedType::attr_noreturn: 4691 return AttributeList::AT_NoReturn; 4692 case AttributedType::attr_cdecl: 4693 return AttributeList::AT_CDecl; 4694 case AttributedType::attr_fastcall: 4695 return AttributeList::AT_FastCall; 4696 case AttributedType::attr_stdcall: 4697 return AttributeList::AT_StdCall; 4698 case AttributedType::attr_thiscall: 4699 return AttributeList::AT_ThisCall; 4700 case AttributedType::attr_pascal: 4701 return AttributeList::AT_Pascal; 4702 case AttributedType::attr_swiftcall: 4703 return AttributeList::AT_SwiftCall; 4704 case AttributedType::attr_vectorcall: 4705 return AttributeList::AT_VectorCall; 4706 case AttributedType::attr_pcs: 4707 case AttributedType::attr_pcs_vfp: 4708 return AttributeList::AT_Pcs; 4709 case AttributedType::attr_inteloclbicc: 4710 return AttributeList::AT_IntelOclBicc; 4711 case AttributedType::attr_ms_abi: 4712 return AttributeList::AT_MSABI; 4713 case AttributedType::attr_sysv_abi: 4714 return AttributeList::AT_SysVABI; 4715 case AttributedType::attr_preserve_most: 4716 return AttributeList::AT_PreserveMost; 4717 case AttributedType::attr_preserve_all: 4718 return AttributeList::AT_PreserveAll; 4719 case AttributedType::attr_ptr32: 4720 return AttributeList::AT_Ptr32; 4721 case AttributedType::attr_ptr64: 4722 return AttributeList::AT_Ptr64; 4723 case AttributedType::attr_sptr: 4724 return AttributeList::AT_SPtr; 4725 case AttributedType::attr_uptr: 4726 return AttributeList::AT_UPtr; 4727 case AttributedType::attr_nonnull: 4728 return AttributeList::AT_TypeNonNull; 4729 case AttributedType::attr_nullable: 4730 return AttributeList::AT_TypeNullable; 4731 case AttributedType::attr_null_unspecified: 4732 return AttributeList::AT_TypeNullUnspecified; 4733 case AttributedType::attr_objc_kindof: 4734 return AttributeList::AT_ObjCKindOf; 4735 } 4736 llvm_unreachable("unexpected attribute kind!"); 4737 } 4738 4739 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 4740 const AttributeList *attrs, 4741 const AttributeList *DeclAttrs = nullptr) { 4742 // DeclAttrs and attrs cannot be both empty. 4743 assert((attrs || DeclAttrs) && 4744 "no type attributes in the expected location!"); 4745 4746 AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind()); 4747 // Try to search for an attribute of matching kind in attrs list. 4748 while (attrs && attrs->getKind() != parsedKind) 4749 attrs = attrs->getNext(); 4750 if (!attrs) { 4751 // No matching type attribute in attrs list found. 4752 // Try searching through C++11 attributes in the declarator attribute list. 4753 while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() || 4754 DeclAttrs->getKind() != parsedKind)) 4755 DeclAttrs = DeclAttrs->getNext(); 4756 attrs = DeclAttrs; 4757 } 4758 4759 assert(attrs && "no matching type attribute in expected location!"); 4760 4761 TL.setAttrNameLoc(attrs->getLoc()); 4762 if (TL.hasAttrExprOperand()) { 4763 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind"); 4764 TL.setAttrExprOperand(attrs->getArgAsExpr(0)); 4765 } else if (TL.hasAttrEnumOperand()) { 4766 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) && 4767 "unexpected attribute operand kind"); 4768 if (attrs->isArgIdent(0)) 4769 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc); 4770 else 4771 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc()); 4772 } 4773 4774 // FIXME: preserve this information to here. 4775 if (TL.hasAttrOperand()) 4776 TL.setAttrOperandParensRange(SourceRange()); 4777 } 4778 4779 namespace { 4780 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 4781 ASTContext &Context; 4782 const DeclSpec &DS; 4783 4784 public: 4785 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 4786 : Context(Context), DS(DS) {} 4787 4788 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 4789 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 4790 Visit(TL.getModifiedLoc()); 4791 } 4792 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 4793 Visit(TL.getUnqualifiedLoc()); 4794 } 4795 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 4796 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 4797 } 4798 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 4799 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 4800 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 4801 // addition field. What we have is good enough for dispay of location 4802 // of 'fixit' on interface name. 4803 TL.setNameEndLoc(DS.getLocEnd()); 4804 } 4805 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 4806 TypeSourceInfo *RepTInfo = nullptr; 4807 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 4808 TL.copy(RepTInfo->getTypeLoc()); 4809 } 4810 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 4811 TypeSourceInfo *RepTInfo = nullptr; 4812 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 4813 TL.copy(RepTInfo->getTypeLoc()); 4814 } 4815 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 4816 TypeSourceInfo *TInfo = nullptr; 4817 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4818 4819 // If we got no declarator info from previous Sema routines, 4820 // just fill with the typespec loc. 4821 if (!TInfo) { 4822 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 4823 return; 4824 } 4825 4826 TypeLoc OldTL = TInfo->getTypeLoc(); 4827 if (TInfo->getType()->getAs<ElaboratedType>()) { 4828 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 4829 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 4830 .castAs<TemplateSpecializationTypeLoc>(); 4831 TL.copy(NamedTL); 4832 } else { 4833 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 4834 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); 4835 } 4836 4837 } 4838 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 4839 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 4840 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 4841 TL.setParensRange(DS.getTypeofParensRange()); 4842 } 4843 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 4844 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 4845 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 4846 TL.setParensRange(DS.getTypeofParensRange()); 4847 assert(DS.getRepAsType()); 4848 TypeSourceInfo *TInfo = nullptr; 4849 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4850 TL.setUnderlyingTInfo(TInfo); 4851 } 4852 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 4853 // FIXME: This holds only because we only have one unary transform. 4854 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 4855 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 4856 TL.setParensRange(DS.getTypeofParensRange()); 4857 assert(DS.getRepAsType()); 4858 TypeSourceInfo *TInfo = nullptr; 4859 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4860 TL.setUnderlyingTInfo(TInfo); 4861 } 4862 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 4863 // By default, use the source location of the type specifier. 4864 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 4865 if (TL.needsExtraLocalData()) { 4866 // Set info for the written builtin specifiers. 4867 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 4868 // Try to have a meaningful source location. 4869 if (TL.getWrittenSignSpec() != TSS_unspecified) 4870 // Sign spec loc overrides the others (e.g., 'unsigned long'). 4871 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 4872 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 4873 // Width spec loc overrides type spec loc (e.g., 'short int'). 4874 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 4875 } 4876 } 4877 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 4878 ElaboratedTypeKeyword Keyword 4879 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 4880 if (DS.getTypeSpecType() == TST_typename) { 4881 TypeSourceInfo *TInfo = nullptr; 4882 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4883 if (TInfo) { 4884 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 4885 return; 4886 } 4887 } 4888 TL.setElaboratedKeywordLoc(Keyword != ETK_None 4889 ? DS.getTypeSpecTypeLoc() 4890 : SourceLocation()); 4891 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 4892 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4893 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 4894 } 4895 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 4896 assert(DS.getTypeSpecType() == TST_typename); 4897 TypeSourceInfo *TInfo = nullptr; 4898 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4899 assert(TInfo); 4900 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 4901 } 4902 void VisitDependentTemplateSpecializationTypeLoc( 4903 DependentTemplateSpecializationTypeLoc TL) { 4904 assert(DS.getTypeSpecType() == TST_typename); 4905 TypeSourceInfo *TInfo = nullptr; 4906 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4907 assert(TInfo); 4908 TL.copy( 4909 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 4910 } 4911 void VisitTagTypeLoc(TagTypeLoc TL) { 4912 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 4913 } 4914 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 4915 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 4916 // or an _Atomic qualifier. 4917 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 4918 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 4919 TL.setParensRange(DS.getTypeofParensRange()); 4920 4921 TypeSourceInfo *TInfo = nullptr; 4922 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4923 assert(TInfo); 4924 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 4925 } else { 4926 TL.setKWLoc(DS.getAtomicSpecLoc()); 4927 // No parens, to indicate this was spelled as an _Atomic qualifier. 4928 TL.setParensRange(SourceRange()); 4929 Visit(TL.getValueLoc()); 4930 } 4931 } 4932 4933 void VisitPipeTypeLoc(PipeTypeLoc TL) { 4934 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 4935 4936 TypeSourceInfo *TInfo = nullptr; 4937 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4938 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 4939 } 4940 4941 void VisitTypeLoc(TypeLoc TL) { 4942 // FIXME: add other typespec types and change this to an assert. 4943 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 4944 } 4945 }; 4946 4947 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 4948 ASTContext &Context; 4949 const DeclaratorChunk &Chunk; 4950 4951 public: 4952 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 4953 : Context(Context), Chunk(Chunk) {} 4954 4955 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 4956 llvm_unreachable("qualified type locs not expected here!"); 4957 } 4958 void VisitDecayedTypeLoc(DecayedTypeLoc TL) { 4959 llvm_unreachable("decayed type locs not expected here!"); 4960 } 4961 4962 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 4963 fillAttributedTypeLoc(TL, Chunk.getAttrs()); 4964 } 4965 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 4966 // nothing 4967 } 4968 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 4969 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 4970 TL.setCaretLoc(Chunk.Loc); 4971 } 4972 void VisitPointerTypeLoc(PointerTypeLoc TL) { 4973 assert(Chunk.Kind == DeclaratorChunk::Pointer); 4974 TL.setStarLoc(Chunk.Loc); 4975 } 4976 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 4977 assert(Chunk.Kind == DeclaratorChunk::Pointer); 4978 TL.setStarLoc(Chunk.Loc); 4979 } 4980 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 4981 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 4982 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 4983 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 4984 4985 const Type* ClsTy = TL.getClass(); 4986 QualType ClsQT = QualType(ClsTy, 0); 4987 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 4988 // Now copy source location info into the type loc component. 4989 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 4990 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 4991 case NestedNameSpecifier::Identifier: 4992 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 4993 { 4994 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 4995 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 4996 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 4997 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 4998 } 4999 break; 5000 5001 case NestedNameSpecifier::TypeSpec: 5002 case NestedNameSpecifier::TypeSpecWithTemplate: 5003 if (isa<ElaboratedType>(ClsTy)) { 5004 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 5005 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 5006 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 5007 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 5008 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 5009 } else { 5010 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 5011 } 5012 break; 5013 5014 case NestedNameSpecifier::Namespace: 5015 case NestedNameSpecifier::NamespaceAlias: 5016 case NestedNameSpecifier::Global: 5017 case NestedNameSpecifier::Super: 5018 llvm_unreachable("Nested-name-specifier must name a type"); 5019 } 5020 5021 // Finally fill in MemberPointerLocInfo fields. 5022 TL.setStarLoc(Chunk.Loc); 5023 TL.setClassTInfo(ClsTInfo); 5024 } 5025 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 5026 assert(Chunk.Kind == DeclaratorChunk::Reference); 5027 // 'Amp' is misleading: this might have been originally 5028 /// spelled with AmpAmp. 5029 TL.setAmpLoc(Chunk.Loc); 5030 } 5031 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 5032 assert(Chunk.Kind == DeclaratorChunk::Reference); 5033 assert(!Chunk.Ref.LValueRef); 5034 TL.setAmpAmpLoc(Chunk.Loc); 5035 } 5036 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 5037 assert(Chunk.Kind == DeclaratorChunk::Array); 5038 TL.setLBracketLoc(Chunk.Loc); 5039 TL.setRBracketLoc(Chunk.EndLoc); 5040 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 5041 } 5042 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 5043 assert(Chunk.Kind == DeclaratorChunk::Function); 5044 TL.setLocalRangeBegin(Chunk.Loc); 5045 TL.setLocalRangeEnd(Chunk.EndLoc); 5046 5047 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 5048 TL.setLParenLoc(FTI.getLParenLoc()); 5049 TL.setRParenLoc(FTI.getRParenLoc()); 5050 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { 5051 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 5052 TL.setParam(tpi++, Param); 5053 } 5054 // FIXME: exception specs 5055 } 5056 void VisitParenTypeLoc(ParenTypeLoc TL) { 5057 assert(Chunk.Kind == DeclaratorChunk::Paren); 5058 TL.setLParenLoc(Chunk.Loc); 5059 TL.setRParenLoc(Chunk.EndLoc); 5060 } 5061 void VisitPipeTypeLoc(PipeTypeLoc TL) { 5062 assert(Chunk.Kind == DeclaratorChunk::Pipe); 5063 TL.setKWLoc(Chunk.Loc); 5064 } 5065 5066 void VisitTypeLoc(TypeLoc TL) { 5067 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 5068 } 5069 }; 5070 } // end anonymous namespace 5071 5072 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 5073 SourceLocation Loc; 5074 switch (Chunk.Kind) { 5075 case DeclaratorChunk::Function: 5076 case DeclaratorChunk::Array: 5077 case DeclaratorChunk::Paren: 5078 case DeclaratorChunk::Pipe: 5079 llvm_unreachable("cannot be _Atomic qualified"); 5080 5081 case DeclaratorChunk::Pointer: 5082 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); 5083 break; 5084 5085 case DeclaratorChunk::BlockPointer: 5086 case DeclaratorChunk::Reference: 5087 case DeclaratorChunk::MemberPointer: 5088 // FIXME: Provide a source location for the _Atomic keyword. 5089 break; 5090 } 5091 5092 ATL.setKWLoc(Loc); 5093 ATL.setParensRange(SourceRange()); 5094 } 5095 5096 /// \brief Create and instantiate a TypeSourceInfo with type source information. 5097 /// 5098 /// \param T QualType referring to the type as written in source code. 5099 /// 5100 /// \param ReturnTypeInfo For declarators whose return type does not show 5101 /// up in the normal place in the declaration specifiers (such as a C++ 5102 /// conversion function), this pointer will refer to a type source information 5103 /// for that return type. 5104 TypeSourceInfo * 5105 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 5106 TypeSourceInfo *ReturnTypeInfo) { 5107 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 5108 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 5109 const AttributeList *DeclAttrs = D.getAttributes(); 5110 5111 // Handle parameter packs whose type is a pack expansion. 5112 if (isa<PackExpansionType>(T)) { 5113 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 5114 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 5115 } 5116 5117 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5118 // An AtomicTypeLoc might be produced by an atomic qualifier in this 5119 // declarator chunk. 5120 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 5121 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 5122 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 5123 } 5124 5125 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 5126 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs); 5127 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 5128 } 5129 5130 // FIXME: Ordering here? 5131 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) 5132 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 5133 5134 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 5135 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 5136 } 5137 5138 // If we have different source information for the return type, use 5139 // that. This really only applies to C++ conversion functions. 5140 if (ReturnTypeInfo) { 5141 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 5142 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 5143 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 5144 } else { 5145 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 5146 } 5147 5148 return TInfo; 5149 } 5150 5151 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 5152 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 5153 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 5154 // and Sema during declaration parsing. Try deallocating/caching them when 5155 // it's appropriate, instead of allocating them and keeping them around. 5156 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 5157 TypeAlignment); 5158 new (LocT) LocInfoType(T, TInfo); 5159 assert(LocT->getTypeClass() != T->getTypeClass() && 5160 "LocInfoType's TypeClass conflicts with an existing Type class"); 5161 return ParsedType::make(QualType(LocT, 0)); 5162 } 5163 5164 void LocInfoType::getAsStringInternal(std::string &Str, 5165 const PrintingPolicy &Policy) const { 5166 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 5167 " was used directly instead of getting the QualType through" 5168 " GetTypeFromParser"); 5169 } 5170 5171 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 5172 // C99 6.7.6: Type names have no identifier. This is already validated by 5173 // the parser. 5174 assert(D.getIdentifier() == nullptr && 5175 "Type name should have no identifier!"); 5176 5177 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5178 QualType T = TInfo->getType(); 5179 if (D.isInvalidType()) 5180 return true; 5181 5182 // Make sure there are no unused decl attributes on the declarator. 5183 // We don't want to do this for ObjC parameters because we're going 5184 // to apply them to the actual parameter declaration. 5185 // Likewise, we don't want to do this for alias declarations, because 5186 // we are actually going to build a declaration from this eventually. 5187 if (D.getContext() != Declarator::ObjCParameterContext && 5188 D.getContext() != Declarator::AliasDeclContext && 5189 D.getContext() != Declarator::AliasTemplateContext) 5190 checkUnusedDeclAttributes(D); 5191 5192 if (getLangOpts().CPlusPlus) { 5193 // Check that there are no default arguments (C++ only). 5194 CheckExtraCXXDefaultArguments(D); 5195 } 5196 5197 return CreateParsedType(T, TInfo); 5198 } 5199 5200 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 5201 QualType T = Context.getObjCInstanceType(); 5202 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 5203 return CreateParsedType(T, TInfo); 5204 } 5205 5206 //===----------------------------------------------------------------------===// 5207 // Type Attribute Processing 5208 //===----------------------------------------------------------------------===// 5209 5210 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 5211 /// specified type. The attribute contains 1 argument, the id of the address 5212 /// space for the type. 5213 static void HandleAddressSpaceTypeAttribute(QualType &Type, 5214 const AttributeList &Attr, Sema &S){ 5215 5216 // If this type is already address space qualified, reject it. 5217 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by 5218 // qualifiers for two or more different address spaces." 5219 if (Type.getAddressSpace()) { 5220 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 5221 Attr.setInvalid(); 5222 return; 5223 } 5224 5225 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 5226 // qualified by an address-space qualifier." 5227 if (Type->isFunctionType()) { 5228 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 5229 Attr.setInvalid(); 5230 return; 5231 } 5232 5233 unsigned ASIdx; 5234 if (Attr.getKind() == AttributeList::AT_AddressSpace) { 5235 // Check the attribute arguments. 5236 if (Attr.getNumArgs() != 1) { 5237 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 5238 << Attr.getName() << 1; 5239 Attr.setInvalid(); 5240 return; 5241 } 5242 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 5243 llvm::APSInt addrSpace(32); 5244 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 5245 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 5246 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 5247 << Attr.getName() << AANT_ArgumentIntegerConstant 5248 << ASArgExpr->getSourceRange(); 5249 Attr.setInvalid(); 5250 return; 5251 } 5252 5253 // Bounds checking. 5254 if (addrSpace.isSigned()) { 5255 if (addrSpace.isNegative()) { 5256 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 5257 << ASArgExpr->getSourceRange(); 5258 Attr.setInvalid(); 5259 return; 5260 } 5261 addrSpace.setIsSigned(false); 5262 } 5263 llvm::APSInt max(addrSpace.getBitWidth()); 5264 max = Qualifiers::MaxAddressSpace; 5265 if (addrSpace > max) { 5266 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 5267 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange(); 5268 Attr.setInvalid(); 5269 return; 5270 } 5271 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 5272 } else { 5273 // The keyword-based type attributes imply which address space to use. 5274 switch (Attr.getKind()) { 5275 case AttributeList::AT_OpenCLGlobalAddressSpace: 5276 ASIdx = LangAS::opencl_global; break; 5277 case AttributeList::AT_OpenCLLocalAddressSpace: 5278 ASIdx = LangAS::opencl_local; break; 5279 case AttributeList::AT_OpenCLConstantAddressSpace: 5280 ASIdx = LangAS::opencl_constant; break; 5281 case AttributeList::AT_OpenCLGenericAddressSpace: 5282 ASIdx = LangAS::opencl_generic; break; 5283 default: 5284 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace); 5285 ASIdx = 0; break; 5286 } 5287 } 5288 5289 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 5290 } 5291 5292 /// Does this type have a "direct" ownership qualifier? That is, 5293 /// is it written like "__strong id", as opposed to something like 5294 /// "typeof(foo)", where that happens to be strong? 5295 static bool hasDirectOwnershipQualifier(QualType type) { 5296 // Fast path: no qualifier at all. 5297 assert(type.getQualifiers().hasObjCLifetime()); 5298 5299 while (true) { 5300 // __strong id 5301 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { 5302 if (attr->getAttrKind() == AttributedType::attr_objc_ownership) 5303 return true; 5304 5305 type = attr->getModifiedType(); 5306 5307 // X *__strong (...) 5308 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { 5309 type = paren->getInnerType(); 5310 5311 // That's it for things we want to complain about. In particular, 5312 // we do not want to look through typedefs, typeof(expr), 5313 // typeof(type), or any other way that the type is somehow 5314 // abstracted. 5315 } else { 5316 5317 return false; 5318 } 5319 } 5320 } 5321 5322 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 5323 /// attribute on the specified type. 5324 /// 5325 /// Returns 'true' if the attribute was handled. 5326 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 5327 AttributeList &attr, 5328 QualType &type) { 5329 bool NonObjCPointer = false; 5330 5331 if (!type->isDependentType() && !type->isUndeducedType()) { 5332 if (const PointerType *ptr = type->getAs<PointerType>()) { 5333 QualType pointee = ptr->getPointeeType(); 5334 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 5335 return false; 5336 // It is important not to lose the source info that there was an attribute 5337 // applied to non-objc pointer. We will create an attributed type but 5338 // its type will be the same as the original type. 5339 NonObjCPointer = true; 5340 } else if (!type->isObjCRetainableType()) { 5341 return false; 5342 } 5343 5344 // Don't accept an ownership attribute in the declspec if it would 5345 // just be the return type of a block pointer. 5346 if (state.isProcessingDeclSpec()) { 5347 Declarator &D = state.getDeclarator(); 5348 if (maybeMovePastReturnType(D, D.getNumTypeObjects(), 5349 /*onlyBlockPointers=*/true)) 5350 return false; 5351 } 5352 } 5353 5354 Sema &S = state.getSema(); 5355 SourceLocation AttrLoc = attr.getLoc(); 5356 if (AttrLoc.isMacroID()) 5357 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first; 5358 5359 if (!attr.isArgIdent(0)) { 5360 S.Diag(AttrLoc, diag::err_attribute_argument_type) 5361 << attr.getName() << AANT_ArgumentString; 5362 attr.setInvalid(); 5363 return true; 5364 } 5365 5366 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 5367 Qualifiers::ObjCLifetime lifetime; 5368 if (II->isStr("none")) 5369 lifetime = Qualifiers::OCL_ExplicitNone; 5370 else if (II->isStr("strong")) 5371 lifetime = Qualifiers::OCL_Strong; 5372 else if (II->isStr("weak")) 5373 lifetime = Qualifiers::OCL_Weak; 5374 else if (II->isStr("autoreleasing")) 5375 lifetime = Qualifiers::OCL_Autoreleasing; 5376 else { 5377 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 5378 << attr.getName() << II; 5379 attr.setInvalid(); 5380 return true; 5381 } 5382 5383 // Just ignore lifetime attributes other than __weak and __unsafe_unretained 5384 // outside of ARC mode. 5385 if (!S.getLangOpts().ObjCAutoRefCount && 5386 lifetime != Qualifiers::OCL_Weak && 5387 lifetime != Qualifiers::OCL_ExplicitNone) { 5388 return true; 5389 } 5390 5391 SplitQualType underlyingType = type.split(); 5392 5393 // Check for redundant/conflicting ownership qualifiers. 5394 if (Qualifiers::ObjCLifetime previousLifetime 5395 = type.getQualifiers().getObjCLifetime()) { 5396 // If it's written directly, that's an error. 5397 if (hasDirectOwnershipQualifier(type)) { 5398 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 5399 << type; 5400 return true; 5401 } 5402 5403 // Otherwise, if the qualifiers actually conflict, pull sugar off 5404 // until we reach a type that is directly qualified. 5405 if (previousLifetime != lifetime) { 5406 // This should always terminate: the canonical type is 5407 // qualified, so some bit of sugar must be hiding it. 5408 while (!underlyingType.Quals.hasObjCLifetime()) { 5409 underlyingType = underlyingType.getSingleStepDesugaredType(); 5410 } 5411 underlyingType.Quals.removeObjCLifetime(); 5412 } 5413 } 5414 5415 underlyingType.Quals.addObjCLifetime(lifetime); 5416 5417 if (NonObjCPointer) { 5418 StringRef name = attr.getName()->getName(); 5419 switch (lifetime) { 5420 case Qualifiers::OCL_None: 5421 case Qualifiers::OCL_ExplicitNone: 5422 break; 5423 case Qualifiers::OCL_Strong: name = "__strong"; break; 5424 case Qualifiers::OCL_Weak: name = "__weak"; break; 5425 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 5426 } 5427 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name 5428 << TDS_ObjCObjOrBlock << type; 5429 } 5430 5431 // Don't actually add the __unsafe_unretained qualifier in non-ARC files, 5432 // because having both 'T' and '__unsafe_unretained T' exist in the type 5433 // system causes unfortunate widespread consistency problems. (For example, 5434 // they're not considered compatible types, and we mangle them identicially 5435 // as template arguments.) These problems are all individually fixable, 5436 // but it's easier to just not add the qualifier and instead sniff it out 5437 // in specific places using isObjCInertUnsafeUnretainedType(). 5438 // 5439 // Doing this does means we miss some trivial consistency checks that 5440 // would've triggered in ARC, but that's better than trying to solve all 5441 // the coexistence problems with __unsafe_unretained. 5442 if (!S.getLangOpts().ObjCAutoRefCount && 5443 lifetime == Qualifiers::OCL_ExplicitNone) { 5444 type = S.Context.getAttributedType( 5445 AttributedType::attr_objc_inert_unsafe_unretained, 5446 type, type); 5447 return true; 5448 } 5449 5450 QualType origType = type; 5451 if (!NonObjCPointer) 5452 type = S.Context.getQualifiedType(underlyingType); 5453 5454 // If we have a valid source location for the attribute, use an 5455 // AttributedType instead. 5456 if (AttrLoc.isValid()) 5457 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, 5458 origType, type); 5459 5460 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, 5461 unsigned diagnostic, QualType type) { 5462 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 5463 S.DelayedDiagnostics.add( 5464 sema::DelayedDiagnostic::makeForbiddenType( 5465 S.getSourceManager().getExpansionLoc(loc), 5466 diagnostic, type, /*ignored*/ 0)); 5467 } else { 5468 S.Diag(loc, diagnostic); 5469 } 5470 }; 5471 5472 // Sometimes, __weak isn't allowed. 5473 if (lifetime == Qualifiers::OCL_Weak && 5474 !S.getLangOpts().ObjCWeak && !NonObjCPointer) { 5475 5476 // Use a specialized diagnostic if the runtime just doesn't support them. 5477 unsigned diagnostic = 5478 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled 5479 : diag::err_arc_weak_no_runtime); 5480 5481 // In any case, delay the diagnostic until we know what we're parsing. 5482 diagnoseOrDelay(S, AttrLoc, diagnostic, type); 5483 5484 attr.setInvalid(); 5485 return true; 5486 } 5487 5488 // Forbid __weak for class objects marked as 5489 // objc_arc_weak_reference_unavailable 5490 if (lifetime == Qualifiers::OCL_Weak) { 5491 if (const ObjCObjectPointerType *ObjT = 5492 type->getAs<ObjCObjectPointerType>()) { 5493 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 5494 if (Class->isArcWeakrefUnavailable()) { 5495 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 5496 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 5497 diag::note_class_declared); 5498 } 5499 } 5500 } 5501 } 5502 5503 return true; 5504 } 5505 5506 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 5507 /// attribute on the specified type. Returns true to indicate that 5508 /// the attribute was handled, false to indicate that the type does 5509 /// not permit the attribute. 5510 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 5511 AttributeList &attr, 5512 QualType &type) { 5513 Sema &S = state.getSema(); 5514 5515 // Delay if this isn't some kind of pointer. 5516 if (!type->isPointerType() && 5517 !type->isObjCObjectPointerType() && 5518 !type->isBlockPointerType()) 5519 return false; 5520 5521 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 5522 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 5523 attr.setInvalid(); 5524 return true; 5525 } 5526 5527 // Check the attribute arguments. 5528 if (!attr.isArgIdent(0)) { 5529 S.Diag(attr.getLoc(), diag::err_attribute_argument_type) 5530 << attr.getName() << AANT_ArgumentString; 5531 attr.setInvalid(); 5532 return true; 5533 } 5534 Qualifiers::GC GCAttr; 5535 if (attr.getNumArgs() > 1) { 5536 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) 5537 << attr.getName() << 1; 5538 attr.setInvalid(); 5539 return true; 5540 } 5541 5542 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 5543 if (II->isStr("weak")) 5544 GCAttr = Qualifiers::Weak; 5545 else if (II->isStr("strong")) 5546 GCAttr = Qualifiers::Strong; 5547 else { 5548 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 5549 << attr.getName() << II; 5550 attr.setInvalid(); 5551 return true; 5552 } 5553 5554 QualType origType = type; 5555 type = S.Context.getObjCGCQualType(origType, GCAttr); 5556 5557 // Make an attributed type to preserve the source information. 5558 if (attr.getLoc().isValid()) 5559 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 5560 origType, type); 5561 5562 return true; 5563 } 5564 5565 namespace { 5566 /// A helper class to unwrap a type down to a function for the 5567 /// purposes of applying attributes there. 5568 /// 5569 /// Use: 5570 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 5571 /// if (unwrapped.isFunctionType()) { 5572 /// const FunctionType *fn = unwrapped.get(); 5573 /// // change fn somehow 5574 /// T = unwrapped.wrap(fn); 5575 /// } 5576 struct FunctionTypeUnwrapper { 5577 enum WrapKind { 5578 Desugar, 5579 Attributed, 5580 Parens, 5581 Pointer, 5582 BlockPointer, 5583 Reference, 5584 MemberPointer 5585 }; 5586 5587 QualType Original; 5588 const FunctionType *Fn; 5589 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 5590 5591 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 5592 while (true) { 5593 const Type *Ty = T.getTypePtr(); 5594 if (isa<FunctionType>(Ty)) { 5595 Fn = cast<FunctionType>(Ty); 5596 return; 5597 } else if (isa<ParenType>(Ty)) { 5598 T = cast<ParenType>(Ty)->getInnerType(); 5599 Stack.push_back(Parens); 5600 } else if (isa<PointerType>(Ty)) { 5601 T = cast<PointerType>(Ty)->getPointeeType(); 5602 Stack.push_back(Pointer); 5603 } else if (isa<BlockPointerType>(Ty)) { 5604 T = cast<BlockPointerType>(Ty)->getPointeeType(); 5605 Stack.push_back(BlockPointer); 5606 } else if (isa<MemberPointerType>(Ty)) { 5607 T = cast<MemberPointerType>(Ty)->getPointeeType(); 5608 Stack.push_back(MemberPointer); 5609 } else if (isa<ReferenceType>(Ty)) { 5610 T = cast<ReferenceType>(Ty)->getPointeeType(); 5611 Stack.push_back(Reference); 5612 } else if (isa<AttributedType>(Ty)) { 5613 T = cast<AttributedType>(Ty)->getEquivalentType(); 5614 Stack.push_back(Attributed); 5615 } else { 5616 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 5617 if (Ty == DTy) { 5618 Fn = nullptr; 5619 return; 5620 } 5621 5622 T = QualType(DTy, 0); 5623 Stack.push_back(Desugar); 5624 } 5625 } 5626 } 5627 5628 bool isFunctionType() const { return (Fn != nullptr); } 5629 const FunctionType *get() const { return Fn; } 5630 5631 QualType wrap(Sema &S, const FunctionType *New) { 5632 // If T wasn't modified from the unwrapped type, do nothing. 5633 if (New == get()) return Original; 5634 5635 Fn = New; 5636 return wrap(S.Context, Original, 0); 5637 } 5638 5639 private: 5640 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 5641 if (I == Stack.size()) 5642 return C.getQualifiedType(Fn, Old.getQualifiers()); 5643 5644 // Build up the inner type, applying the qualifiers from the old 5645 // type to the new type. 5646 SplitQualType SplitOld = Old.split(); 5647 5648 // As a special case, tail-recurse if there are no qualifiers. 5649 if (SplitOld.Quals.empty()) 5650 return wrap(C, SplitOld.Ty, I); 5651 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 5652 } 5653 5654 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 5655 if (I == Stack.size()) return QualType(Fn, 0); 5656 5657 switch (static_cast<WrapKind>(Stack[I++])) { 5658 case Desugar: 5659 // This is the point at which we potentially lose source 5660 // information. 5661 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 5662 5663 case Attributed: 5664 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); 5665 5666 case Parens: { 5667 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 5668 return C.getParenType(New); 5669 } 5670 5671 case Pointer: { 5672 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 5673 return C.getPointerType(New); 5674 } 5675 5676 case BlockPointer: { 5677 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 5678 return C.getBlockPointerType(New); 5679 } 5680 5681 case MemberPointer: { 5682 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 5683 QualType New = wrap(C, OldMPT->getPointeeType(), I); 5684 return C.getMemberPointerType(New, OldMPT->getClass()); 5685 } 5686 5687 case Reference: { 5688 const ReferenceType *OldRef = cast<ReferenceType>(Old); 5689 QualType New = wrap(C, OldRef->getPointeeType(), I); 5690 if (isa<LValueReferenceType>(OldRef)) 5691 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 5692 else 5693 return C.getRValueReferenceType(New); 5694 } 5695 } 5696 5697 llvm_unreachable("unknown wrapping kind"); 5698 } 5699 }; 5700 } // end anonymous namespace 5701 5702 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, 5703 AttributeList &Attr, 5704 QualType &Type) { 5705 Sema &S = State.getSema(); 5706 5707 AttributeList::Kind Kind = Attr.getKind(); 5708 QualType Desugared = Type; 5709 const AttributedType *AT = dyn_cast<AttributedType>(Type); 5710 while (AT) { 5711 AttributedType::Kind CurAttrKind = AT->getAttrKind(); 5712 5713 // You cannot specify duplicate type attributes, so if the attribute has 5714 // already been applied, flag it. 5715 if (getAttrListKind(CurAttrKind) == Kind) { 5716 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact) 5717 << Attr.getName(); 5718 return true; 5719 } 5720 5721 // You cannot have both __sptr and __uptr on the same type, nor can you 5722 // have __ptr32 and __ptr64. 5723 if ((CurAttrKind == AttributedType::attr_ptr32 && 5724 Kind == AttributeList::AT_Ptr64) || 5725 (CurAttrKind == AttributedType::attr_ptr64 && 5726 Kind == AttributeList::AT_Ptr32)) { 5727 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 5728 << "'__ptr32'" << "'__ptr64'"; 5729 return true; 5730 } else if ((CurAttrKind == AttributedType::attr_sptr && 5731 Kind == AttributeList::AT_UPtr) || 5732 (CurAttrKind == AttributedType::attr_uptr && 5733 Kind == AttributeList::AT_SPtr)) { 5734 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 5735 << "'__sptr'" << "'__uptr'"; 5736 return true; 5737 } 5738 5739 Desugared = AT->getEquivalentType(); 5740 AT = dyn_cast<AttributedType>(Desugared); 5741 } 5742 5743 // Pointer type qualifiers can only operate on pointer types, but not 5744 // pointer-to-member types. 5745 if (!isa<PointerType>(Desugared)) { 5746 if (Type->isMemberPointerType()) 5747 S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers) 5748 << Attr.getName(); 5749 else 5750 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only) 5751 << Attr.getName() << 0; 5752 return true; 5753 } 5754 5755 AttributedType::Kind TAK; 5756 switch (Kind) { 5757 default: llvm_unreachable("Unknown attribute kind"); 5758 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break; 5759 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break; 5760 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break; 5761 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break; 5762 } 5763 5764 Type = S.Context.getAttributedType(TAK, Type, Type); 5765 return false; 5766 } 5767 5768 bool Sema::checkNullabilityTypeSpecifier(QualType &type, 5769 NullabilityKind nullability, 5770 SourceLocation nullabilityLoc, 5771 bool isContextSensitive) { 5772 // We saw a nullability type specifier. If this is the first one for 5773 // this file, note that. 5774 FileID file = getNullabilityCompletenessCheckFileID(*this, nullabilityLoc); 5775 if (!file.isInvalid()) { 5776 FileNullability &fileNullability = NullabilityMap[file]; 5777 if (!fileNullability.SawTypeNullability) { 5778 // If we have already seen a pointer declarator without a nullability 5779 // annotation, complain about it. 5780 if (fileNullability.PointerLoc.isValid()) { 5781 Diag(fileNullability.PointerLoc, diag::warn_nullability_missing) 5782 << static_cast<unsigned>(fileNullability.PointerKind); 5783 } 5784 5785 fileNullability.SawTypeNullability = true; 5786 } 5787 } 5788 5789 // Check for existing nullability attributes on the type. 5790 QualType desugared = type; 5791 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { 5792 // Check whether there is already a null 5793 if (auto existingNullability = attributed->getImmediateNullability()) { 5794 // Duplicated nullability. 5795 if (nullability == *existingNullability) { 5796 Diag(nullabilityLoc, diag::warn_nullability_duplicate) 5797 << DiagNullabilityKind(nullability, isContextSensitive) 5798 << FixItHint::CreateRemoval(nullabilityLoc); 5799 5800 break; 5801 } 5802 5803 // Conflicting nullability. 5804 Diag(nullabilityLoc, diag::err_nullability_conflicting) 5805 << DiagNullabilityKind(nullability, isContextSensitive) 5806 << DiagNullabilityKind(*existingNullability, false); 5807 return true; 5808 } 5809 5810 desugared = attributed->getModifiedType(); 5811 } 5812 5813 // If there is already a different nullability specifier, complain. 5814 // This (unlike the code above) looks through typedefs that might 5815 // have nullability specifiers on them, which means we cannot 5816 // provide a useful Fix-It. 5817 if (auto existingNullability = desugared->getNullability(Context)) { 5818 if (nullability != *existingNullability) { 5819 Diag(nullabilityLoc, diag::err_nullability_conflicting) 5820 << DiagNullabilityKind(nullability, isContextSensitive) 5821 << DiagNullabilityKind(*existingNullability, false); 5822 5823 // Try to find the typedef with the existing nullability specifier. 5824 if (auto typedefType = desugared->getAs<TypedefType>()) { 5825 TypedefNameDecl *typedefDecl = typedefType->getDecl(); 5826 QualType underlyingType = typedefDecl->getUnderlyingType(); 5827 if (auto typedefNullability 5828 = AttributedType::stripOuterNullability(underlyingType)) { 5829 if (*typedefNullability == *existingNullability) { 5830 Diag(typedefDecl->getLocation(), diag::note_nullability_here) 5831 << DiagNullabilityKind(*existingNullability, false); 5832 } 5833 } 5834 } 5835 5836 return true; 5837 } 5838 } 5839 5840 // If this definitely isn't a pointer type, reject the specifier. 5841 if (!desugared->canHaveNullability()) { 5842 Diag(nullabilityLoc, diag::err_nullability_nonpointer) 5843 << DiagNullabilityKind(nullability, isContextSensitive) << type; 5844 return true; 5845 } 5846 5847 // For the context-sensitive keywords/Objective-C property 5848 // attributes, require that the type be a single-level pointer. 5849 if (isContextSensitive) { 5850 // Make sure that the pointee isn't itself a pointer type. 5851 QualType pointeeType = desugared->getPointeeType(); 5852 if (pointeeType->isAnyPointerType() || 5853 pointeeType->isObjCObjectPointerType() || 5854 pointeeType->isMemberPointerType()) { 5855 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) 5856 << DiagNullabilityKind(nullability, true) 5857 << type; 5858 Diag(nullabilityLoc, diag::note_nullability_type_specifier) 5859 << DiagNullabilityKind(nullability, false) 5860 << type 5861 << FixItHint::CreateReplacement(nullabilityLoc, 5862 getNullabilitySpelling(nullability)); 5863 return true; 5864 } 5865 } 5866 5867 // Form the attributed type. 5868 type = Context.getAttributedType( 5869 AttributedType::getNullabilityAttrKind(nullability), type, type); 5870 return false; 5871 } 5872 5873 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) { 5874 // Find out if it's an Objective-C object or object pointer type; 5875 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); 5876 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() 5877 : type->getAs<ObjCObjectType>(); 5878 5879 // If not, we can't apply __kindof. 5880 if (!objType) { 5881 // FIXME: Handle dependent types that aren't yet object types. 5882 Diag(loc, diag::err_objc_kindof_nonobject) 5883 << type; 5884 return true; 5885 } 5886 5887 // Rebuild the "equivalent" type, which pushes __kindof down into 5888 // the object type. 5889 QualType equivType = Context.getObjCObjectType(objType->getBaseType(), 5890 objType->getTypeArgsAsWritten(), 5891 objType->getProtocols(), 5892 /*isKindOf=*/true); 5893 5894 // If we started with an object pointer type, rebuild it. 5895 if (ptrType) { 5896 equivType = Context.getObjCObjectPointerType(equivType); 5897 if (auto nullability = type->getNullability(Context)) { 5898 auto attrKind = AttributedType::getNullabilityAttrKind(*nullability); 5899 equivType = Context.getAttributedType(attrKind, equivType, equivType); 5900 } 5901 } 5902 5903 // Build the attributed type to record where __kindof occurred. 5904 type = Context.getAttributedType(AttributedType::attr_objc_kindof, 5905 type, 5906 equivType); 5907 5908 return false; 5909 } 5910 5911 /// Map a nullability attribute kind to a nullability kind. 5912 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) { 5913 switch (kind) { 5914 case AttributeList::AT_TypeNonNull: 5915 return NullabilityKind::NonNull; 5916 5917 case AttributeList::AT_TypeNullable: 5918 return NullabilityKind::Nullable; 5919 5920 case AttributeList::AT_TypeNullUnspecified: 5921 return NullabilityKind::Unspecified; 5922 5923 default: 5924 llvm_unreachable("not a nullability attribute kind"); 5925 } 5926 } 5927 5928 /// Distribute a nullability type attribute that cannot be applied to 5929 /// the type specifier to a pointer, block pointer, or member pointer 5930 /// declarator, complaining if necessary. 5931 /// 5932 /// \returns true if the nullability annotation was distributed, false 5933 /// otherwise. 5934 static bool distributeNullabilityTypeAttr(TypeProcessingState &state, 5935 QualType type, 5936 AttributeList &attr) { 5937 Declarator &declarator = state.getDeclarator(); 5938 5939 /// Attempt to move the attribute to the specified chunk. 5940 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { 5941 // If there is already a nullability attribute there, don't add 5942 // one. 5943 if (hasNullabilityAttr(chunk.getAttrListRef())) 5944 return false; 5945 5946 // Complain about the nullability qualifier being in the wrong 5947 // place. 5948 enum { 5949 PK_Pointer, 5950 PK_BlockPointer, 5951 PK_MemberPointer, 5952 PK_FunctionPointer, 5953 PK_MemberFunctionPointer, 5954 } pointerKind 5955 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer 5956 : PK_Pointer) 5957 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer 5958 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; 5959 5960 auto diag = state.getSema().Diag(attr.getLoc(), 5961 diag::warn_nullability_declspec) 5962 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), 5963 attr.isContextSensitiveKeywordAttribute()) 5964 << type 5965 << static_cast<unsigned>(pointerKind); 5966 5967 // FIXME: MemberPointer chunks don't carry the location of the *. 5968 if (chunk.Kind != DeclaratorChunk::MemberPointer) { 5969 diag << FixItHint::CreateRemoval(attr.getLoc()) 5970 << FixItHint::CreateInsertion( 5971 state.getSema().getPreprocessor() 5972 .getLocForEndOfToken(chunk.Loc), 5973 " " + attr.getName()->getName().str() + " "); 5974 } 5975 5976 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 5977 chunk.getAttrListRef()); 5978 return true; 5979 }; 5980 5981 // Move it to the outermost pointer, member pointer, or block 5982 // pointer declarator. 5983 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 5984 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 5985 switch (chunk.Kind) { 5986 case DeclaratorChunk::Pointer: 5987 case DeclaratorChunk::BlockPointer: 5988 case DeclaratorChunk::MemberPointer: 5989 return moveToChunk(chunk, false); 5990 5991 case DeclaratorChunk::Paren: 5992 case DeclaratorChunk::Array: 5993 continue; 5994 5995 case DeclaratorChunk::Function: 5996 // Try to move past the return type to a function/block/member 5997 // function pointer. 5998 if (DeclaratorChunk *dest = maybeMovePastReturnType( 5999 declarator, i, 6000 /*onlyBlockPointers=*/false)) { 6001 return moveToChunk(*dest, true); 6002 } 6003 6004 return false; 6005 6006 // Don't walk through these. 6007 case DeclaratorChunk::Reference: 6008 case DeclaratorChunk::Pipe: 6009 return false; 6010 } 6011 } 6012 6013 return false; 6014 } 6015 6016 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) { 6017 assert(!Attr.isInvalid()); 6018 switch (Attr.getKind()) { 6019 default: 6020 llvm_unreachable("not a calling convention attribute"); 6021 case AttributeList::AT_CDecl: 6022 return AttributedType::attr_cdecl; 6023 case AttributeList::AT_FastCall: 6024 return AttributedType::attr_fastcall; 6025 case AttributeList::AT_StdCall: 6026 return AttributedType::attr_stdcall; 6027 case AttributeList::AT_ThisCall: 6028 return AttributedType::attr_thiscall; 6029 case AttributeList::AT_Pascal: 6030 return AttributedType::attr_pascal; 6031 case AttributeList::AT_SwiftCall: 6032 return AttributedType::attr_swiftcall; 6033 case AttributeList::AT_VectorCall: 6034 return AttributedType::attr_vectorcall; 6035 case AttributeList::AT_Pcs: { 6036 // The attribute may have had a fixit applied where we treated an 6037 // identifier as a string literal. The contents of the string are valid, 6038 // but the form may not be. 6039 StringRef Str; 6040 if (Attr.isArgExpr(0)) 6041 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); 6042 else 6043 Str = Attr.getArgAsIdent(0)->Ident->getName(); 6044 return llvm::StringSwitch<AttributedType::Kind>(Str) 6045 .Case("aapcs", AttributedType::attr_pcs) 6046 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp); 6047 } 6048 case AttributeList::AT_IntelOclBicc: 6049 return AttributedType::attr_inteloclbicc; 6050 case AttributeList::AT_MSABI: 6051 return AttributedType::attr_ms_abi; 6052 case AttributeList::AT_SysVABI: 6053 return AttributedType::attr_sysv_abi; 6054 case AttributeList::AT_PreserveMost: 6055 return AttributedType::attr_preserve_most; 6056 case AttributeList::AT_PreserveAll: 6057 return AttributedType::attr_preserve_all; 6058 } 6059 llvm_unreachable("unexpected attribute kind!"); 6060 } 6061 6062 /// Process an individual function attribute. Returns true to 6063 /// indicate that the attribute was handled, false if it wasn't. 6064 static bool handleFunctionTypeAttr(TypeProcessingState &state, 6065 AttributeList &attr, 6066 QualType &type) { 6067 Sema &S = state.getSema(); 6068 6069 FunctionTypeUnwrapper unwrapped(S, type); 6070 6071 if (attr.getKind() == AttributeList::AT_NoReturn) { 6072 if (S.CheckNoReturnAttr(attr)) 6073 return true; 6074 6075 // Delay if this is not a function type. 6076 if (!unwrapped.isFunctionType()) 6077 return false; 6078 6079 // Otherwise we can process right away. 6080 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 6081 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6082 return true; 6083 } 6084 6085 // ns_returns_retained is not always a type attribute, but if we got 6086 // here, we're treating it as one right now. 6087 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) { 6088 assert(S.getLangOpts().ObjCAutoRefCount && 6089 "ns_returns_retained treated as type attribute in non-ARC"); 6090 if (attr.getNumArgs()) return true; 6091 6092 // Delay if this is not a function type. 6093 if (!unwrapped.isFunctionType()) 6094 return false; 6095 6096 FunctionType::ExtInfo EI 6097 = unwrapped.get()->getExtInfo().withProducesResult(true); 6098 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6099 return true; 6100 } 6101 6102 if (attr.getKind() == AttributeList::AT_Regparm) { 6103 unsigned value; 6104 if (S.CheckRegparmAttr(attr, value)) 6105 return true; 6106 6107 // Delay if this is not a function type. 6108 if (!unwrapped.isFunctionType()) 6109 return false; 6110 6111 // Diagnose regparm with fastcall. 6112 const FunctionType *fn = unwrapped.get(); 6113 CallingConv CC = fn->getCallConv(); 6114 if (CC == CC_X86FastCall) { 6115 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6116 << FunctionType::getNameForCallConv(CC) 6117 << "regparm"; 6118 attr.setInvalid(); 6119 return true; 6120 } 6121 6122 FunctionType::ExtInfo EI = 6123 unwrapped.get()->getExtInfo().withRegParm(value); 6124 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6125 return true; 6126 } 6127 6128 // Delay if the type didn't work out to a function. 6129 if (!unwrapped.isFunctionType()) return false; 6130 6131 // Otherwise, a calling convention. 6132 CallingConv CC; 6133 if (S.CheckCallingConvAttr(attr, CC)) 6134 return true; 6135 6136 const FunctionType *fn = unwrapped.get(); 6137 CallingConv CCOld = fn->getCallConv(); 6138 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr); 6139 6140 if (CCOld != CC) { 6141 // Error out on when there's already an attribute on the type 6142 // and the CCs don't match. 6143 const AttributedType *AT = S.getCallingConvAttributedType(type); 6144 if (AT && AT->getAttrKind() != CCAttrKind) { 6145 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6146 << FunctionType::getNameForCallConv(CC) 6147 << FunctionType::getNameForCallConv(CCOld); 6148 attr.setInvalid(); 6149 return true; 6150 } 6151 } 6152 6153 // Diagnose use of variadic functions with calling conventions that 6154 // don't support them (e.g. because they're callee-cleanup). 6155 // We delay warning about this on unprototyped function declarations 6156 // until after redeclaration checking, just in case we pick up a 6157 // prototype that way. And apparently we also "delay" warning about 6158 // unprototyped function types in general, despite not necessarily having 6159 // much ability to diagnose it later. 6160 if (!supportsVariadicCall(CC)) { 6161 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); 6162 if (FnP && FnP->isVariadic()) { 6163 unsigned DiagID = diag::err_cconv_varargs; 6164 6165 // stdcall and fastcall are ignored with a warning for GCC and MS 6166 // compatibility. 6167 bool IsInvalid = true; 6168 if (CC == CC_X86StdCall || CC == CC_X86FastCall) { 6169 DiagID = diag::warn_cconv_varargs; 6170 IsInvalid = false; 6171 } 6172 6173 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC); 6174 if (IsInvalid) attr.setInvalid(); 6175 return true; 6176 } 6177 } 6178 6179 // Also diagnose fastcall with regparm. 6180 if (CC == CC_X86FastCall && fn->getHasRegParm()) { 6181 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6182 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); 6183 attr.setInvalid(); 6184 return true; 6185 } 6186 6187 // Modify the CC from the wrapped function type, wrap it all back, and then 6188 // wrap the whole thing in an AttributedType as written. The modified type 6189 // might have a different CC if we ignored the attribute. 6190 QualType Equivalent; 6191 if (CCOld == CC) { 6192 Equivalent = type; 6193 } else { 6194 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 6195 Equivalent = 6196 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6197 } 6198 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent); 6199 return true; 6200 } 6201 6202 bool Sema::hasExplicitCallingConv(QualType &T) { 6203 QualType R = T.IgnoreParens(); 6204 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) { 6205 if (AT->isCallingConv()) 6206 return true; 6207 R = AT->getModifiedType().IgnoreParens(); 6208 } 6209 return false; 6210 } 6211 6212 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, 6213 SourceLocation Loc) { 6214 FunctionTypeUnwrapper Unwrapped(*this, T); 6215 const FunctionType *FT = Unwrapped.get(); 6216 bool IsVariadic = (isa<FunctionProtoType>(FT) && 6217 cast<FunctionProtoType>(FT)->isVariadic()); 6218 CallingConv CurCC = FT->getCallConv(); 6219 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); 6220 6221 if (CurCC == ToCC) 6222 return; 6223 6224 // MS compiler ignores explicit calling convention attributes on structors. We 6225 // should do the same. 6226 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { 6227 // Issue a warning on ignored calling convention -- except of __stdcall. 6228 // Again, this is what MS compiler does. 6229 if (CurCC != CC_X86StdCall) 6230 Diag(Loc, diag::warn_cconv_structors) 6231 << FunctionType::getNameForCallConv(CurCC); 6232 // Default adjustment. 6233 } else { 6234 // Only adjust types with the default convention. For example, on Windows 6235 // we should adjust a __cdecl type to __thiscall for instance methods, and a 6236 // __thiscall type to __cdecl for static methods. 6237 CallingConv DefaultCC = 6238 Context.getDefaultCallingConvention(IsVariadic, IsStatic); 6239 6240 if (CurCC != DefaultCC || DefaultCC == ToCC) 6241 return; 6242 6243 if (hasExplicitCallingConv(T)) 6244 return; 6245 } 6246 6247 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); 6248 QualType Wrapped = Unwrapped.wrap(*this, FT); 6249 T = Context.getAdjustedType(T, Wrapped); 6250 } 6251 6252 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 6253 /// and float scalars, although arrays, pointers, and function return values are 6254 /// allowed in conjunction with this construct. Aggregates with this attribute 6255 /// are invalid, even if they are of the same size as a corresponding scalar. 6256 /// The raw attribute should contain precisely 1 argument, the vector size for 6257 /// the variable, measured in bytes. If curType and rawAttr are well formed, 6258 /// this routine will return a new vector type. 6259 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 6260 Sema &S) { 6261 // Check the attribute arguments. 6262 if (Attr.getNumArgs() != 1) { 6263 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6264 << Attr.getName() << 1; 6265 Attr.setInvalid(); 6266 return; 6267 } 6268 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 6269 llvm::APSInt vecSize(32); 6270 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 6271 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 6272 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 6273 << Attr.getName() << AANT_ArgumentIntegerConstant 6274 << sizeExpr->getSourceRange(); 6275 Attr.setInvalid(); 6276 return; 6277 } 6278 // The base type must be integer (not Boolean or enumeration) or float, and 6279 // can't already be a vector. 6280 if (!CurType->isBuiltinType() || CurType->isBooleanType() || 6281 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) { 6282 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 6283 Attr.setInvalid(); 6284 return; 6285 } 6286 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 6287 // vecSize is specified in bytes - convert to bits. 6288 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 6289 6290 // the vector size needs to be an integral multiple of the type size. 6291 if (vectorSize % typeSize) { 6292 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 6293 << sizeExpr->getSourceRange(); 6294 Attr.setInvalid(); 6295 return; 6296 } 6297 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) { 6298 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large) 6299 << sizeExpr->getSourceRange(); 6300 Attr.setInvalid(); 6301 return; 6302 } 6303 if (vectorSize == 0) { 6304 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 6305 << sizeExpr->getSourceRange(); 6306 Attr.setInvalid(); 6307 return; 6308 } 6309 6310 // Success! Instantiate the vector type, the number of elements is > 0, and 6311 // not required to be a power of 2, unlike GCC. 6312 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 6313 VectorType::GenericVector); 6314 } 6315 6316 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on 6317 /// a type. 6318 static void HandleExtVectorTypeAttr(QualType &CurType, 6319 const AttributeList &Attr, 6320 Sema &S) { 6321 // check the attribute arguments. 6322 if (Attr.getNumArgs() != 1) { 6323 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6324 << Attr.getName() << 1; 6325 return; 6326 } 6327 6328 Expr *sizeExpr; 6329 6330 // Special case where the argument is a template id. 6331 if (Attr.isArgIdent(0)) { 6332 CXXScopeSpec SS; 6333 SourceLocation TemplateKWLoc; 6334 UnqualifiedId id; 6335 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); 6336 6337 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 6338 id, false, false); 6339 if (Size.isInvalid()) 6340 return; 6341 6342 sizeExpr = Size.get(); 6343 } else { 6344 sizeExpr = Attr.getArgAsExpr(0); 6345 } 6346 6347 // Create the vector type. 6348 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 6349 if (!T.isNull()) 6350 CurType = T; 6351 } 6352 6353 static bool isPermittedNeonBaseType(QualType &Ty, 6354 VectorType::VectorKind VecKind, Sema &S) { 6355 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 6356 if (!BTy) 6357 return false; 6358 6359 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 6360 6361 // Signed poly is mathematically wrong, but has been baked into some ABIs by 6362 // now. 6363 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || 6364 Triple.getArch() == llvm::Triple::aarch64_be; 6365 if (VecKind == VectorType::NeonPolyVector) { 6366 if (IsPolyUnsigned) { 6367 // AArch64 polynomial vectors are unsigned and support poly64. 6368 return BTy->getKind() == BuiltinType::UChar || 6369 BTy->getKind() == BuiltinType::UShort || 6370 BTy->getKind() == BuiltinType::ULong || 6371 BTy->getKind() == BuiltinType::ULongLong; 6372 } else { 6373 // AArch32 polynomial vector are signed. 6374 return BTy->getKind() == BuiltinType::SChar || 6375 BTy->getKind() == BuiltinType::Short; 6376 } 6377 } 6378 6379 // Non-polynomial vector types: the usual suspects are allowed, as well as 6380 // float64_t on AArch64. 6381 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 || 6382 Triple.getArch() == llvm::Triple::aarch64_be; 6383 6384 if (Is64Bit && BTy->getKind() == BuiltinType::Double) 6385 return true; 6386 6387 return BTy->getKind() == BuiltinType::SChar || 6388 BTy->getKind() == BuiltinType::UChar || 6389 BTy->getKind() == BuiltinType::Short || 6390 BTy->getKind() == BuiltinType::UShort || 6391 BTy->getKind() == BuiltinType::Int || 6392 BTy->getKind() == BuiltinType::UInt || 6393 BTy->getKind() == BuiltinType::Long || 6394 BTy->getKind() == BuiltinType::ULong || 6395 BTy->getKind() == BuiltinType::LongLong || 6396 BTy->getKind() == BuiltinType::ULongLong || 6397 BTy->getKind() == BuiltinType::Float || 6398 BTy->getKind() == BuiltinType::Half; 6399 } 6400 6401 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 6402 /// "neon_polyvector_type" attributes are used to create vector types that 6403 /// are mangled according to ARM's ABI. Otherwise, these types are identical 6404 /// to those created with the "vector_size" attribute. Unlike "vector_size" 6405 /// the argument to these Neon attributes is the number of vector elements, 6406 /// not the vector size in bytes. The vector width and element type must 6407 /// match one of the standard Neon vector types. 6408 static void HandleNeonVectorTypeAttr(QualType& CurType, 6409 const AttributeList &Attr, Sema &S, 6410 VectorType::VectorKind VecKind) { 6411 // Target must have NEON 6412 if (!S.Context.getTargetInfo().hasFeature("neon")) { 6413 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName(); 6414 Attr.setInvalid(); 6415 return; 6416 } 6417 // Check the attribute arguments. 6418 if (Attr.getNumArgs() != 1) { 6419 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6420 << Attr.getName() << 1; 6421 Attr.setInvalid(); 6422 return; 6423 } 6424 // The number of elements must be an ICE. 6425 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 6426 llvm::APSInt numEltsInt(32); 6427 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 6428 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 6429 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 6430 << Attr.getName() << AANT_ArgumentIntegerConstant 6431 << numEltsExpr->getSourceRange(); 6432 Attr.setInvalid(); 6433 return; 6434 } 6435 // Only certain element types are supported for Neon vectors. 6436 if (!isPermittedNeonBaseType(CurType, VecKind, S)) { 6437 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 6438 Attr.setInvalid(); 6439 return; 6440 } 6441 6442 // The total size of the vector must be 64 or 128 bits. 6443 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 6444 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 6445 unsigned vecSize = typeSize * numElts; 6446 if (vecSize != 64 && vecSize != 128) { 6447 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 6448 Attr.setInvalid(); 6449 return; 6450 } 6451 6452 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 6453 } 6454 6455 /// Handle OpenCL Access Qualifier Attribute. 6456 static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr, 6457 Sema &S) { 6458 // OpenCL v2.0 s6.6 - Access qualifier can used only for image and pipe type. 6459 if (!(CurType->isImageType() || CurType->isPipeType())) { 6460 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); 6461 Attr.setInvalid(); 6462 return; 6463 } 6464 } 6465 6466 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 6467 TypeAttrLocation TAL, AttributeList *attrs) { 6468 // Scan through and apply attributes to this type where it makes sense. Some 6469 // attributes (such as __address_space__, __vector_size__, etc) apply to the 6470 // type, but others can be present in the type specifiers even though they 6471 // apply to the decl. Here we apply type attributes and ignore the rest. 6472 6473 bool hasOpenCLAddressSpace = false; 6474 while (attrs) { 6475 AttributeList &attr = *attrs; 6476 attrs = attr.getNext(); // reset to the next here due to early loop continue 6477 // stmts 6478 6479 // Skip attributes that were marked to be invalid. 6480 if (attr.isInvalid()) 6481 continue; 6482 6483 if (attr.isCXX11Attribute()) { 6484 // [[gnu::...]] attributes are treated as declaration attributes, so may 6485 // not appertain to a DeclaratorChunk, even if we handle them as type 6486 // attributes. 6487 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) { 6488 if (TAL == TAL_DeclChunk) { 6489 state.getSema().Diag(attr.getLoc(), 6490 diag::warn_cxx11_gnu_attribute_on_type) 6491 << attr.getName(); 6492 continue; 6493 } 6494 } else if (TAL != TAL_DeclChunk) { 6495 // Otherwise, only consider type processing for a C++11 attribute if 6496 // it's actually been applied to a type. 6497 continue; 6498 } 6499 } 6500 6501 // If this is an attribute we can handle, do so now, 6502 // otherwise, add it to the FnAttrs list for rechaining. 6503 switch (attr.getKind()) { 6504 default: 6505 // A C++11 attribute on a declarator chunk must appertain to a type. 6506 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { 6507 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 6508 << attr.getName(); 6509 attr.setUsedAsTypeAttr(); 6510 } 6511 break; 6512 6513 case AttributeList::UnknownAttribute: 6514 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) 6515 state.getSema().Diag(attr.getLoc(), 6516 diag::warn_unknown_attribute_ignored) 6517 << attr.getName(); 6518 break; 6519 6520 case AttributeList::IgnoredAttribute: 6521 break; 6522 6523 case AttributeList::AT_MayAlias: 6524 // FIXME: This attribute needs to actually be handled, but if we ignore 6525 // it it breaks large amounts of Linux software. 6526 attr.setUsedAsTypeAttr(); 6527 break; 6528 case AttributeList::AT_OpenCLPrivateAddressSpace: 6529 case AttributeList::AT_OpenCLGlobalAddressSpace: 6530 case AttributeList::AT_OpenCLLocalAddressSpace: 6531 case AttributeList::AT_OpenCLConstantAddressSpace: 6532 case AttributeList::AT_OpenCLGenericAddressSpace: 6533 case AttributeList::AT_AddressSpace: 6534 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 6535 attr.setUsedAsTypeAttr(); 6536 hasOpenCLAddressSpace = true; 6537 break; 6538 OBJC_POINTER_TYPE_ATTRS_CASELIST: 6539 if (!handleObjCPointerTypeAttr(state, attr, type)) 6540 distributeObjCPointerTypeAttr(state, attr, type); 6541 attr.setUsedAsTypeAttr(); 6542 break; 6543 case AttributeList::AT_VectorSize: 6544 HandleVectorSizeAttr(type, attr, state.getSema()); 6545 attr.setUsedAsTypeAttr(); 6546 break; 6547 case AttributeList::AT_ExtVectorType: 6548 HandleExtVectorTypeAttr(type, attr, state.getSema()); 6549 attr.setUsedAsTypeAttr(); 6550 break; 6551 case AttributeList::AT_NeonVectorType: 6552 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 6553 VectorType::NeonVector); 6554 attr.setUsedAsTypeAttr(); 6555 break; 6556 case AttributeList::AT_NeonPolyVectorType: 6557 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 6558 VectorType::NeonPolyVector); 6559 attr.setUsedAsTypeAttr(); 6560 break; 6561 case AttributeList::AT_OpenCLAccess: 6562 HandleOpenCLAccessAttr(type, attr, state.getSema()); 6563 attr.setUsedAsTypeAttr(); 6564 break; 6565 6566 MS_TYPE_ATTRS_CASELIST: 6567 if (!handleMSPointerTypeQualifierAttr(state, attr, type)) 6568 attr.setUsedAsTypeAttr(); 6569 break; 6570 6571 6572 NULLABILITY_TYPE_ATTRS_CASELIST: 6573 // Either add nullability here or try to distribute it. We 6574 // don't want to distribute the nullability specifier past any 6575 // dependent type, because that complicates the user model. 6576 if (type->canHaveNullability() || type->isDependentType() || 6577 !distributeNullabilityTypeAttr(state, type, attr)) { 6578 if (state.getSema().checkNullabilityTypeSpecifier( 6579 type, 6580 mapNullabilityAttrKind(attr.getKind()), 6581 attr.getLoc(), 6582 attr.isContextSensitiveKeywordAttribute())) { 6583 attr.setInvalid(); 6584 } 6585 6586 attr.setUsedAsTypeAttr(); 6587 } 6588 break; 6589 6590 case AttributeList::AT_ObjCKindOf: 6591 // '__kindof' must be part of the decl-specifiers. 6592 switch (TAL) { 6593 case TAL_DeclSpec: 6594 break; 6595 6596 case TAL_DeclChunk: 6597 case TAL_DeclName: 6598 state.getSema().Diag(attr.getLoc(), 6599 diag::err_objc_kindof_wrong_position) 6600 << FixItHint::CreateRemoval(attr.getLoc()) 6601 << FixItHint::CreateInsertion( 6602 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof "); 6603 break; 6604 } 6605 6606 // Apply it regardless. 6607 if (state.getSema().checkObjCKindOfType(type, attr.getLoc())) 6608 attr.setInvalid(); 6609 attr.setUsedAsTypeAttr(); 6610 break; 6611 6612 case AttributeList::AT_NSReturnsRetained: 6613 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 6614 break; 6615 // fallthrough into the function attrs 6616 6617 FUNCTION_TYPE_ATTRS_CASELIST: 6618 attr.setUsedAsTypeAttr(); 6619 6620 // Never process function type attributes as part of the 6621 // declaration-specifiers. 6622 if (TAL == TAL_DeclSpec) 6623 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 6624 6625 // Otherwise, handle the possible delays. 6626 else if (!handleFunctionTypeAttr(state, attr, type)) 6627 distributeFunctionTypeAttr(state, attr, type); 6628 break; 6629 } 6630 } 6631 6632 // If address space is not set, OpenCL 2.0 defines non private default 6633 // address spaces for some cases: 6634 // OpenCL 2.0, section 6.5: 6635 // The address space for a variable at program scope or a static variable 6636 // inside a function can either be __global or __constant, but defaults to 6637 // __global if not specified. 6638 // (...) 6639 // Pointers that are declared without pointing to a named address space point 6640 // to the generic address space. 6641 if (state.getSema().getLangOpts().OpenCLVersion >= 200 && 6642 !hasOpenCLAddressSpace && type.getAddressSpace() == 0 && 6643 (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) { 6644 Declarator &D = state.getDeclarator(); 6645 if (state.getCurrentChunkIndex() > 0 && 6646 D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind == 6647 DeclaratorChunk::Pointer) { 6648 type = state.getSema().Context.getAddrSpaceQualType( 6649 type, LangAS::opencl_generic); 6650 } else if (state.getCurrentChunkIndex() == 0 && 6651 D.getContext() == Declarator::FileContext && 6652 !D.isFunctionDeclarator() && !D.isFunctionDefinition() && 6653 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6654 !type->isSamplerT()) 6655 type = state.getSema().Context.getAddrSpaceQualType( 6656 type, LangAS::opencl_global); 6657 else if (state.getCurrentChunkIndex() == 0 && 6658 D.getContext() == Declarator::BlockContext && 6659 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) 6660 type = state.getSema().Context.getAddrSpaceQualType( 6661 type, LangAS::opencl_global); 6662 } 6663 } 6664 6665 void Sema::completeExprArrayBound(Expr *E) { 6666 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 6667 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 6668 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { 6669 SourceLocation PointOfInstantiation = E->getExprLoc(); 6670 6671 if (MemberSpecializationInfo *MSInfo = 6672 Var->getMemberSpecializationInfo()) { 6673 // If we don't already have a point of instantiation, this is it. 6674 if (MSInfo->getPointOfInstantiation().isInvalid()) { 6675 MSInfo->setPointOfInstantiation(PointOfInstantiation); 6676 6677 // This is a modification of an existing AST node. Notify 6678 // listeners. 6679 if (ASTMutationListener *L = getASTMutationListener()) 6680 L->StaticDataMemberInstantiated(Var); 6681 } 6682 } else { 6683 VarTemplateSpecializationDecl *VarSpec = 6684 cast<VarTemplateSpecializationDecl>(Var); 6685 if (VarSpec->getPointOfInstantiation().isInvalid()) 6686 VarSpec->setPointOfInstantiation(PointOfInstantiation); 6687 } 6688 6689 InstantiateVariableDefinition(PointOfInstantiation, Var); 6690 6691 // Update the type to the newly instantiated definition's type both 6692 // here and within the expression. 6693 if (VarDecl *Def = Var->getDefinition()) { 6694 DRE->setDecl(Def); 6695 QualType T = Def->getType(); 6696 DRE->setType(T); 6697 // FIXME: Update the type on all intervening expressions. 6698 E->setType(T); 6699 } 6700 6701 // We still go on to try to complete the type independently, as it 6702 // may also require instantiations or diagnostics if it remains 6703 // incomplete. 6704 } 6705 } 6706 } 6707 } 6708 6709 /// \brief Ensure that the type of the given expression is complete. 6710 /// 6711 /// This routine checks whether the expression \p E has a complete type. If the 6712 /// expression refers to an instantiable construct, that instantiation is 6713 /// performed as needed to complete its type. Furthermore 6714 /// Sema::RequireCompleteType is called for the expression's type (or in the 6715 /// case of a reference type, the referred-to type). 6716 /// 6717 /// \param E The expression whose type is required to be complete. 6718 /// \param Diagnoser The object that will emit a diagnostic if the type is 6719 /// incomplete. 6720 /// 6721 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 6722 /// otherwise. 6723 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) { 6724 QualType T = E->getType(); 6725 6726 // Incomplete array types may be completed by the initializer attached to 6727 // their definitions. For static data members of class templates and for 6728 // variable templates, we need to instantiate the definition to get this 6729 // initializer and complete the type. 6730 if (T->isIncompleteArrayType()) { 6731 completeExprArrayBound(E); 6732 T = E->getType(); 6733 } 6734 6735 // FIXME: Are there other cases which require instantiating something other 6736 // than the type to complete the type of an expression? 6737 6738 return RequireCompleteType(E->getExprLoc(), T, Diagnoser); 6739 } 6740 6741 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 6742 BoundTypeDiagnoser<> Diagnoser(DiagID); 6743 return RequireCompleteExprType(E, Diagnoser); 6744 } 6745 6746 /// @brief Ensure that the type T is a complete type. 6747 /// 6748 /// This routine checks whether the type @p T is complete in any 6749 /// context where a complete type is required. If @p T is a complete 6750 /// type, returns false. If @p T is a class template specialization, 6751 /// this routine then attempts to perform class template 6752 /// instantiation. If instantiation fails, or if @p T is incomplete 6753 /// and cannot be completed, issues the diagnostic @p diag (giving it 6754 /// the type @p T) and returns true. 6755 /// 6756 /// @param Loc The location in the source that the incomplete type 6757 /// diagnostic should refer to. 6758 /// 6759 /// @param T The type that this routine is examining for completeness. 6760 /// 6761 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 6762 /// @c false otherwise. 6763 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 6764 TypeDiagnoser &Diagnoser) { 6765 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser)) 6766 return true; 6767 if (const TagType *Tag = T->getAs<TagType>()) { 6768 if (!Tag->getDecl()->isCompleteDefinitionRequired()) { 6769 Tag->getDecl()->setCompleteDefinitionRequired(); 6770 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); 6771 } 6772 } 6773 return false; 6774 } 6775 6776 /// \brief Determine whether there is any declaration of \p D that was ever a 6777 /// definition (perhaps before module merging) and is currently visible. 6778 /// \param D The definition of the entity. 6779 /// \param Suggested Filled in with the declaration that should be made visible 6780 /// in order to provide a definition of this entity. 6781 /// \param OnlyNeedComplete If \c true, we only need the type to be complete, 6782 /// not defined. This only matters for enums with a fixed underlying 6783 /// type, since in all other cases, a type is complete if and only if it 6784 /// is defined. 6785 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 6786 bool OnlyNeedComplete) { 6787 // Easy case: if we don't have modules, all declarations are visible. 6788 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) 6789 return true; 6790 6791 // If this definition was instantiated from a template, map back to the 6792 // pattern from which it was instantiated. 6793 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { 6794 // We're in the middle of defining it; this definition should be treated 6795 // as visible. 6796 return true; 6797 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 6798 if (auto *Pattern = RD->getTemplateInstantiationPattern()) 6799 RD = Pattern; 6800 D = RD->getDefinition(); 6801 } else if (auto *ED = dyn_cast<EnumDecl>(D)) { 6802 while (auto *NewED = ED->getInstantiatedFromMemberEnum()) 6803 ED = NewED; 6804 if (OnlyNeedComplete && ED->isFixed()) { 6805 // If the enum has a fixed underlying type, and we're only looking for a 6806 // complete type (not a definition), any visible declaration of it will 6807 // do. 6808 *Suggested = nullptr; 6809 for (auto *Redecl : ED->redecls()) { 6810 if (isVisible(Redecl)) 6811 return true; 6812 if (Redecl->isThisDeclarationADefinition() || 6813 (Redecl->isCanonicalDecl() && !*Suggested)) 6814 *Suggested = Redecl; 6815 } 6816 return false; 6817 } 6818 D = ED->getDefinition(); 6819 } 6820 assert(D && "missing definition for pattern of instantiated definition"); 6821 6822 *Suggested = D; 6823 if (isVisible(D)) 6824 return true; 6825 6826 // The external source may have additional definitions of this type that are 6827 // visible, so complete the redeclaration chain now and ask again. 6828 if (auto *Source = Context.getExternalSource()) { 6829 Source->CompleteRedeclChain(D); 6830 return isVisible(D); 6831 } 6832 6833 return false; 6834 } 6835 6836 /// Locks in the inheritance model for the given class and all of its bases. 6837 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { 6838 RD = RD->getMostRecentDecl(); 6839 if (!RD->hasAttr<MSInheritanceAttr>()) { 6840 MSInheritanceAttr::Spelling IM; 6841 6842 switch (S.MSPointerToMemberRepresentationMethod) { 6843 case LangOptions::PPTMK_BestCase: 6844 IM = RD->calculateInheritanceModel(); 6845 break; 6846 case LangOptions::PPTMK_FullGeneralitySingleInheritance: 6847 IM = MSInheritanceAttr::Keyword_single_inheritance; 6848 break; 6849 case LangOptions::PPTMK_FullGeneralityMultipleInheritance: 6850 IM = MSInheritanceAttr::Keyword_multiple_inheritance; 6851 break; 6852 case LangOptions::PPTMK_FullGeneralityVirtualInheritance: 6853 IM = MSInheritanceAttr::Keyword_unspecified_inheritance; 6854 break; 6855 } 6856 6857 RD->addAttr(MSInheritanceAttr::CreateImplicit( 6858 S.getASTContext(), IM, 6859 /*BestCase=*/S.MSPointerToMemberRepresentationMethod == 6860 LangOptions::PPTMK_BestCase, 6861 S.ImplicitMSInheritanceAttrLoc.isValid() 6862 ? S.ImplicitMSInheritanceAttrLoc 6863 : RD->getSourceRange())); 6864 S.Consumer.AssignInheritanceModel(RD); 6865 } 6866 } 6867 6868 /// \brief The implementation of RequireCompleteType 6869 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 6870 TypeDiagnoser *Diagnoser) { 6871 // FIXME: Add this assertion to make sure we always get instantiation points. 6872 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 6873 // FIXME: Add this assertion to help us flush out problems with 6874 // checking for dependent types and type-dependent expressions. 6875 // 6876 // assert(!T->isDependentType() && 6877 // "Can't ask whether a dependent type is complete"); 6878 6879 // We lock in the inheritance model once somebody has asked us to ensure 6880 // that a pointer-to-member type is complete. 6881 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 6882 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { 6883 if (!MPTy->getClass()->isDependentType()) { 6884 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); 6885 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); 6886 } 6887 } 6888 } 6889 6890 // If we have a complete type, we're done. 6891 NamedDecl *Def = nullptr; 6892 if (!T->isIncompleteType(&Def)) { 6893 // If we know about the definition but it is not visible, complain. 6894 NamedDecl *SuggestedDef = nullptr; 6895 if (Def && 6896 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { 6897 // If the user is going to see an error here, recover by making the 6898 // definition visible. 6899 bool TreatAsComplete = Diagnoser && !isSFINAEContext(); 6900 if (Diagnoser) 6901 diagnoseMissingImport(Loc, SuggestedDef, /*NeedDefinition*/true, 6902 /*Recover*/TreatAsComplete); 6903 return !TreatAsComplete; 6904 } 6905 6906 return false; 6907 } 6908 6909 const TagType *Tag = T->getAs<TagType>(); 6910 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>(); 6911 6912 // If there's an unimported definition of this type in a module (for 6913 // instance, because we forward declared it, then imported the definition), 6914 // import that definition now. 6915 // 6916 // FIXME: What about other cases where an import extends a redeclaration 6917 // chain for a declaration that can be accessed through a mechanism other 6918 // than name lookup (eg, referenced in a template, or a variable whose type 6919 // could be completed by the module)? 6920 // 6921 // FIXME: Should we map through to the base array element type before 6922 // checking for a tag type? 6923 if (Tag || IFace) { 6924 NamedDecl *D = 6925 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl(); 6926 6927 // Avoid diagnosing invalid decls as incomplete. 6928 if (D->isInvalidDecl()) 6929 return true; 6930 6931 // Give the external AST source a chance to complete the type. 6932 if (auto *Source = Context.getExternalSource()) { 6933 if (Tag) 6934 Source->CompleteType(Tag->getDecl()); 6935 else 6936 Source->CompleteType(IFace->getDecl()); 6937 6938 // If the external source completed the type, go through the motions 6939 // again to ensure we're allowed to use the completed type. 6940 if (!T->isIncompleteType()) 6941 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 6942 } 6943 } 6944 6945 // If we have a class template specialization or a class member of a 6946 // class template specialization, or an array with known size of such, 6947 // try to instantiate it. 6948 QualType MaybeTemplate = T; 6949 while (const ConstantArrayType *Array 6950 = Context.getAsConstantArrayType(MaybeTemplate)) 6951 MaybeTemplate = Array->getElementType(); 6952 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 6953 bool Instantiated = false; 6954 bool Diagnosed = false; 6955 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 6956 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 6957 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 6958 Diagnosed = InstantiateClassTemplateSpecialization( 6959 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, 6960 /*Complain=*/Diagnoser); 6961 Instantiated = true; 6962 } 6963 } else if (CXXRecordDecl *Rec 6964 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 6965 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass(); 6966 if (!Rec->isBeingDefined() && Pattern) { 6967 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo(); 6968 assert(MSI && "Missing member specialization information?"); 6969 // This record was instantiated from a class within a template. 6970 if (MSI->getTemplateSpecializationKind() != 6971 TSK_ExplicitSpecialization) { 6972 Diagnosed = InstantiateClass(Loc, Rec, Pattern, 6973 getTemplateInstantiationArgs(Rec), 6974 TSK_ImplicitInstantiation, 6975 /*Complain=*/Diagnoser); 6976 Instantiated = true; 6977 } 6978 } 6979 } 6980 6981 if (Instantiated) { 6982 // Instantiate* might have already complained that the template is not 6983 // defined, if we asked it to. 6984 if (Diagnoser && Diagnosed) 6985 return true; 6986 // If we instantiated a definition, check that it's usable, even if 6987 // instantiation produced an error, so that repeated calls to this 6988 // function give consistent answers. 6989 if (!T->isIncompleteType()) 6990 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 6991 } 6992 } 6993 6994 if (!Diagnoser) 6995 return true; 6996 6997 // We have an incomplete type. Produce a diagnostic. 6998 if (Ident___float128 && 6999 T == Context.getTypeDeclType(Context.getFloat128StubType())) { 7000 Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128); 7001 return true; 7002 } 7003 7004 Diagnoser->diagnose(*this, Loc, T); 7005 7006 // If the type was a forward declaration of a class/struct/union 7007 // type, produce a note. 7008 if (Tag && !Tag->getDecl()->isInvalidDecl()) 7009 Diag(Tag->getDecl()->getLocation(), 7010 Tag->isBeingDefined() ? diag::note_type_being_defined 7011 : diag::note_forward_declaration) 7012 << QualType(Tag, 0); 7013 7014 // If the Objective-C class was a forward declaration, produce a note. 7015 if (IFace && !IFace->getDecl()->isInvalidDecl()) 7016 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class); 7017 7018 // If we have external information that we can use to suggest a fix, 7019 // produce a note. 7020 if (ExternalSource) 7021 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); 7022 7023 return true; 7024 } 7025 7026 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 7027 unsigned DiagID) { 7028 BoundTypeDiagnoser<> Diagnoser(DiagID); 7029 return RequireCompleteType(Loc, T, Diagnoser); 7030 } 7031 7032 /// \brief Get diagnostic %select index for tag kind for 7033 /// literal type diagnostic message. 7034 /// WARNING: Indexes apply to particular diagnostics only! 7035 /// 7036 /// \returns diagnostic %select index. 7037 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 7038 switch (Tag) { 7039 case TTK_Struct: return 0; 7040 case TTK_Interface: return 1; 7041 case TTK_Class: return 2; 7042 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 7043 } 7044 } 7045 7046 /// @brief Ensure that the type T is a literal type. 7047 /// 7048 /// This routine checks whether the type @p T is a literal type. If @p T is an 7049 /// incomplete type, an attempt is made to complete it. If @p T is a literal 7050 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 7051 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 7052 /// it the type @p T), along with notes explaining why the type is not a 7053 /// literal type, and returns true. 7054 /// 7055 /// @param Loc The location in the source that the non-literal type 7056 /// diagnostic should refer to. 7057 /// 7058 /// @param T The type that this routine is examining for literalness. 7059 /// 7060 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 7061 /// 7062 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 7063 /// @c false otherwise. 7064 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 7065 TypeDiagnoser &Diagnoser) { 7066 assert(!T->isDependentType() && "type should not be dependent"); 7067 7068 QualType ElemType = Context.getBaseElementType(T); 7069 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && 7070 T->isLiteralType(Context)) 7071 return false; 7072 7073 Diagnoser.diagnose(*this, Loc, T); 7074 7075 if (T->isVariableArrayType()) 7076 return true; 7077 7078 const RecordType *RT = ElemType->getAs<RecordType>(); 7079 if (!RT) 7080 return true; 7081 7082 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 7083 7084 // A partially-defined class type can't be a literal type, because a literal 7085 // class type must have a trivial destructor (which can't be checked until 7086 // the class definition is complete). 7087 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) 7088 return true; 7089 7090 // If the class has virtual base classes, then it's not an aggregate, and 7091 // cannot have any constexpr constructors or a trivial default constructor, 7092 // so is non-literal. This is better to diagnose than the resulting absence 7093 // of constexpr constructors. 7094 if (RD->getNumVBases()) { 7095 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 7096 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 7097 for (const auto &I : RD->vbases()) 7098 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here) 7099 << I.getSourceRange(); 7100 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 7101 !RD->hasTrivialDefaultConstructor()) { 7102 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 7103 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 7104 for (const auto &I : RD->bases()) { 7105 if (!I.getType()->isLiteralType(Context)) { 7106 Diag(I.getLocStart(), 7107 diag::note_non_literal_base_class) 7108 << RD << I.getType() << I.getSourceRange(); 7109 return true; 7110 } 7111 } 7112 for (const auto *I : RD->fields()) { 7113 if (!I->getType()->isLiteralType(Context) || 7114 I->getType().isVolatileQualified()) { 7115 Diag(I->getLocation(), diag::note_non_literal_field) 7116 << RD << I << I->getType() 7117 << I->getType().isVolatileQualified(); 7118 return true; 7119 } 7120 } 7121 } else if (!RD->hasTrivialDestructor()) { 7122 // All fields and bases are of literal types, so have trivial destructors. 7123 // If this class's destructor is non-trivial it must be user-declared. 7124 CXXDestructorDecl *Dtor = RD->getDestructor(); 7125 assert(Dtor && "class has literal fields and bases but no dtor?"); 7126 if (!Dtor) 7127 return true; 7128 7129 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 7130 diag::note_non_literal_user_provided_dtor : 7131 diag::note_non_literal_nontrivial_dtor) << RD; 7132 if (!Dtor->isUserProvided()) 7133 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true); 7134 } 7135 7136 return true; 7137 } 7138 7139 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 7140 BoundTypeDiagnoser<> Diagnoser(DiagID); 7141 return RequireLiteralType(Loc, T, Diagnoser); 7142 } 7143 7144 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 7145 /// and qualified by the nested-name-specifier contained in SS. 7146 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 7147 const CXXScopeSpec &SS, QualType T) { 7148 if (T.isNull()) 7149 return T; 7150 NestedNameSpecifier *NNS; 7151 if (SS.isValid()) 7152 NNS = SS.getScopeRep(); 7153 else { 7154 if (Keyword == ETK_None) 7155 return T; 7156 NNS = nullptr; 7157 } 7158 return Context.getElaboratedType(Keyword, NNS, T); 7159 } 7160 7161 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 7162 ExprResult ER = CheckPlaceholderExpr(E); 7163 if (ER.isInvalid()) return QualType(); 7164 E = ER.get(); 7165 7166 if (!getLangOpts().CPlusPlus && E->refersToBitField()) 7167 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; 7168 7169 if (!E->isTypeDependent()) { 7170 QualType T = E->getType(); 7171 if (const TagType *TT = T->getAs<TagType>()) 7172 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 7173 } 7174 return Context.getTypeOfExprType(E); 7175 } 7176 7177 /// getDecltypeForExpr - Given an expr, will return the decltype for 7178 /// that expression, according to the rules in C++11 7179 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 7180 static QualType getDecltypeForExpr(Sema &S, Expr *E) { 7181 if (E->isTypeDependent()) 7182 return S.Context.DependentTy; 7183 7184 // C++11 [dcl.type.simple]p4: 7185 // The type denoted by decltype(e) is defined as follows: 7186 // 7187 // - if e is an unparenthesized id-expression or an unparenthesized class 7188 // member access (5.2.5), decltype(e) is the type of the entity named 7189 // by e. If there is no such entity, or if e names a set of overloaded 7190 // functions, the program is ill-formed; 7191 // 7192 // We apply the same rules for Objective-C ivar and property references. 7193 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 7194 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 7195 return VD->getType(); 7196 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 7197 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 7198 return FD->getType(); 7199 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { 7200 return IR->getDecl()->getType(); 7201 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { 7202 if (PR->isExplicitProperty()) 7203 return PR->getExplicitProperty()->getType(); 7204 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { 7205 return PE->getType(); 7206 } 7207 7208 // C++11 [expr.lambda.prim]p18: 7209 // Every occurrence of decltype((x)) where x is a possibly 7210 // parenthesized id-expression that names an entity of automatic 7211 // storage duration is treated as if x were transformed into an 7212 // access to a corresponding data member of the closure type that 7213 // would have been declared if x were an odr-use of the denoted 7214 // entity. 7215 using namespace sema; 7216 if (S.getCurLambda()) { 7217 if (isa<ParenExpr>(E)) { 7218 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 7219 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 7220 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); 7221 if (!T.isNull()) 7222 return S.Context.getLValueReferenceType(T); 7223 } 7224 } 7225 } 7226 } 7227 7228 7229 // C++11 [dcl.type.simple]p4: 7230 // [...] 7231 QualType T = E->getType(); 7232 switch (E->getValueKind()) { 7233 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 7234 // type of e; 7235 case VK_XValue: T = S.Context.getRValueReferenceType(T); break; 7236 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 7237 // type of e; 7238 case VK_LValue: T = S.Context.getLValueReferenceType(T); break; 7239 // - otherwise, decltype(e) is the type of e. 7240 case VK_RValue: break; 7241 } 7242 7243 return T; 7244 } 7245 7246 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc, 7247 bool AsUnevaluated) { 7248 ExprResult ER = CheckPlaceholderExpr(E); 7249 if (ER.isInvalid()) return QualType(); 7250 E = ER.get(); 7251 7252 if (AsUnevaluated && ActiveTemplateInstantiations.empty() && 7253 E->HasSideEffects(Context, false)) { 7254 // The expression operand for decltype is in an unevaluated expression 7255 // context, so side effects could result in unintended consequences. 7256 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 7257 } 7258 7259 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); 7260 } 7261 7262 QualType Sema::BuildUnaryTransformType(QualType BaseType, 7263 UnaryTransformType::UTTKind UKind, 7264 SourceLocation Loc) { 7265 switch (UKind) { 7266 case UnaryTransformType::EnumUnderlyingType: 7267 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 7268 Diag(Loc, diag::err_only_enums_have_underlying_types); 7269 return QualType(); 7270 } else { 7271 QualType Underlying = BaseType; 7272 if (!BaseType->isDependentType()) { 7273 // The enum could be incomplete if we're parsing its definition or 7274 // recovering from an error. 7275 NamedDecl *FwdDecl = nullptr; 7276 if (BaseType->isIncompleteType(&FwdDecl)) { 7277 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; 7278 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; 7279 return QualType(); 7280 } 7281 7282 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 7283 assert(ED && "EnumType has no EnumDecl"); 7284 7285 DiagnoseUseOfDecl(ED, Loc); 7286 7287 Underlying = ED->getIntegerType(); 7288 assert(!Underlying.isNull()); 7289 } 7290 return Context.getUnaryTransformType(BaseType, Underlying, 7291 UnaryTransformType::EnumUnderlyingType); 7292 } 7293 } 7294 llvm_unreachable("unknown unary transform type"); 7295 } 7296 7297 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 7298 if (!T->isDependentType()) { 7299 // FIXME: It isn't entirely clear whether incomplete atomic types 7300 // are allowed or not; for simplicity, ban them for the moment. 7301 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 7302 return QualType(); 7303 7304 int DisallowedKind = -1; 7305 if (T->isArrayType()) 7306 DisallowedKind = 1; 7307 else if (T->isFunctionType()) 7308 DisallowedKind = 2; 7309 else if (T->isReferenceType()) 7310 DisallowedKind = 3; 7311 else if (T->isAtomicType()) 7312 DisallowedKind = 4; 7313 else if (T.hasQualifiers()) 7314 DisallowedKind = 5; 7315 else if (!T.isTriviallyCopyableType(Context)) 7316 // Some other non-trivially-copyable type (probably a C++ class) 7317 DisallowedKind = 6; 7318 7319 if (DisallowedKind != -1) { 7320 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 7321 return QualType(); 7322 } 7323 7324 // FIXME: Do we need any handling for ARC here? 7325 } 7326 7327 // Build the pointer type. 7328 return Context.getAtomicType(T); 7329 } 7330