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