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