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