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