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 CC = CC_OpenCLKernel; 3179 break; 3180 } 3181 } 3182 } 3183 3184 return CC; 3185 } 3186 3187 namespace { 3188 /// A simple notion of pointer kinds, which matches up with the various 3189 /// pointer declarators. 3190 enum class SimplePointerKind { 3191 Pointer, 3192 BlockPointer, 3193 MemberPointer, 3194 Array, 3195 }; 3196 } // end anonymous namespace 3197 3198 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { 3199 switch (nullability) { 3200 case NullabilityKind::NonNull: 3201 if (!Ident__Nonnull) 3202 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull"); 3203 return Ident__Nonnull; 3204 3205 case NullabilityKind::Nullable: 3206 if (!Ident__Nullable) 3207 Ident__Nullable = PP.getIdentifierInfo("_Nullable"); 3208 return Ident__Nullable; 3209 3210 case NullabilityKind::Unspecified: 3211 if (!Ident__Null_unspecified) 3212 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified"); 3213 return Ident__Null_unspecified; 3214 } 3215 llvm_unreachable("Unknown nullability kind."); 3216 } 3217 3218 /// Retrieve the identifier "NSError". 3219 IdentifierInfo *Sema::getNSErrorIdent() { 3220 if (!Ident_NSError) 3221 Ident_NSError = PP.getIdentifierInfo("NSError"); 3222 3223 return Ident_NSError; 3224 } 3225 3226 /// Check whether there is a nullability attribute of any kind in the given 3227 /// attribute list. 3228 static bool hasNullabilityAttr(const AttributeList *attrs) { 3229 for (const AttributeList *attr = attrs; attr; 3230 attr = attr->getNext()) { 3231 if (attr->getKind() == AttributeList::AT_TypeNonNull || 3232 attr->getKind() == AttributeList::AT_TypeNullable || 3233 attr->getKind() == AttributeList::AT_TypeNullUnspecified) 3234 return true; 3235 } 3236 3237 return false; 3238 } 3239 3240 namespace { 3241 /// Describes the kind of a pointer a declarator describes. 3242 enum class PointerDeclaratorKind { 3243 // Not a pointer. 3244 NonPointer, 3245 // Single-level pointer. 3246 SingleLevelPointer, 3247 // Multi-level pointer (of any pointer kind). 3248 MultiLevelPointer, 3249 // CFFooRef* 3250 MaybePointerToCFRef, 3251 // CFErrorRef* 3252 CFErrorRefPointer, 3253 // NSError** 3254 NSErrorPointerPointer, 3255 }; 3256 3257 /// Describes a declarator chunk wrapping a pointer that marks inference as 3258 /// unexpected. 3259 // These values must be kept in sync with diagnostics. 3260 enum class PointerWrappingDeclaratorKind { 3261 /// Pointer is top-level. 3262 None = -1, 3263 /// Pointer is an array element. 3264 Array = 0, 3265 /// Pointer is the referent type of a C++ reference. 3266 Reference = 1 3267 }; 3268 } // end anonymous namespace 3269 3270 /// Classify the given declarator, whose type-specified is \c type, based on 3271 /// what kind of pointer it refers to. 3272 /// 3273 /// This is used to determine the default nullability. 3274 static PointerDeclaratorKind 3275 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, 3276 PointerWrappingDeclaratorKind &wrappingKind) { 3277 unsigned numNormalPointers = 0; 3278 3279 // For any dependent type, we consider it a non-pointer. 3280 if (type->isDependentType()) 3281 return PointerDeclaratorKind::NonPointer; 3282 3283 // Look through the declarator chunks to identify pointers. 3284 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { 3285 DeclaratorChunk &chunk = declarator.getTypeObject(i); 3286 switch (chunk.Kind) { 3287 case DeclaratorChunk::Array: 3288 if (numNormalPointers == 0) 3289 wrappingKind = PointerWrappingDeclaratorKind::Array; 3290 break; 3291 3292 case DeclaratorChunk::Function: 3293 case DeclaratorChunk::Pipe: 3294 break; 3295 3296 case DeclaratorChunk::BlockPointer: 3297 case DeclaratorChunk::MemberPointer: 3298 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3299 : PointerDeclaratorKind::SingleLevelPointer; 3300 3301 case DeclaratorChunk::Paren: 3302 break; 3303 3304 case DeclaratorChunk::Reference: 3305 if (numNormalPointers == 0) 3306 wrappingKind = PointerWrappingDeclaratorKind::Reference; 3307 break; 3308 3309 case DeclaratorChunk::Pointer: 3310 ++numNormalPointers; 3311 if (numNormalPointers > 2) 3312 return PointerDeclaratorKind::MultiLevelPointer; 3313 break; 3314 } 3315 } 3316 3317 // Then, dig into the type specifier itself. 3318 unsigned numTypeSpecifierPointers = 0; 3319 do { 3320 // Decompose normal pointers. 3321 if (auto ptrType = type->getAs<PointerType>()) { 3322 ++numNormalPointers; 3323 3324 if (numNormalPointers > 2) 3325 return PointerDeclaratorKind::MultiLevelPointer; 3326 3327 type = ptrType->getPointeeType(); 3328 ++numTypeSpecifierPointers; 3329 continue; 3330 } 3331 3332 // Decompose block pointers. 3333 if (type->getAs<BlockPointerType>()) { 3334 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3335 : PointerDeclaratorKind::SingleLevelPointer; 3336 } 3337 3338 // Decompose member pointers. 3339 if (type->getAs<MemberPointerType>()) { 3340 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3341 : PointerDeclaratorKind::SingleLevelPointer; 3342 } 3343 3344 // Look at Objective-C object pointers. 3345 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { 3346 ++numNormalPointers; 3347 ++numTypeSpecifierPointers; 3348 3349 // If this is NSError**, report that. 3350 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { 3351 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() && 3352 numNormalPointers == 2 && numTypeSpecifierPointers < 2) { 3353 return PointerDeclaratorKind::NSErrorPointerPointer; 3354 } 3355 } 3356 3357 break; 3358 } 3359 3360 // Look at Objective-C class types. 3361 if (auto objcClass = type->getAs<ObjCInterfaceType>()) { 3362 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) { 3363 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) 3364 return PointerDeclaratorKind::NSErrorPointerPointer;; 3365 } 3366 3367 break; 3368 } 3369 3370 // If at this point we haven't seen a pointer, we won't see one. 3371 if (numNormalPointers == 0) 3372 return PointerDeclaratorKind::NonPointer; 3373 3374 if (auto recordType = type->getAs<RecordType>()) { 3375 RecordDecl *recordDecl = recordType->getDecl(); 3376 3377 bool isCFError = false; 3378 if (S.CFError) { 3379 // If we already know about CFError, test it directly. 3380 isCFError = (S.CFError == recordDecl); 3381 } else { 3382 // Check whether this is CFError, which we identify based on its bridge 3383 // to NSError. 3384 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) { 3385 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) { 3386 if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) { 3387 S.CFError = recordDecl; 3388 isCFError = true; 3389 } 3390 } 3391 } 3392 } 3393 3394 // If this is CFErrorRef*, report it as such. 3395 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) { 3396 return PointerDeclaratorKind::CFErrorRefPointer; 3397 } 3398 break; 3399 } 3400 3401 break; 3402 } while (true); 3403 3404 switch (numNormalPointers) { 3405 case 0: 3406 return PointerDeclaratorKind::NonPointer; 3407 3408 case 1: 3409 return PointerDeclaratorKind::SingleLevelPointer; 3410 3411 case 2: 3412 return PointerDeclaratorKind::MaybePointerToCFRef; 3413 3414 default: 3415 return PointerDeclaratorKind::MultiLevelPointer; 3416 } 3417 } 3418 3419 static FileID getNullabilityCompletenessCheckFileID(Sema &S, 3420 SourceLocation loc) { 3421 // If we're anywhere in a function, method, or closure context, don't perform 3422 // completeness checks. 3423 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { 3424 if (ctx->isFunctionOrMethod()) 3425 return FileID(); 3426 3427 if (ctx->isFileContext()) 3428 break; 3429 } 3430 3431 // We only care about the expansion location. 3432 loc = S.SourceMgr.getExpansionLoc(loc); 3433 FileID file = S.SourceMgr.getFileID(loc); 3434 if (file.isInvalid()) 3435 return FileID(); 3436 3437 // Retrieve file information. 3438 bool invalid = false; 3439 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid); 3440 if (invalid || !sloc.isFile()) 3441 return FileID(); 3442 3443 // We don't want to perform completeness checks on the main file or in 3444 // system headers. 3445 const SrcMgr::FileInfo &fileInfo = sloc.getFile(); 3446 if (fileInfo.getIncludeLoc().isInvalid()) 3447 return FileID(); 3448 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && 3449 S.Diags.getSuppressSystemWarnings()) { 3450 return FileID(); 3451 } 3452 3453 return file; 3454 } 3455 3456 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc, 3457 /// taking into account whitespace before and after. 3458 static void fixItNullability(Sema &S, DiagnosticBuilder &Diag, 3459 SourceLocation PointerLoc, 3460 NullabilityKind Nullability) { 3461 assert(PointerLoc.isValid()); 3462 if (PointerLoc.isMacroID()) 3463 return; 3464 3465 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc); 3466 if (!FixItLoc.isValid() || FixItLoc == PointerLoc) 3467 return; 3468 3469 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc); 3470 if (!NextChar) 3471 return; 3472 3473 SmallString<32> InsertionTextBuf{" "}; 3474 InsertionTextBuf += getNullabilitySpelling(Nullability); 3475 InsertionTextBuf += " "; 3476 StringRef InsertionText = InsertionTextBuf.str(); 3477 3478 if (isWhitespace(*NextChar)) { 3479 InsertionText = InsertionText.drop_back(); 3480 } else if (NextChar[-1] == '[') { 3481 if (NextChar[0] == ']') 3482 InsertionText = InsertionText.drop_back().drop_front(); 3483 else 3484 InsertionText = InsertionText.drop_front(); 3485 } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) && 3486 !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) { 3487 InsertionText = InsertionText.drop_back().drop_front(); 3488 } 3489 3490 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText); 3491 } 3492 3493 static void emitNullabilityConsistencyWarning(Sema &S, 3494 SimplePointerKind PointerKind, 3495 SourceLocation PointerLoc) { 3496 assert(PointerLoc.isValid()); 3497 3498 if (PointerKind == SimplePointerKind::Array) { 3499 S.Diag(PointerLoc, diag::warn_nullability_missing_array); 3500 } else { 3501 S.Diag(PointerLoc, diag::warn_nullability_missing) 3502 << static_cast<unsigned>(PointerKind); 3503 } 3504 3505 if (PointerLoc.isMacroID()) 3506 return; 3507 3508 auto addFixIt = [&](NullabilityKind Nullability) { 3509 auto Diag = S.Diag(PointerLoc, diag::note_nullability_fix_it); 3510 Diag << static_cast<unsigned>(Nullability); 3511 Diag << static_cast<unsigned>(PointerKind); 3512 fixItNullability(S, Diag, PointerLoc, Nullability); 3513 }; 3514 addFixIt(NullabilityKind::Nullable); 3515 addFixIt(NullabilityKind::NonNull); 3516 } 3517 3518 /// Complains about missing nullability if the file containing \p pointerLoc 3519 /// has other uses of nullability (either the keywords or the \c assume_nonnull 3520 /// pragma). 3521 /// 3522 /// If the file has \e not seen other uses of nullability, this particular 3523 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen(). 3524 static void checkNullabilityConsistency(Sema &S, 3525 SimplePointerKind pointerKind, 3526 SourceLocation pointerLoc) { 3527 // Determine which file we're performing consistency checking for. 3528 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc); 3529 if (file.isInvalid()) 3530 return; 3531 3532 // If we haven't seen any type nullability in this file, we won't warn now 3533 // about anything. 3534 FileNullability &fileNullability = S.NullabilityMap[file]; 3535 if (!fileNullability.SawTypeNullability) { 3536 // If this is the first pointer declarator in the file, and the appropriate 3537 // warning is on, record it in case we need to diagnose it retroactively. 3538 diag::kind diagKind; 3539 if (pointerKind == SimplePointerKind::Array) 3540 diagKind = diag::warn_nullability_missing_array; 3541 else 3542 diagKind = diag::warn_nullability_missing; 3543 3544 if (fileNullability.PointerLoc.isInvalid() && 3545 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) { 3546 fileNullability.PointerLoc = pointerLoc; 3547 fileNullability.PointerKind = static_cast<unsigned>(pointerKind); 3548 } 3549 3550 return; 3551 } 3552 3553 // Complain about missing nullability. 3554 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc); 3555 } 3556 3557 /// Marks that a nullability feature has been used in the file containing 3558 /// \p loc. 3559 /// 3560 /// If this file already had pointer types in it that were missing nullability, 3561 /// the first such instance is retroactively diagnosed. 3562 /// 3563 /// \sa checkNullabilityConsistency 3564 static void recordNullabilitySeen(Sema &S, SourceLocation loc) { 3565 FileID file = getNullabilityCompletenessCheckFileID(S, loc); 3566 if (file.isInvalid()) 3567 return; 3568 3569 FileNullability &fileNullability = S.NullabilityMap[file]; 3570 if (fileNullability.SawTypeNullability) 3571 return; 3572 fileNullability.SawTypeNullability = true; 3573 3574 // If we haven't seen any type nullability before, now we have. Retroactively 3575 // diagnose the first unannotated pointer, if there was one. 3576 if (fileNullability.PointerLoc.isInvalid()) 3577 return; 3578 3579 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind); 3580 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc); 3581 } 3582 3583 /// Returns true if any of the declarator chunks before \p endIndex include a 3584 /// level of indirection: array, pointer, reference, or pointer-to-member. 3585 /// 3586 /// Because declarator chunks are stored in outer-to-inner order, testing 3587 /// every chunk before \p endIndex is testing all chunks that embed the current 3588 /// chunk as part of their type. 3589 /// 3590 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the 3591 /// end index, in which case all chunks are tested. 3592 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) { 3593 unsigned i = endIndex; 3594 while (i != 0) { 3595 // Walk outwards along the declarator chunks. 3596 --i; 3597 const DeclaratorChunk &DC = D.getTypeObject(i); 3598 switch (DC.Kind) { 3599 case DeclaratorChunk::Paren: 3600 break; 3601 case DeclaratorChunk::Array: 3602 case DeclaratorChunk::Pointer: 3603 case DeclaratorChunk::Reference: 3604 case DeclaratorChunk::MemberPointer: 3605 return true; 3606 case DeclaratorChunk::Function: 3607 case DeclaratorChunk::BlockPointer: 3608 case DeclaratorChunk::Pipe: 3609 // These are invalid anyway, so just ignore. 3610 break; 3611 } 3612 } 3613 return false; 3614 } 3615 3616 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 3617 QualType declSpecType, 3618 TypeSourceInfo *TInfo) { 3619 // The TypeSourceInfo that this function returns will not be a null type. 3620 // If there is an error, this function will fill in a dummy type as fallback. 3621 QualType T = declSpecType; 3622 Declarator &D = state.getDeclarator(); 3623 Sema &S = state.getSema(); 3624 ASTContext &Context = S.Context; 3625 const LangOptions &LangOpts = S.getLangOpts(); 3626 3627 // The name we're declaring, if any. 3628 DeclarationName Name; 3629 if (D.getIdentifier()) 3630 Name = D.getIdentifier(); 3631 3632 // Does this declaration declare a typedef-name? 3633 bool IsTypedefName = 3634 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 3635 D.getContext() == Declarator::AliasDeclContext || 3636 D.getContext() == Declarator::AliasTemplateContext; 3637 3638 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 3639 bool IsQualifiedFunction = T->isFunctionProtoType() && 3640 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 || 3641 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); 3642 3643 // If T is 'decltype(auto)', the only declarators we can have are parens 3644 // and at most one function declarator if this is a function declaration. 3645 // If T is a deduced class template specialization type, we can have no 3646 // declarator chunks at all. 3647 if (auto *DT = T->getAs<DeducedType>()) { 3648 const AutoType *AT = T->getAs<AutoType>(); 3649 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT); 3650 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) { 3651 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3652 unsigned Index = E - I - 1; 3653 DeclaratorChunk &DeclChunk = D.getTypeObject(Index); 3654 unsigned DiagId = IsClassTemplateDeduction 3655 ? diag::err_deduced_class_template_compound_type 3656 : diag::err_decltype_auto_compound_type; 3657 unsigned DiagKind = 0; 3658 switch (DeclChunk.Kind) { 3659 case DeclaratorChunk::Paren: 3660 // FIXME: Rejecting this is a little silly. 3661 if (IsClassTemplateDeduction) { 3662 DiagKind = 4; 3663 break; 3664 } 3665 continue; 3666 case DeclaratorChunk::Function: { 3667 if (IsClassTemplateDeduction) { 3668 DiagKind = 3; 3669 break; 3670 } 3671 unsigned FnIndex; 3672 if (D.isFunctionDeclarationContext() && 3673 D.isFunctionDeclarator(FnIndex) && FnIndex == Index) 3674 continue; 3675 DiagId = diag::err_decltype_auto_function_declarator_not_declaration; 3676 break; 3677 } 3678 case DeclaratorChunk::Pointer: 3679 case DeclaratorChunk::BlockPointer: 3680 case DeclaratorChunk::MemberPointer: 3681 DiagKind = 0; 3682 break; 3683 case DeclaratorChunk::Reference: 3684 DiagKind = 1; 3685 break; 3686 case DeclaratorChunk::Array: 3687 DiagKind = 2; 3688 break; 3689 case DeclaratorChunk::Pipe: 3690 break; 3691 } 3692 3693 S.Diag(DeclChunk.Loc, DiagId) << DiagKind; 3694 D.setInvalidType(true); 3695 break; 3696 } 3697 } 3698 } 3699 3700 // Determine whether we should infer _Nonnull on pointer types. 3701 Optional<NullabilityKind> inferNullability; 3702 bool inferNullabilityCS = false; 3703 bool inferNullabilityInnerOnly = false; 3704 bool inferNullabilityInnerOnlyComplete = false; 3705 3706 // Are we in an assume-nonnull region? 3707 bool inAssumeNonNullRegion = false; 3708 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc(); 3709 if (assumeNonNullLoc.isValid()) { 3710 inAssumeNonNullRegion = true; 3711 recordNullabilitySeen(S, assumeNonNullLoc); 3712 } 3713 3714 // Whether to complain about missing nullability specifiers or not. 3715 enum { 3716 /// Never complain. 3717 CAMN_No, 3718 /// Complain on the inner pointers (but not the outermost 3719 /// pointer). 3720 CAMN_InnerPointers, 3721 /// Complain about any pointers that don't have nullability 3722 /// specified or inferred. 3723 CAMN_Yes 3724 } complainAboutMissingNullability = CAMN_No; 3725 unsigned NumPointersRemaining = 0; 3726 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None; 3727 3728 if (IsTypedefName) { 3729 // For typedefs, we do not infer any nullability (the default), 3730 // and we only complain about missing nullability specifiers on 3731 // inner pointers. 3732 complainAboutMissingNullability = CAMN_InnerPointers; 3733 3734 if (T->canHaveNullability(/*ResultIfUnknown*/false) && 3735 !T->getNullability(S.Context)) { 3736 // Note that we allow but don't require nullability on dependent types. 3737 ++NumPointersRemaining; 3738 } 3739 3740 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { 3741 DeclaratorChunk &chunk = D.getTypeObject(i); 3742 switch (chunk.Kind) { 3743 case DeclaratorChunk::Array: 3744 case DeclaratorChunk::Function: 3745 case DeclaratorChunk::Pipe: 3746 break; 3747 3748 case DeclaratorChunk::BlockPointer: 3749 case DeclaratorChunk::MemberPointer: 3750 ++NumPointersRemaining; 3751 break; 3752 3753 case DeclaratorChunk::Paren: 3754 case DeclaratorChunk::Reference: 3755 continue; 3756 3757 case DeclaratorChunk::Pointer: 3758 ++NumPointersRemaining; 3759 continue; 3760 } 3761 } 3762 } else { 3763 bool isFunctionOrMethod = false; 3764 switch (auto context = state.getDeclarator().getContext()) { 3765 case Declarator::ObjCParameterContext: 3766 case Declarator::ObjCResultContext: 3767 case Declarator::PrototypeContext: 3768 case Declarator::TrailingReturnContext: 3769 isFunctionOrMethod = true; 3770 // fallthrough 3771 3772 case Declarator::MemberContext: 3773 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { 3774 complainAboutMissingNullability = CAMN_No; 3775 break; 3776 } 3777 3778 // Weak properties are inferred to be nullable. 3779 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) { 3780 inferNullability = NullabilityKind::Nullable; 3781 break; 3782 } 3783 3784 // fallthrough 3785 3786 case Declarator::FileContext: 3787 case Declarator::KNRTypeListContext: { 3788 complainAboutMissingNullability = CAMN_Yes; 3789 3790 // Nullability inference depends on the type and declarator. 3791 auto wrappingKind = PointerWrappingDeclaratorKind::None; 3792 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) { 3793 case PointerDeclaratorKind::NonPointer: 3794 case PointerDeclaratorKind::MultiLevelPointer: 3795 // Cannot infer nullability. 3796 break; 3797 3798 case PointerDeclaratorKind::SingleLevelPointer: 3799 // Infer _Nonnull if we are in an assumes-nonnull region. 3800 if (inAssumeNonNullRegion) { 3801 complainAboutInferringWithinChunk = wrappingKind; 3802 inferNullability = NullabilityKind::NonNull; 3803 inferNullabilityCS = (context == Declarator::ObjCParameterContext || 3804 context == Declarator::ObjCResultContext); 3805 } 3806 break; 3807 3808 case PointerDeclaratorKind::CFErrorRefPointer: 3809 case PointerDeclaratorKind::NSErrorPointerPointer: 3810 // Within a function or method signature, infer _Nullable at both 3811 // levels. 3812 if (isFunctionOrMethod && inAssumeNonNullRegion) 3813 inferNullability = NullabilityKind::Nullable; 3814 break; 3815 3816 case PointerDeclaratorKind::MaybePointerToCFRef: 3817 if (isFunctionOrMethod) { 3818 // On pointer-to-pointer parameters marked cf_returns_retained or 3819 // cf_returns_not_retained, if the outer pointer is explicit then 3820 // infer the inner pointer as _Nullable. 3821 auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool { 3822 while (NextAttr) { 3823 if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained || 3824 NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained) 3825 return true; 3826 NextAttr = NextAttr->getNext(); 3827 } 3828 return false; 3829 }; 3830 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { 3831 if (hasCFReturnsAttr(D.getAttributes()) || 3832 hasCFReturnsAttr(InnermostChunk->getAttrs()) || 3833 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) { 3834 inferNullability = NullabilityKind::Nullable; 3835 inferNullabilityInnerOnly = true; 3836 } 3837 } 3838 } 3839 break; 3840 } 3841 break; 3842 } 3843 3844 case Declarator::ConversionIdContext: 3845 complainAboutMissingNullability = CAMN_Yes; 3846 break; 3847 3848 case Declarator::AliasDeclContext: 3849 case Declarator::AliasTemplateContext: 3850 case Declarator::BlockContext: 3851 case Declarator::BlockLiteralContext: 3852 case Declarator::ConditionContext: 3853 case Declarator::CXXCatchContext: 3854 case Declarator::CXXNewContext: 3855 case Declarator::ForContext: 3856 case Declarator::InitStmtContext: 3857 case Declarator::LambdaExprContext: 3858 case Declarator::LambdaExprParameterContext: 3859 case Declarator::ObjCCatchContext: 3860 case Declarator::TemplateParamContext: 3861 case Declarator::TemplateTypeArgContext: 3862 case Declarator::TypeNameContext: 3863 case Declarator::FunctionalCastContext: 3864 // Don't infer in these contexts. 3865 break; 3866 } 3867 } 3868 3869 // Local function that returns true if its argument looks like a va_list. 3870 auto isVaList = [&S](QualType T) -> bool { 3871 auto *typedefTy = T->getAs<TypedefType>(); 3872 if (!typedefTy) 3873 return false; 3874 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl(); 3875 do { 3876 if (typedefTy->getDecl() == vaListTypedef) 3877 return true; 3878 if (auto *name = typedefTy->getDecl()->getIdentifier()) 3879 if (name->isStr("va_list")) 3880 return true; 3881 typedefTy = typedefTy->desugar()->getAs<TypedefType>(); 3882 } while (typedefTy); 3883 return false; 3884 }; 3885 3886 // Local function that checks the nullability for a given pointer declarator. 3887 // Returns true if _Nonnull was inferred. 3888 auto inferPointerNullability = [&](SimplePointerKind pointerKind, 3889 SourceLocation pointerLoc, 3890 AttributeList *&attrs) -> AttributeList * { 3891 // We've seen a pointer. 3892 if (NumPointersRemaining > 0) 3893 --NumPointersRemaining; 3894 3895 // If a nullability attribute is present, there's nothing to do. 3896 if (hasNullabilityAttr(attrs)) 3897 return nullptr; 3898 3899 // If we're supposed to infer nullability, do so now. 3900 if (inferNullability && !inferNullabilityInnerOnlyComplete) { 3901 AttributeList::Syntax syntax 3902 = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword 3903 : AttributeList::AS_Keyword; 3904 AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool() 3905 .create( 3906 S.getNullabilityKeyword( 3907 *inferNullability), 3908 SourceRange(pointerLoc), 3909 nullptr, SourceLocation(), 3910 nullptr, 0, syntax); 3911 3912 spliceAttrIntoList(*nullabilityAttr, attrs); 3913 3914 if (inferNullabilityCS) { 3915 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() 3916 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); 3917 } 3918 3919 if (pointerLoc.isValid() && 3920 complainAboutInferringWithinChunk != 3921 PointerWrappingDeclaratorKind::None) { 3922 auto Diag = 3923 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type); 3924 Diag << static_cast<int>(complainAboutInferringWithinChunk); 3925 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull); 3926 } 3927 3928 if (inferNullabilityInnerOnly) 3929 inferNullabilityInnerOnlyComplete = true; 3930 return nullabilityAttr; 3931 } 3932 3933 // If we're supposed to complain about missing nullability, do so 3934 // now if it's truly missing. 3935 switch (complainAboutMissingNullability) { 3936 case CAMN_No: 3937 break; 3938 3939 case CAMN_InnerPointers: 3940 if (NumPointersRemaining == 0) 3941 break; 3942 // Fallthrough. 3943 3944 case CAMN_Yes: 3945 checkNullabilityConsistency(S, pointerKind, pointerLoc); 3946 } 3947 return nullptr; 3948 }; 3949 3950 // If the type itself could have nullability but does not, infer pointer 3951 // nullability and perform consistency checking. 3952 if (S.CodeSynthesisContexts.empty()) { 3953 if (T->canHaveNullability(/*ResultIfUnknown*/false) && 3954 !T->getNullability(S.Context)) { 3955 if (isVaList(T)) { 3956 // Record that we've seen a pointer, but do nothing else. 3957 if (NumPointersRemaining > 0) 3958 --NumPointersRemaining; 3959 } else { 3960 SimplePointerKind pointerKind = SimplePointerKind::Pointer; 3961 if (T->isBlockPointerType()) 3962 pointerKind = SimplePointerKind::BlockPointer; 3963 else if (T->isMemberPointerType()) 3964 pointerKind = SimplePointerKind::MemberPointer; 3965 3966 if (auto *attr = inferPointerNullability( 3967 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), 3968 D.getMutableDeclSpec().getAttributes().getListRef())) { 3969 T = Context.getAttributedType( 3970 AttributedType::getNullabilityAttrKind(*inferNullability),T,T); 3971 attr->setUsedAsTypeAttr(); 3972 } 3973 } 3974 } 3975 3976 if (complainAboutMissingNullability == CAMN_Yes && 3977 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) && 3978 D.isPrototypeContext() && 3979 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) { 3980 checkNullabilityConsistency(S, SimplePointerKind::Array, 3981 D.getDeclSpec().getTypeSpecTypeLoc()); 3982 } 3983 } 3984 3985 // Walk the DeclTypeInfo, building the recursive type as we go. 3986 // DeclTypeInfos are ordered from the identifier out, which is 3987 // opposite of what we want :). 3988 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3989 unsigned chunkIndex = e - i - 1; 3990 state.setCurrentChunkIndex(chunkIndex); 3991 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 3992 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; 3993 switch (DeclType.Kind) { 3994 case DeclaratorChunk::Paren: 3995 T = S.BuildParenType(T); 3996 break; 3997 case DeclaratorChunk::BlockPointer: 3998 // If blocks are disabled, emit an error. 3999 if (!LangOpts.Blocks) 4000 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL; 4001 4002 // Handle pointer nullability. 4003 inferPointerNullability(SimplePointerKind::BlockPointer, 4004 DeclType.Loc, DeclType.getAttrListRef()); 4005 4006 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 4007 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) { 4008 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly 4009 // qualified with const. 4010 if (LangOpts.OpenCL) 4011 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const; 4012 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 4013 } 4014 break; 4015 case DeclaratorChunk::Pointer: 4016 // Verify that we're not building a pointer to pointer to function with 4017 // exception specification. 4018 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 4019 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 4020 D.setInvalidType(true); 4021 // Build the type anyway. 4022 } 4023 4024 // Handle pointer nullability 4025 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, 4026 DeclType.getAttrListRef()); 4027 4028 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) { 4029 T = Context.getObjCObjectPointerType(T); 4030 if (DeclType.Ptr.TypeQuals) 4031 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 4032 break; 4033 } 4034 4035 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used. 4036 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used. 4037 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed. 4038 if (LangOpts.OpenCL) { 4039 if (T->isImageType() || T->isSamplerT() || T->isPipeType() || 4040 T->isBlockPointerType()) { 4041 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T; 4042 D.setInvalidType(true); 4043 } 4044 } 4045 4046 T = S.BuildPointerType(T, DeclType.Loc, Name); 4047 if (DeclType.Ptr.TypeQuals) 4048 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 4049 break; 4050 case DeclaratorChunk::Reference: { 4051 // Verify that we're not building a reference to pointer to function with 4052 // exception specification. 4053 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 4054 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 4055 D.setInvalidType(true); 4056 // Build the type anyway. 4057 } 4058 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 4059 4060 if (DeclType.Ref.HasRestrict) 4061 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 4062 break; 4063 } 4064 case DeclaratorChunk::Array: { 4065 // Verify that we're not building an array of pointers to function with 4066 // exception specification. 4067 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 4068 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 4069 D.setInvalidType(true); 4070 // Build the type anyway. 4071 } 4072 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 4073 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 4074 ArrayType::ArraySizeModifier ASM; 4075 if (ATI.isStar) 4076 ASM = ArrayType::Star; 4077 else if (ATI.hasStatic) 4078 ASM = ArrayType::Static; 4079 else 4080 ASM = ArrayType::Normal; 4081 if (ASM == ArrayType::Star && !D.isPrototypeContext()) { 4082 // FIXME: This check isn't quite right: it allows star in prototypes 4083 // for function definitions, and disallows some edge cases detailed 4084 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 4085 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 4086 ASM = ArrayType::Normal; 4087 D.setInvalidType(true); 4088 } 4089 4090 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static 4091 // shall appear only in a declaration of a function parameter with an 4092 // array type, ... 4093 if (ASM == ArrayType::Static || ATI.TypeQuals) { 4094 if (!(D.isPrototypeContext() || 4095 D.getContext() == Declarator::KNRTypeListContext)) { 4096 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << 4097 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 4098 // Remove the 'static' and the type qualifiers. 4099 if (ASM == ArrayType::Static) 4100 ASM = ArrayType::Normal; 4101 ATI.TypeQuals = 0; 4102 D.setInvalidType(true); 4103 } 4104 4105 // C99 6.7.5.2p1: ... and then only in the outermost array type 4106 // derivation. 4107 if (hasOuterPointerLikeChunk(D, chunkIndex)) { 4108 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << 4109 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 4110 if (ASM == ArrayType::Static) 4111 ASM = ArrayType::Normal; 4112 ATI.TypeQuals = 0; 4113 D.setInvalidType(true); 4114 } 4115 } 4116 const AutoType *AT = T->getContainedAutoType(); 4117 // Allow arrays of auto if we are a generic lambda parameter. 4118 // i.e. [](auto (&array)[5]) { return array[0]; }; OK 4119 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) { 4120 // We've already diagnosed this for decltype(auto). 4121 if (!AT->isDecltypeAuto()) 4122 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) 4123 << getPrintableNameForEntity(Name) << T; 4124 T = QualType(); 4125 break; 4126 } 4127 4128 // Array parameters can be marked nullable as well, although it's not 4129 // necessary if they're marked 'static'. 4130 if (complainAboutMissingNullability == CAMN_Yes && 4131 !hasNullabilityAttr(DeclType.getAttrs()) && 4132 ASM != ArrayType::Static && 4133 D.isPrototypeContext() && 4134 !hasOuterPointerLikeChunk(D, chunkIndex)) { 4135 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc); 4136 } 4137 4138 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 4139 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 4140 break; 4141 } 4142 case DeclaratorChunk::Function: { 4143 // If the function declarator has a prototype (i.e. it is not () and 4144 // does not have a K&R-style identifier list), then the arguments are part 4145 // of the type, otherwise the argument list is (). 4146 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 4147 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier(); 4148 4149 // Check for auto functions and trailing return type and adjust the 4150 // return type accordingly. 4151 if (!D.isInvalidType()) { 4152 // trailing-return-type is only required if we're declaring a function, 4153 // and not, for instance, a pointer to a function. 4154 if (D.getDeclSpec().hasAutoTypeSpec() && 4155 !FTI.hasTrailingReturnType() && chunkIndex == 0 && 4156 !S.getLangOpts().CPlusPlus14) { 4157 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 4158 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto 4159 ? diag::err_auto_missing_trailing_return 4160 : diag::err_deduced_return_type); 4161 T = Context.IntTy; 4162 D.setInvalidType(true); 4163 } else if (FTI.hasTrailingReturnType()) { 4164 // T must be exactly 'auto' at this point. See CWG issue 681. 4165 if (isa<ParenType>(T)) { 4166 S.Diag(D.getLocStart(), 4167 diag::err_trailing_return_in_parens) 4168 << T << D.getSourceRange(); 4169 D.setInvalidType(true); 4170 } else if (D.getName().getKind() == 4171 UnqualifiedId::IK_DeductionGuideName) { 4172 if (T != Context.DependentTy) { 4173 S.Diag(D.getDeclSpec().getLocStart(), 4174 diag::err_deduction_guide_with_complex_decl) 4175 << D.getSourceRange(); 4176 D.setInvalidType(true); 4177 } 4178 } else if (D.getContext() != Declarator::LambdaExprContext && 4179 (T.hasQualifiers() || !isa<AutoType>(T) || 4180 cast<AutoType>(T)->getKeyword() != 4181 AutoTypeKeyword::Auto)) { 4182 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 4183 diag::err_trailing_return_without_auto) 4184 << T << D.getDeclSpec().getSourceRange(); 4185 D.setInvalidType(true); 4186 } 4187 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); 4188 if (T.isNull()) { 4189 // An error occurred parsing the trailing return type. 4190 T = Context.IntTy; 4191 D.setInvalidType(true); 4192 } 4193 } 4194 } 4195 4196 // C99 6.7.5.3p1: The return type may not be a function or array type. 4197 // For conversion functions, we'll diagnose this particular error later. 4198 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) && 4199 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 4200 unsigned diagID = diag::err_func_returning_array_function; 4201 // Last processing chunk in block context means this function chunk 4202 // represents the block. 4203 if (chunkIndex == 0 && 4204 D.getContext() == Declarator::BlockLiteralContext) 4205 diagID = diag::err_block_returning_array_function; 4206 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 4207 T = Context.IntTy; 4208 D.setInvalidType(true); 4209 } 4210 4211 // Do not allow returning half FP value. 4212 // FIXME: This really should be in BuildFunctionType. 4213 if (T->isHalfType()) { 4214 if (S.getLangOpts().OpenCL) { 4215 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 4216 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) 4217 << T << 0 /*pointer hint*/; 4218 D.setInvalidType(true); 4219 } 4220 } else if (!S.getLangOpts().HalfArgsAndReturns) { 4221 S.Diag(D.getIdentifierLoc(), 4222 diag::err_parameters_retval_cannot_have_fp16_type) << 1; 4223 D.setInvalidType(true); 4224 } 4225 } 4226 4227 if (LangOpts.OpenCL) { 4228 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a 4229 // function. 4230 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() || 4231 T->isPipeType()) { 4232 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) 4233 << T << 1 /*hint off*/; 4234 D.setInvalidType(true); 4235 } 4236 // OpenCL doesn't support variadic functions and blocks 4237 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf. 4238 // We also allow here any toolchain reserved identifiers. 4239 if (FTI.isVariadic && 4240 !(D.getIdentifier() && 4241 ((D.getIdentifier()->getName() == "printf" && 4242 LangOpts.OpenCLVersion >= 120) || 4243 D.getIdentifier()->getName().startswith("__")))) { 4244 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function); 4245 D.setInvalidType(true); 4246 } 4247 } 4248 4249 // Methods cannot return interface types. All ObjC objects are 4250 // passed by reference. 4251 if (T->isObjCObjectType()) { 4252 SourceLocation DiagLoc, FixitLoc; 4253 if (TInfo) { 4254 DiagLoc = TInfo->getTypeLoc().getLocStart(); 4255 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd()); 4256 } else { 4257 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 4258 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd()); 4259 } 4260 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) 4261 << 0 << T 4262 << FixItHint::CreateInsertion(FixitLoc, "*"); 4263 4264 T = Context.getObjCObjectPointerType(T); 4265 if (TInfo) { 4266 TypeLocBuilder TLB; 4267 TLB.pushFullCopy(TInfo->getTypeLoc()); 4268 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); 4269 TLoc.setStarLoc(FixitLoc); 4270 TInfo = TLB.getTypeSourceInfo(Context, T); 4271 } 4272 4273 D.setInvalidType(true); 4274 } 4275 4276 // cv-qualifiers on return types are pointless except when the type is a 4277 // class type in C++. 4278 if ((T.getCVRQualifiers() || T->isAtomicType()) && 4279 !(S.getLangOpts().CPlusPlus && 4280 (T->isDependentType() || T->isRecordType()))) { 4281 if (T->isVoidType() && !S.getLangOpts().CPlusPlus && 4282 D.getFunctionDefinitionKind() == FDK_Definition) { 4283 // [6.9.1/3] qualified void return is invalid on a C 4284 // function definition. Apparently ok on declarations and 4285 // in C++ though (!) 4286 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; 4287 } else 4288 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); 4289 } 4290 4291 // Objective-C ARC ownership qualifiers are ignored on the function 4292 // return type (by type canonicalization). Complain if this attribute 4293 // was written here. 4294 if (T.getQualifiers().hasObjCLifetime()) { 4295 SourceLocation AttrLoc; 4296 if (chunkIndex + 1 < D.getNumTypeObjects()) { 4297 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 4298 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs(); 4299 Attr; Attr = Attr->getNext()) { 4300 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 4301 AttrLoc = Attr->getLoc(); 4302 break; 4303 } 4304 } 4305 } 4306 if (AttrLoc.isInvalid()) { 4307 for (const AttributeList *Attr 4308 = D.getDeclSpec().getAttributes().getList(); 4309 Attr; Attr = Attr->getNext()) { 4310 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 4311 AttrLoc = Attr->getLoc(); 4312 break; 4313 } 4314 } 4315 } 4316 4317 if (AttrLoc.isValid()) { 4318 // The ownership attributes are almost always written via 4319 // the predefined 4320 // __strong/__weak/__autoreleasing/__unsafe_unretained. 4321 if (AttrLoc.isMacroID()) 4322 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first; 4323 4324 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 4325 << T.getQualifiers().getObjCLifetime(); 4326 } 4327 } 4328 4329 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { 4330 // C++ [dcl.fct]p6: 4331 // Types shall not be defined in return or parameter types. 4332 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 4333 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 4334 << Context.getTypeDeclType(Tag); 4335 } 4336 4337 // Exception specs are not allowed in typedefs. Complain, but add it 4338 // anyway. 4339 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus1z) 4340 S.Diag(FTI.getExceptionSpecLocBeg(), 4341 diag::err_exception_spec_in_typedef) 4342 << (D.getContext() == Declarator::AliasDeclContext || 4343 D.getContext() == Declarator::AliasTemplateContext); 4344 4345 // If we see "T var();" or "T var(T());" at block scope, it is probably 4346 // an attempt to initialize a variable, not a function declaration. 4347 if (FTI.isAmbiguous) 4348 warnAboutAmbiguousFunction(S, D, DeclType, T); 4349 4350 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex)); 4351 4352 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) { 4353 // Simple void foo(), where the incoming T is the result type. 4354 T = Context.getFunctionNoProtoType(T, EI); 4355 } else { 4356 // We allow a zero-parameter variadic function in C if the 4357 // function is marked with the "overloadable" attribute. Scan 4358 // for this attribute now. 4359 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) { 4360 bool Overloadable = false; 4361 for (const AttributeList *Attrs = D.getAttributes(); 4362 Attrs; Attrs = Attrs->getNext()) { 4363 if (Attrs->getKind() == AttributeList::AT_Overloadable) { 4364 Overloadable = true; 4365 break; 4366 } 4367 } 4368 4369 if (!Overloadable) 4370 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); 4371 } 4372 4373 if (FTI.NumParams && FTI.Params[0].Param == nullptr) { 4374 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 4375 // definition. 4376 S.Diag(FTI.Params[0].IdentLoc, 4377 diag::err_ident_list_in_fn_declaration); 4378 D.setInvalidType(true); 4379 // Recover by creating a K&R-style function type. 4380 T = Context.getFunctionNoProtoType(T, EI); 4381 break; 4382 } 4383 4384 FunctionProtoType::ExtProtoInfo EPI; 4385 EPI.ExtInfo = EI; 4386 EPI.Variadic = FTI.isVariadic; 4387 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 4388 EPI.TypeQuals = FTI.TypeQuals; 4389 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 4390 : FTI.RefQualifierIsLValueRef? RQ_LValue 4391 : RQ_RValue; 4392 4393 // Otherwise, we have a function with a parameter list that is 4394 // potentially variadic. 4395 SmallVector<QualType, 16> ParamTys; 4396 ParamTys.reserve(FTI.NumParams); 4397 4398 SmallVector<FunctionProtoType::ExtParameterInfo, 16> 4399 ExtParameterInfos(FTI.NumParams); 4400 bool HasAnyInterestingExtParameterInfos = false; 4401 4402 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 4403 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 4404 QualType ParamTy = Param->getType(); 4405 assert(!ParamTy.isNull() && "Couldn't parse type?"); 4406 4407 // Look for 'void'. void is allowed only as a single parameter to a 4408 // function with no other parameters (C99 6.7.5.3p10). We record 4409 // int(void) as a FunctionProtoType with an empty parameter list. 4410 if (ParamTy->isVoidType()) { 4411 // If this is something like 'float(int, void)', reject it. 'void' 4412 // is an incomplete type (C99 6.2.5p19) and function decls cannot 4413 // have parameters of incomplete type. 4414 if (FTI.NumParams != 1 || FTI.isVariadic) { 4415 S.Diag(DeclType.Loc, diag::err_void_only_param); 4416 ParamTy = Context.IntTy; 4417 Param->setType(ParamTy); 4418 } else if (FTI.Params[i].Ident) { 4419 // Reject, but continue to parse 'int(void abc)'. 4420 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); 4421 ParamTy = Context.IntTy; 4422 Param->setType(ParamTy); 4423 } else { 4424 // Reject, but continue to parse 'float(const void)'. 4425 if (ParamTy.hasQualifiers()) 4426 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 4427 4428 // Do not add 'void' to the list. 4429 break; 4430 } 4431 } else if (ParamTy->isHalfType()) { 4432 // Disallow half FP parameters. 4433 // FIXME: This really should be in BuildFunctionType. 4434 if (S.getLangOpts().OpenCL) { 4435 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 4436 S.Diag(Param->getLocation(), 4437 diag::err_opencl_half_param) << ParamTy; 4438 D.setInvalidType(); 4439 Param->setInvalidDecl(); 4440 } 4441 } else if (!S.getLangOpts().HalfArgsAndReturns) { 4442 S.Diag(Param->getLocation(), 4443 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 4444 D.setInvalidType(); 4445 } 4446 } else if (!FTI.hasPrototype) { 4447 if (ParamTy->isPromotableIntegerType()) { 4448 ParamTy = Context.getPromotedIntegerType(ParamTy); 4449 Param->setKNRPromoted(true); 4450 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { 4451 if (BTy->getKind() == BuiltinType::Float) { 4452 ParamTy = Context.DoubleTy; 4453 Param->setKNRPromoted(true); 4454 } 4455 } 4456 } 4457 4458 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { 4459 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); 4460 HasAnyInterestingExtParameterInfos = true; 4461 } 4462 4463 if (auto attr = Param->getAttr<ParameterABIAttr>()) { 4464 ExtParameterInfos[i] = 4465 ExtParameterInfos[i].withABI(attr->getABI()); 4466 HasAnyInterestingExtParameterInfos = true; 4467 } 4468 4469 if (Param->hasAttr<PassObjectSizeAttr>()) { 4470 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize(); 4471 HasAnyInterestingExtParameterInfos = true; 4472 } 4473 4474 ParamTys.push_back(ParamTy); 4475 } 4476 4477 if (HasAnyInterestingExtParameterInfos) { 4478 EPI.ExtParameterInfos = ExtParameterInfos.data(); 4479 checkExtParameterInfos(S, ParamTys, EPI, 4480 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); 4481 } 4482 4483 SmallVector<QualType, 4> Exceptions; 4484 SmallVector<ParsedType, 2> DynamicExceptions; 4485 SmallVector<SourceRange, 2> DynamicExceptionRanges; 4486 Expr *NoexceptExpr = nullptr; 4487 4488 if (FTI.getExceptionSpecType() == EST_Dynamic) { 4489 // FIXME: It's rather inefficient to have to split into two vectors 4490 // here. 4491 unsigned N = FTI.getNumExceptions(); 4492 DynamicExceptions.reserve(N); 4493 DynamicExceptionRanges.reserve(N); 4494 for (unsigned I = 0; I != N; ++I) { 4495 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 4496 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 4497 } 4498 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 4499 NoexceptExpr = FTI.NoexceptExpr; 4500 } 4501 4502 S.checkExceptionSpecification(D.isFunctionDeclarationContext(), 4503 FTI.getExceptionSpecType(), 4504 DynamicExceptions, 4505 DynamicExceptionRanges, 4506 NoexceptExpr, 4507 Exceptions, 4508 EPI.ExceptionSpec); 4509 4510 T = Context.getFunctionType(T, ParamTys, EPI); 4511 } 4512 break; 4513 } 4514 case DeclaratorChunk::MemberPointer: { 4515 // The scope spec must refer to a class, or be dependent. 4516 CXXScopeSpec &SS = DeclType.Mem.Scope(); 4517 QualType ClsType; 4518 4519 // Handle pointer nullability. 4520 inferPointerNullability(SimplePointerKind::MemberPointer, 4521 DeclType.Loc, DeclType.getAttrListRef()); 4522 4523 if (SS.isInvalid()) { 4524 // Avoid emitting extra errors if we already errored on the scope. 4525 D.setInvalidType(true); 4526 } else if (S.isDependentScopeSpecifier(SS) || 4527 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 4528 NestedNameSpecifier *NNS = SS.getScopeRep(); 4529 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 4530 switch (NNS->getKind()) { 4531 case NestedNameSpecifier::Identifier: 4532 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 4533 NNS->getAsIdentifier()); 4534 break; 4535 4536 case NestedNameSpecifier::Namespace: 4537 case NestedNameSpecifier::NamespaceAlias: 4538 case NestedNameSpecifier::Global: 4539 case NestedNameSpecifier::Super: 4540 llvm_unreachable("Nested-name-specifier must name a type"); 4541 4542 case NestedNameSpecifier::TypeSpec: 4543 case NestedNameSpecifier::TypeSpecWithTemplate: 4544 ClsType = QualType(NNS->getAsType(), 0); 4545 // Note: if the NNS has a prefix and ClsType is a nondependent 4546 // TemplateSpecializationType, then the NNS prefix is NOT included 4547 // in ClsType; hence we wrap ClsType into an ElaboratedType. 4548 // NOTE: in particular, no wrap occurs if ClsType already is an 4549 // Elaborated, DependentName, or DependentTemplateSpecialization. 4550 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 4551 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 4552 break; 4553 } 4554 } else { 4555 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 4556 diag::err_illegal_decl_mempointer_in_nonclass) 4557 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 4558 << DeclType.Mem.Scope().getRange(); 4559 D.setInvalidType(true); 4560 } 4561 4562 if (!ClsType.isNull()) 4563 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, 4564 D.getIdentifier()); 4565 if (T.isNull()) { 4566 T = Context.IntTy; 4567 D.setInvalidType(true); 4568 } else if (DeclType.Mem.TypeQuals) { 4569 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 4570 } 4571 break; 4572 } 4573 4574 case DeclaratorChunk::Pipe: { 4575 T = S.BuildReadPipeType(T, DeclType.Loc); 4576 processTypeAttrs(state, T, TAL_DeclSpec, 4577 D.getDeclSpec().getAttributes().getList()); 4578 break; 4579 } 4580 } 4581 4582 if (T.isNull()) { 4583 D.setInvalidType(true); 4584 T = Context.IntTy; 4585 } 4586 4587 // See if there are any attributes on this declarator chunk. 4588 processTypeAttrs(state, T, TAL_DeclChunk, 4589 const_cast<AttributeList *>(DeclType.getAttrs())); 4590 } 4591 4592 // GNU warning -Wstrict-prototypes 4593 // Warn if a function declaration is without a prototype. 4594 // This warning is issued for all kinds of unprototyped function 4595 // declarations (i.e. function type typedef, function pointer etc.) 4596 // C99 6.7.5.3p14: 4597 // The empty list in a function declarator that is not part of a definition 4598 // of that function specifies that no information about the number or types 4599 // of the parameters is supplied. 4600 if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) { 4601 bool IsBlock = false; 4602 for (const DeclaratorChunk &DeclType : D.type_objects()) { 4603 switch (DeclType.Kind) { 4604 case DeclaratorChunk::BlockPointer: 4605 IsBlock = true; 4606 break; 4607 case DeclaratorChunk::Function: { 4608 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 4609 if (FTI.NumParams == 0) 4610 S.Diag(DeclType.Loc, diag::warn_strict_prototypes) 4611 << IsBlock 4612 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void"); 4613 IsBlock = false; 4614 break; 4615 } 4616 default: 4617 break; 4618 } 4619 } 4620 } 4621 4622 assert(!T.isNull() && "T must not be null after this point"); 4623 4624 if (LangOpts.CPlusPlus && T->isFunctionType()) { 4625 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 4626 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 4627 4628 // C++ 8.3.5p4: 4629 // A cv-qualifier-seq shall only be part of the function type 4630 // for a nonstatic member function, the function type to which a pointer 4631 // to member refers, or the top-level function type of a function typedef 4632 // declaration. 4633 // 4634 // Core issue 547 also allows cv-qualifiers on function types that are 4635 // top-level template type arguments. 4636 enum { NonMember, Member, DeductionGuide } Kind = NonMember; 4637 if (D.getName().getKind() == UnqualifiedId::IK_DeductionGuideName) 4638 Kind = DeductionGuide; 4639 else if (!D.getCXXScopeSpec().isSet()) { 4640 if ((D.getContext() == Declarator::MemberContext || 4641 D.getContext() == Declarator::LambdaExprContext) && 4642 !D.getDeclSpec().isFriendSpecified()) 4643 Kind = Member; 4644 } else { 4645 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 4646 if (!DC || DC->isRecord()) 4647 Kind = Member; 4648 } 4649 4650 // C++11 [dcl.fct]p6 (w/DR1417): 4651 // An attempt to specify a function type with a cv-qualifier-seq or a 4652 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 4653 // - the function type for a non-static member function, 4654 // - the function type to which a pointer to member refers, 4655 // - the top-level function type of a function typedef declaration or 4656 // alias-declaration, 4657 // - the type-id in the default argument of a type-parameter, or 4658 // - the type-id of a template-argument for a type-parameter 4659 // 4660 // FIXME: Checking this here is insufficient. We accept-invalid on: 4661 // 4662 // template<typename T> struct S { void f(T); }; 4663 // S<int() const> s; 4664 // 4665 // ... for instance. 4666 if (IsQualifiedFunction && 4667 !(Kind == Member && 4668 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 4669 !IsTypedefName && 4670 D.getContext() != Declarator::TemplateTypeArgContext) { 4671 SourceLocation Loc = D.getLocStart(); 4672 SourceRange RemovalRange; 4673 unsigned I; 4674 if (D.isFunctionDeclarator(I)) { 4675 SmallVector<SourceLocation, 4> RemovalLocs; 4676 const DeclaratorChunk &Chunk = D.getTypeObject(I); 4677 assert(Chunk.Kind == DeclaratorChunk::Function); 4678 if (Chunk.Fun.hasRefQualifier()) 4679 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 4680 if (Chunk.Fun.TypeQuals & Qualifiers::Const) 4681 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); 4682 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) 4683 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); 4684 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) 4685 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); 4686 if (!RemovalLocs.empty()) { 4687 std::sort(RemovalLocs.begin(), RemovalLocs.end(), 4688 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 4689 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 4690 Loc = RemovalLocs.front(); 4691 } 4692 } 4693 4694 S.Diag(Loc, diag::err_invalid_qualified_function_type) 4695 << Kind << D.isFunctionDeclarator() << T 4696 << getFunctionQualifiersAsString(FnTy) 4697 << FixItHint::CreateRemoval(RemovalRange); 4698 4699 // Strip the cv-qualifiers and ref-qualifiers from the type. 4700 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 4701 EPI.TypeQuals = 0; 4702 EPI.RefQualifier = RQ_None; 4703 4704 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), 4705 EPI); 4706 // Rebuild any parens around the identifier in the function type. 4707 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4708 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 4709 break; 4710 T = S.BuildParenType(T); 4711 } 4712 } 4713 } 4714 4715 // Apply any undistributed attributes from the declarator. 4716 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); 4717 4718 // Diagnose any ignored type attributes. 4719 state.diagnoseIgnoredTypeAttrs(T); 4720 4721 // C++0x [dcl.constexpr]p9: 4722 // A constexpr specifier used in an object declaration declares the object 4723 // as const. 4724 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 4725 T.addConst(); 4726 } 4727 4728 // If there was an ellipsis in the declarator, the declaration declares a 4729 // parameter pack whose type may be a pack expansion type. 4730 if (D.hasEllipsis()) { 4731 // C++0x [dcl.fct]p13: 4732 // A declarator-id or abstract-declarator containing an ellipsis shall 4733 // only be used in a parameter-declaration. Such a parameter-declaration 4734 // is a parameter pack (14.5.3). [...] 4735 switch (D.getContext()) { 4736 case Declarator::PrototypeContext: 4737 case Declarator::LambdaExprParameterContext: 4738 // C++0x [dcl.fct]p13: 4739 // [...] When it is part of a parameter-declaration-clause, the 4740 // parameter pack is a function parameter pack (14.5.3). The type T 4741 // of the declarator-id of the function parameter pack shall contain 4742 // a template parameter pack; each template parameter pack in T is 4743 // expanded by the function parameter pack. 4744 // 4745 // We represent function parameter packs as function parameters whose 4746 // type is a pack expansion. 4747 if (!T->containsUnexpandedParameterPack()) { 4748 S.Diag(D.getEllipsisLoc(), 4749 diag::err_function_parameter_pack_without_parameter_packs) 4750 << T << D.getSourceRange(); 4751 D.setEllipsisLoc(SourceLocation()); 4752 } else { 4753 T = Context.getPackExpansionType(T, None); 4754 } 4755 break; 4756 case Declarator::TemplateParamContext: 4757 // C++0x [temp.param]p15: 4758 // If a template-parameter is a [...] is a parameter-declaration that 4759 // declares a parameter pack (8.3.5), then the template-parameter is a 4760 // template parameter pack (14.5.3). 4761 // 4762 // Note: core issue 778 clarifies that, if there are any unexpanded 4763 // parameter packs in the type of the non-type template parameter, then 4764 // it expands those parameter packs. 4765 if (T->containsUnexpandedParameterPack()) 4766 T = Context.getPackExpansionType(T, None); 4767 else 4768 S.Diag(D.getEllipsisLoc(), 4769 LangOpts.CPlusPlus11 4770 ? diag::warn_cxx98_compat_variadic_templates 4771 : diag::ext_variadic_templates); 4772 break; 4773 4774 case Declarator::FileContext: 4775 case Declarator::KNRTypeListContext: 4776 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here? 4777 case Declarator::ObjCResultContext: // FIXME: special diagnostic here? 4778 case Declarator::TypeNameContext: 4779 case Declarator::FunctionalCastContext: 4780 case Declarator::CXXNewContext: 4781 case Declarator::AliasDeclContext: 4782 case Declarator::AliasTemplateContext: 4783 case Declarator::MemberContext: 4784 case Declarator::BlockContext: 4785 case Declarator::ForContext: 4786 case Declarator::InitStmtContext: 4787 case Declarator::ConditionContext: 4788 case Declarator::CXXCatchContext: 4789 case Declarator::ObjCCatchContext: 4790 case Declarator::BlockLiteralContext: 4791 case Declarator::LambdaExprContext: 4792 case Declarator::ConversionIdContext: 4793 case Declarator::TrailingReturnContext: 4794 case Declarator::TemplateTypeArgContext: 4795 // FIXME: We may want to allow parameter packs in block-literal contexts 4796 // in the future. 4797 S.Diag(D.getEllipsisLoc(), 4798 diag::err_ellipsis_in_declarator_not_parameter); 4799 D.setEllipsisLoc(SourceLocation()); 4800 break; 4801 } 4802 } 4803 4804 assert(!T.isNull() && "T must not be null at the end of this function"); 4805 if (D.isInvalidType()) 4806 return Context.getTrivialTypeSourceInfo(T); 4807 4808 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); 4809 } 4810 4811 /// GetTypeForDeclarator - Convert the type for the specified 4812 /// declarator to Type instances. 4813 /// 4814 /// The result of this call will never be null, but the associated 4815 /// type may be a null type if there's an unrecoverable error. 4816 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 4817 // Determine the type of the declarator. Not all forms of declarator 4818 // have a type. 4819 4820 TypeProcessingState state(*this, D); 4821 4822 TypeSourceInfo *ReturnTypeInfo = nullptr; 4823 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 4824 4825 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 4826 inferARCWriteback(state, T); 4827 4828 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 4829 } 4830 4831 static void transferARCOwnershipToDeclSpec(Sema &S, 4832 QualType &declSpecTy, 4833 Qualifiers::ObjCLifetime ownership) { 4834 if (declSpecTy->isObjCRetainableType() && 4835 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 4836 Qualifiers qs; 4837 qs.addObjCLifetime(ownership); 4838 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 4839 } 4840 } 4841 4842 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 4843 Qualifiers::ObjCLifetime ownership, 4844 unsigned chunkIndex) { 4845 Sema &S = state.getSema(); 4846 Declarator &D = state.getDeclarator(); 4847 4848 // Look for an explicit lifetime attribute. 4849 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 4850 for (const AttributeList *attr = chunk.getAttrs(); attr; 4851 attr = attr->getNext()) 4852 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 4853 return; 4854 4855 const char *attrStr = nullptr; 4856 switch (ownership) { 4857 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 4858 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 4859 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 4860 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 4861 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 4862 } 4863 4864 IdentifierLoc *Arg = new (S.Context) IdentifierLoc; 4865 Arg->Ident = &S.Context.Idents.get(attrStr); 4866 Arg->Loc = SourceLocation(); 4867 4868 ArgsUnion Args(Arg); 4869 4870 // If there wasn't one, add one (with an invalid source location 4871 // so that we don't make an AttributedType for it). 4872 AttributeList *attr = D.getAttributePool() 4873 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), 4874 /*scope*/ nullptr, SourceLocation(), 4875 /*args*/ &Args, 1, AttributeList::AS_GNU); 4876 spliceAttrIntoList(*attr, chunk.getAttrListRef()); 4877 4878 // TODO: mark whether we did this inference? 4879 } 4880 4881 /// \brief Used for transferring ownership in casts resulting in l-values. 4882 static void transferARCOwnership(TypeProcessingState &state, 4883 QualType &declSpecTy, 4884 Qualifiers::ObjCLifetime ownership) { 4885 Sema &S = state.getSema(); 4886 Declarator &D = state.getDeclarator(); 4887 4888 int inner = -1; 4889 bool hasIndirection = false; 4890 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4891 DeclaratorChunk &chunk = D.getTypeObject(i); 4892 switch (chunk.Kind) { 4893 case DeclaratorChunk::Paren: 4894 // Ignore parens. 4895 break; 4896 4897 case DeclaratorChunk::Array: 4898 case DeclaratorChunk::Reference: 4899 case DeclaratorChunk::Pointer: 4900 if (inner != -1) 4901 hasIndirection = true; 4902 inner = i; 4903 break; 4904 4905 case DeclaratorChunk::BlockPointer: 4906 if (inner != -1) 4907 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 4908 return; 4909 4910 case DeclaratorChunk::Function: 4911 case DeclaratorChunk::MemberPointer: 4912 case DeclaratorChunk::Pipe: 4913 return; 4914 } 4915 } 4916 4917 if (inner == -1) 4918 return; 4919 4920 DeclaratorChunk &chunk = D.getTypeObject(inner); 4921 if (chunk.Kind == DeclaratorChunk::Pointer) { 4922 if (declSpecTy->isObjCRetainableType()) 4923 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 4924 if (declSpecTy->isObjCObjectType() && hasIndirection) 4925 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 4926 } else { 4927 assert(chunk.Kind == DeclaratorChunk::Array || 4928 chunk.Kind == DeclaratorChunk::Reference); 4929 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 4930 } 4931 } 4932 4933 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 4934 TypeProcessingState state(*this, D); 4935 4936 TypeSourceInfo *ReturnTypeInfo = nullptr; 4937 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 4938 4939 if (getLangOpts().ObjC1) { 4940 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 4941 if (ownership != Qualifiers::OCL_None) 4942 transferARCOwnership(state, declSpecTy, ownership); 4943 } 4944 4945 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 4946 } 4947 4948 /// Map an AttributedType::Kind to an AttributeList::Kind. 4949 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 4950 switch (kind) { 4951 case AttributedType::attr_address_space: 4952 return AttributeList::AT_AddressSpace; 4953 case AttributedType::attr_regparm: 4954 return AttributeList::AT_Regparm; 4955 case AttributedType::attr_vector_size: 4956 return AttributeList::AT_VectorSize; 4957 case AttributedType::attr_neon_vector_type: 4958 return AttributeList::AT_NeonVectorType; 4959 case AttributedType::attr_neon_polyvector_type: 4960 return AttributeList::AT_NeonPolyVectorType; 4961 case AttributedType::attr_objc_gc: 4962 return AttributeList::AT_ObjCGC; 4963 case AttributedType::attr_objc_ownership: 4964 case AttributedType::attr_objc_inert_unsafe_unretained: 4965 return AttributeList::AT_ObjCOwnership; 4966 case AttributedType::attr_noreturn: 4967 return AttributeList::AT_NoReturn; 4968 case AttributedType::attr_cdecl: 4969 return AttributeList::AT_CDecl; 4970 case AttributedType::attr_fastcall: 4971 return AttributeList::AT_FastCall; 4972 case AttributedType::attr_stdcall: 4973 return AttributeList::AT_StdCall; 4974 case AttributedType::attr_thiscall: 4975 return AttributeList::AT_ThisCall; 4976 case AttributedType::attr_regcall: 4977 return AttributeList::AT_RegCall; 4978 case AttributedType::attr_pascal: 4979 return AttributeList::AT_Pascal; 4980 case AttributedType::attr_swiftcall: 4981 return AttributeList::AT_SwiftCall; 4982 case AttributedType::attr_vectorcall: 4983 return AttributeList::AT_VectorCall; 4984 case AttributedType::attr_pcs: 4985 case AttributedType::attr_pcs_vfp: 4986 return AttributeList::AT_Pcs; 4987 case AttributedType::attr_inteloclbicc: 4988 return AttributeList::AT_IntelOclBicc; 4989 case AttributedType::attr_ms_abi: 4990 return AttributeList::AT_MSABI; 4991 case AttributedType::attr_sysv_abi: 4992 return AttributeList::AT_SysVABI; 4993 case AttributedType::attr_preserve_most: 4994 return AttributeList::AT_PreserveMost; 4995 case AttributedType::attr_preserve_all: 4996 return AttributeList::AT_PreserveAll; 4997 case AttributedType::attr_ptr32: 4998 return AttributeList::AT_Ptr32; 4999 case AttributedType::attr_ptr64: 5000 return AttributeList::AT_Ptr64; 5001 case AttributedType::attr_sptr: 5002 return AttributeList::AT_SPtr; 5003 case AttributedType::attr_uptr: 5004 return AttributeList::AT_UPtr; 5005 case AttributedType::attr_nonnull: 5006 return AttributeList::AT_TypeNonNull; 5007 case AttributedType::attr_nullable: 5008 return AttributeList::AT_TypeNullable; 5009 case AttributedType::attr_null_unspecified: 5010 return AttributeList::AT_TypeNullUnspecified; 5011 case AttributedType::attr_objc_kindof: 5012 return AttributeList::AT_ObjCKindOf; 5013 } 5014 llvm_unreachable("unexpected attribute kind!"); 5015 } 5016 5017 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 5018 const AttributeList *attrs, 5019 const AttributeList *DeclAttrs = nullptr) { 5020 // DeclAttrs and attrs cannot be both empty. 5021 assert((attrs || DeclAttrs) && 5022 "no type attributes in the expected location!"); 5023 5024 AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind()); 5025 // Try to search for an attribute of matching kind in attrs list. 5026 while (attrs && attrs->getKind() != parsedKind) 5027 attrs = attrs->getNext(); 5028 if (!attrs) { 5029 // No matching type attribute in attrs list found. 5030 // Try searching through C++11 attributes in the declarator attribute list. 5031 while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() || 5032 DeclAttrs->getKind() != parsedKind)) 5033 DeclAttrs = DeclAttrs->getNext(); 5034 attrs = DeclAttrs; 5035 } 5036 5037 assert(attrs && "no matching type attribute in expected location!"); 5038 5039 TL.setAttrNameLoc(attrs->getLoc()); 5040 if (TL.hasAttrExprOperand()) { 5041 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind"); 5042 TL.setAttrExprOperand(attrs->getArgAsExpr(0)); 5043 } else if (TL.hasAttrEnumOperand()) { 5044 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) && 5045 "unexpected attribute operand kind"); 5046 if (attrs->isArgIdent(0)) 5047 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc); 5048 else 5049 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc()); 5050 } 5051 5052 // FIXME: preserve this information to here. 5053 if (TL.hasAttrOperand()) 5054 TL.setAttrOperandParensRange(SourceRange()); 5055 } 5056 5057 namespace { 5058 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 5059 ASTContext &Context; 5060 const DeclSpec &DS; 5061 5062 public: 5063 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 5064 : Context(Context), DS(DS) {} 5065 5066 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 5067 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 5068 Visit(TL.getModifiedLoc()); 5069 } 5070 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 5071 Visit(TL.getUnqualifiedLoc()); 5072 } 5073 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 5074 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 5075 } 5076 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 5077 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 5078 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 5079 // addition field. What we have is good enough for dispay of location 5080 // of 'fixit' on interface name. 5081 TL.setNameEndLoc(DS.getLocEnd()); 5082 } 5083 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 5084 TypeSourceInfo *RepTInfo = nullptr; 5085 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 5086 TL.copy(RepTInfo->getTypeLoc()); 5087 } 5088 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 5089 TypeSourceInfo *RepTInfo = nullptr; 5090 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 5091 TL.copy(RepTInfo->getTypeLoc()); 5092 } 5093 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 5094 TypeSourceInfo *TInfo = nullptr; 5095 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5096 5097 // If we got no declarator info from previous Sema routines, 5098 // just fill with the typespec loc. 5099 if (!TInfo) { 5100 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 5101 return; 5102 } 5103 5104 TypeLoc OldTL = TInfo->getTypeLoc(); 5105 if (TInfo->getType()->getAs<ElaboratedType>()) { 5106 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 5107 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 5108 .castAs<TemplateSpecializationTypeLoc>(); 5109 TL.copy(NamedTL); 5110 } else { 5111 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 5112 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); 5113 } 5114 5115 } 5116 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 5117 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 5118 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 5119 TL.setParensRange(DS.getTypeofParensRange()); 5120 } 5121 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 5122 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 5123 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 5124 TL.setParensRange(DS.getTypeofParensRange()); 5125 assert(DS.getRepAsType()); 5126 TypeSourceInfo *TInfo = nullptr; 5127 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5128 TL.setUnderlyingTInfo(TInfo); 5129 } 5130 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 5131 // FIXME: This holds only because we only have one unary transform. 5132 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 5133 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 5134 TL.setParensRange(DS.getTypeofParensRange()); 5135 assert(DS.getRepAsType()); 5136 TypeSourceInfo *TInfo = nullptr; 5137 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5138 TL.setUnderlyingTInfo(TInfo); 5139 } 5140 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 5141 // By default, use the source location of the type specifier. 5142 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 5143 if (TL.needsExtraLocalData()) { 5144 // Set info for the written builtin specifiers. 5145 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 5146 // Try to have a meaningful source location. 5147 if (TL.getWrittenSignSpec() != TSS_unspecified) 5148 TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); 5149 if (TL.getWrittenWidthSpec() != TSW_unspecified) 5150 TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); 5151 } 5152 } 5153 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 5154 ElaboratedTypeKeyword Keyword 5155 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 5156 if (DS.getTypeSpecType() == TST_typename) { 5157 TypeSourceInfo *TInfo = nullptr; 5158 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5159 if (TInfo) { 5160 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 5161 return; 5162 } 5163 } 5164 TL.setElaboratedKeywordLoc(Keyword != ETK_None 5165 ? DS.getTypeSpecTypeLoc() 5166 : SourceLocation()); 5167 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 5168 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 5169 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 5170 } 5171 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 5172 assert(DS.getTypeSpecType() == TST_typename); 5173 TypeSourceInfo *TInfo = nullptr; 5174 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5175 assert(TInfo); 5176 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 5177 } 5178 void VisitDependentTemplateSpecializationTypeLoc( 5179 DependentTemplateSpecializationTypeLoc TL) { 5180 assert(DS.getTypeSpecType() == TST_typename); 5181 TypeSourceInfo *TInfo = nullptr; 5182 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5183 assert(TInfo); 5184 TL.copy( 5185 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 5186 } 5187 void VisitTagTypeLoc(TagTypeLoc TL) { 5188 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 5189 } 5190 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 5191 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 5192 // or an _Atomic qualifier. 5193 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 5194 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 5195 TL.setParensRange(DS.getTypeofParensRange()); 5196 5197 TypeSourceInfo *TInfo = nullptr; 5198 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5199 assert(TInfo); 5200 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 5201 } else { 5202 TL.setKWLoc(DS.getAtomicSpecLoc()); 5203 // No parens, to indicate this was spelled as an _Atomic qualifier. 5204 TL.setParensRange(SourceRange()); 5205 Visit(TL.getValueLoc()); 5206 } 5207 } 5208 5209 void VisitPipeTypeLoc(PipeTypeLoc TL) { 5210 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 5211 5212 TypeSourceInfo *TInfo = nullptr; 5213 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 5214 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 5215 } 5216 5217 void VisitTypeLoc(TypeLoc TL) { 5218 // FIXME: add other typespec types and change this to an assert. 5219 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 5220 } 5221 }; 5222 5223 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 5224 ASTContext &Context; 5225 const DeclaratorChunk &Chunk; 5226 5227 public: 5228 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 5229 : Context(Context), Chunk(Chunk) {} 5230 5231 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 5232 llvm_unreachable("qualified type locs not expected here!"); 5233 } 5234 void VisitDecayedTypeLoc(DecayedTypeLoc TL) { 5235 llvm_unreachable("decayed type locs not expected here!"); 5236 } 5237 5238 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 5239 fillAttributedTypeLoc(TL, Chunk.getAttrs()); 5240 } 5241 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 5242 // nothing 5243 } 5244 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 5245 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 5246 TL.setCaretLoc(Chunk.Loc); 5247 } 5248 void VisitPointerTypeLoc(PointerTypeLoc TL) { 5249 assert(Chunk.Kind == DeclaratorChunk::Pointer); 5250 TL.setStarLoc(Chunk.Loc); 5251 } 5252 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 5253 assert(Chunk.Kind == DeclaratorChunk::Pointer); 5254 TL.setStarLoc(Chunk.Loc); 5255 } 5256 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 5257 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 5258 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 5259 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 5260 5261 const Type* ClsTy = TL.getClass(); 5262 QualType ClsQT = QualType(ClsTy, 0); 5263 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 5264 // Now copy source location info into the type loc component. 5265 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 5266 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 5267 case NestedNameSpecifier::Identifier: 5268 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 5269 { 5270 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 5271 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 5272 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 5273 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 5274 } 5275 break; 5276 5277 case NestedNameSpecifier::TypeSpec: 5278 case NestedNameSpecifier::TypeSpecWithTemplate: 5279 if (isa<ElaboratedType>(ClsTy)) { 5280 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 5281 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 5282 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 5283 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 5284 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 5285 } else { 5286 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 5287 } 5288 break; 5289 5290 case NestedNameSpecifier::Namespace: 5291 case NestedNameSpecifier::NamespaceAlias: 5292 case NestedNameSpecifier::Global: 5293 case NestedNameSpecifier::Super: 5294 llvm_unreachable("Nested-name-specifier must name a type"); 5295 } 5296 5297 // Finally fill in MemberPointerLocInfo fields. 5298 TL.setStarLoc(Chunk.Loc); 5299 TL.setClassTInfo(ClsTInfo); 5300 } 5301 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 5302 assert(Chunk.Kind == DeclaratorChunk::Reference); 5303 // 'Amp' is misleading: this might have been originally 5304 /// spelled with AmpAmp. 5305 TL.setAmpLoc(Chunk.Loc); 5306 } 5307 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 5308 assert(Chunk.Kind == DeclaratorChunk::Reference); 5309 assert(!Chunk.Ref.LValueRef); 5310 TL.setAmpAmpLoc(Chunk.Loc); 5311 } 5312 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 5313 assert(Chunk.Kind == DeclaratorChunk::Array); 5314 TL.setLBracketLoc(Chunk.Loc); 5315 TL.setRBracketLoc(Chunk.EndLoc); 5316 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 5317 } 5318 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 5319 assert(Chunk.Kind == DeclaratorChunk::Function); 5320 TL.setLocalRangeBegin(Chunk.Loc); 5321 TL.setLocalRangeEnd(Chunk.EndLoc); 5322 5323 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 5324 TL.setLParenLoc(FTI.getLParenLoc()); 5325 TL.setRParenLoc(FTI.getRParenLoc()); 5326 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { 5327 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 5328 TL.setParam(tpi++, Param); 5329 } 5330 TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); 5331 } 5332 void VisitParenTypeLoc(ParenTypeLoc TL) { 5333 assert(Chunk.Kind == DeclaratorChunk::Paren); 5334 TL.setLParenLoc(Chunk.Loc); 5335 TL.setRParenLoc(Chunk.EndLoc); 5336 } 5337 void VisitPipeTypeLoc(PipeTypeLoc TL) { 5338 assert(Chunk.Kind == DeclaratorChunk::Pipe); 5339 TL.setKWLoc(Chunk.Loc); 5340 } 5341 5342 void VisitTypeLoc(TypeLoc TL) { 5343 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 5344 } 5345 }; 5346 } // end anonymous namespace 5347 5348 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 5349 SourceLocation Loc; 5350 switch (Chunk.Kind) { 5351 case DeclaratorChunk::Function: 5352 case DeclaratorChunk::Array: 5353 case DeclaratorChunk::Paren: 5354 case DeclaratorChunk::Pipe: 5355 llvm_unreachable("cannot be _Atomic qualified"); 5356 5357 case DeclaratorChunk::Pointer: 5358 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); 5359 break; 5360 5361 case DeclaratorChunk::BlockPointer: 5362 case DeclaratorChunk::Reference: 5363 case DeclaratorChunk::MemberPointer: 5364 // FIXME: Provide a source location for the _Atomic keyword. 5365 break; 5366 } 5367 5368 ATL.setKWLoc(Loc); 5369 ATL.setParensRange(SourceRange()); 5370 } 5371 5372 /// \brief Create and instantiate a TypeSourceInfo with type source information. 5373 /// 5374 /// \param T QualType referring to the type as written in source code. 5375 /// 5376 /// \param ReturnTypeInfo For declarators whose return type does not show 5377 /// up in the normal place in the declaration specifiers (such as a C++ 5378 /// conversion function), this pointer will refer to a type source information 5379 /// for that return type. 5380 TypeSourceInfo * 5381 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 5382 TypeSourceInfo *ReturnTypeInfo) { 5383 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 5384 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 5385 const AttributeList *DeclAttrs = D.getAttributes(); 5386 5387 // Handle parameter packs whose type is a pack expansion. 5388 if (isa<PackExpansionType>(T)) { 5389 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 5390 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 5391 } 5392 5393 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5394 // An AtomicTypeLoc might be produced by an atomic qualifier in this 5395 // declarator chunk. 5396 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 5397 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 5398 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 5399 } 5400 5401 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 5402 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs); 5403 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 5404 } 5405 5406 // FIXME: Ordering here? 5407 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) 5408 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 5409 5410 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 5411 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 5412 } 5413 5414 // If we have different source information for the return type, use 5415 // that. This really only applies to C++ conversion functions. 5416 if (ReturnTypeInfo) { 5417 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 5418 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 5419 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 5420 } else { 5421 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 5422 } 5423 5424 return TInfo; 5425 } 5426 5427 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 5428 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 5429 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 5430 // and Sema during declaration parsing. Try deallocating/caching them when 5431 // it's appropriate, instead of allocating them and keeping them around. 5432 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 5433 TypeAlignment); 5434 new (LocT) LocInfoType(T, TInfo); 5435 assert(LocT->getTypeClass() != T->getTypeClass() && 5436 "LocInfoType's TypeClass conflicts with an existing Type class"); 5437 return ParsedType::make(QualType(LocT, 0)); 5438 } 5439 5440 void LocInfoType::getAsStringInternal(std::string &Str, 5441 const PrintingPolicy &Policy) const { 5442 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 5443 " was used directly instead of getting the QualType through" 5444 " GetTypeFromParser"); 5445 } 5446 5447 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 5448 // C99 6.7.6: Type names have no identifier. This is already validated by 5449 // the parser. 5450 assert(D.getIdentifier() == nullptr && 5451 "Type name should have no identifier!"); 5452 5453 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5454 QualType T = TInfo->getType(); 5455 if (D.isInvalidType()) 5456 return true; 5457 5458 // Make sure there are no unused decl attributes on the declarator. 5459 // We don't want to do this for ObjC parameters because we're going 5460 // to apply them to the actual parameter declaration. 5461 // Likewise, we don't want to do this for alias declarations, because 5462 // we are actually going to build a declaration from this eventually. 5463 if (D.getContext() != Declarator::ObjCParameterContext && 5464 D.getContext() != Declarator::AliasDeclContext && 5465 D.getContext() != Declarator::AliasTemplateContext) 5466 checkUnusedDeclAttributes(D); 5467 5468 if (getLangOpts().CPlusPlus) { 5469 // Check that there are no default arguments (C++ only). 5470 CheckExtraCXXDefaultArguments(D); 5471 } 5472 5473 return CreateParsedType(T, TInfo); 5474 } 5475 5476 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 5477 QualType T = Context.getObjCInstanceType(); 5478 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 5479 return CreateParsedType(T, TInfo); 5480 } 5481 5482 //===----------------------------------------------------------------------===// 5483 // Type Attribute Processing 5484 //===----------------------------------------------------------------------===// 5485 5486 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 5487 /// specified type. The attribute contains 1 argument, the id of the address 5488 /// space for the type. 5489 static void HandleAddressSpaceTypeAttribute(QualType &Type, 5490 const AttributeList &Attr, Sema &S){ 5491 5492 // If this type is already address space qualified, reject it. 5493 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by 5494 // qualifiers for two or more different address spaces." 5495 if (Type.getAddressSpace()) { 5496 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 5497 Attr.setInvalid(); 5498 return; 5499 } 5500 5501 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 5502 // qualified by an address-space qualifier." 5503 if (Type->isFunctionType()) { 5504 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 5505 Attr.setInvalid(); 5506 return; 5507 } 5508 5509 unsigned ASIdx; 5510 if (Attr.getKind() == AttributeList::AT_AddressSpace) { 5511 // Check the attribute arguments. 5512 if (Attr.getNumArgs() != 1) { 5513 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 5514 << Attr.getName() << 1; 5515 Attr.setInvalid(); 5516 return; 5517 } 5518 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 5519 llvm::APSInt addrSpace(32); 5520 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 5521 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 5522 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 5523 << Attr.getName() << AANT_ArgumentIntegerConstant 5524 << ASArgExpr->getSourceRange(); 5525 Attr.setInvalid(); 5526 return; 5527 } 5528 5529 // Bounds checking. 5530 if (addrSpace.isSigned()) { 5531 if (addrSpace.isNegative()) { 5532 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 5533 << ASArgExpr->getSourceRange(); 5534 Attr.setInvalid(); 5535 return; 5536 } 5537 addrSpace.setIsSigned(false); 5538 } 5539 llvm::APSInt max(addrSpace.getBitWidth()); 5540 max = Qualifiers::MaxAddressSpace - LangAS::FirstTargetAddressSpace; 5541 if (addrSpace > max) { 5542 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 5543 << (unsigned)max.getZExtValue() << ASArgExpr->getSourceRange(); 5544 Attr.setInvalid(); 5545 return; 5546 } 5547 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()) + 5548 LangAS::FirstTargetAddressSpace; 5549 } else { 5550 // The keyword-based type attributes imply which address space to use. 5551 switch (Attr.getKind()) { 5552 case AttributeList::AT_OpenCLGlobalAddressSpace: 5553 ASIdx = LangAS::opencl_global; break; 5554 case AttributeList::AT_OpenCLLocalAddressSpace: 5555 ASIdx = LangAS::opencl_local; break; 5556 case AttributeList::AT_OpenCLConstantAddressSpace: 5557 ASIdx = LangAS::opencl_constant; break; 5558 case AttributeList::AT_OpenCLGenericAddressSpace: 5559 ASIdx = LangAS::opencl_generic; break; 5560 default: 5561 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace); 5562 ASIdx = 0; break; 5563 } 5564 } 5565 5566 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 5567 } 5568 5569 /// Does this type have a "direct" ownership qualifier? That is, 5570 /// is it written like "__strong id", as opposed to something like 5571 /// "typeof(foo)", where that happens to be strong? 5572 static bool hasDirectOwnershipQualifier(QualType type) { 5573 // Fast path: no qualifier at all. 5574 assert(type.getQualifiers().hasObjCLifetime()); 5575 5576 while (true) { 5577 // __strong id 5578 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { 5579 if (attr->getAttrKind() == AttributedType::attr_objc_ownership) 5580 return true; 5581 5582 type = attr->getModifiedType(); 5583 5584 // X *__strong (...) 5585 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { 5586 type = paren->getInnerType(); 5587 5588 // That's it for things we want to complain about. In particular, 5589 // we do not want to look through typedefs, typeof(expr), 5590 // typeof(type), or any other way that the type is somehow 5591 // abstracted. 5592 } else { 5593 5594 return false; 5595 } 5596 } 5597 } 5598 5599 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 5600 /// attribute on the specified type. 5601 /// 5602 /// Returns 'true' if the attribute was handled. 5603 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 5604 AttributeList &attr, 5605 QualType &type) { 5606 bool NonObjCPointer = false; 5607 5608 if (!type->isDependentType() && !type->isUndeducedType()) { 5609 if (const PointerType *ptr = type->getAs<PointerType>()) { 5610 QualType pointee = ptr->getPointeeType(); 5611 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 5612 return false; 5613 // It is important not to lose the source info that there was an attribute 5614 // applied to non-objc pointer. We will create an attributed type but 5615 // its type will be the same as the original type. 5616 NonObjCPointer = true; 5617 } else if (!type->isObjCRetainableType()) { 5618 return false; 5619 } 5620 5621 // Don't accept an ownership attribute in the declspec if it would 5622 // just be the return type of a block pointer. 5623 if (state.isProcessingDeclSpec()) { 5624 Declarator &D = state.getDeclarator(); 5625 if (maybeMovePastReturnType(D, D.getNumTypeObjects(), 5626 /*onlyBlockPointers=*/true)) 5627 return false; 5628 } 5629 } 5630 5631 Sema &S = state.getSema(); 5632 SourceLocation AttrLoc = attr.getLoc(); 5633 if (AttrLoc.isMacroID()) 5634 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first; 5635 5636 if (!attr.isArgIdent(0)) { 5637 S.Diag(AttrLoc, diag::err_attribute_argument_type) 5638 << attr.getName() << AANT_ArgumentString; 5639 attr.setInvalid(); 5640 return true; 5641 } 5642 5643 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 5644 Qualifiers::ObjCLifetime lifetime; 5645 if (II->isStr("none")) 5646 lifetime = Qualifiers::OCL_ExplicitNone; 5647 else if (II->isStr("strong")) 5648 lifetime = Qualifiers::OCL_Strong; 5649 else if (II->isStr("weak")) 5650 lifetime = Qualifiers::OCL_Weak; 5651 else if (II->isStr("autoreleasing")) 5652 lifetime = Qualifiers::OCL_Autoreleasing; 5653 else { 5654 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 5655 << attr.getName() << II; 5656 attr.setInvalid(); 5657 return true; 5658 } 5659 5660 // Just ignore lifetime attributes other than __weak and __unsafe_unretained 5661 // outside of ARC mode. 5662 if (!S.getLangOpts().ObjCAutoRefCount && 5663 lifetime != Qualifiers::OCL_Weak && 5664 lifetime != Qualifiers::OCL_ExplicitNone) { 5665 return true; 5666 } 5667 5668 SplitQualType underlyingType = type.split(); 5669 5670 // Check for redundant/conflicting ownership qualifiers. 5671 if (Qualifiers::ObjCLifetime previousLifetime 5672 = type.getQualifiers().getObjCLifetime()) { 5673 // If it's written directly, that's an error. 5674 if (hasDirectOwnershipQualifier(type)) { 5675 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 5676 << type; 5677 return true; 5678 } 5679 5680 // Otherwise, if the qualifiers actually conflict, pull sugar off 5681 // and remove the ObjCLifetime qualifiers. 5682 if (previousLifetime != lifetime) { 5683 // It's possible to have multiple local ObjCLifetime qualifiers. We 5684 // can't stop after we reach a type that is directly qualified. 5685 const Type *prevTy = nullptr; 5686 while (!prevTy || prevTy != underlyingType.Ty) { 5687 prevTy = underlyingType.Ty; 5688 underlyingType = underlyingType.getSingleStepDesugaredType(); 5689 } 5690 underlyingType.Quals.removeObjCLifetime(); 5691 } 5692 } 5693 5694 underlyingType.Quals.addObjCLifetime(lifetime); 5695 5696 if (NonObjCPointer) { 5697 StringRef name = attr.getName()->getName(); 5698 switch (lifetime) { 5699 case Qualifiers::OCL_None: 5700 case Qualifiers::OCL_ExplicitNone: 5701 break; 5702 case Qualifiers::OCL_Strong: name = "__strong"; break; 5703 case Qualifiers::OCL_Weak: name = "__weak"; break; 5704 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 5705 } 5706 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name 5707 << TDS_ObjCObjOrBlock << type; 5708 } 5709 5710 // Don't actually add the __unsafe_unretained qualifier in non-ARC files, 5711 // because having both 'T' and '__unsafe_unretained T' exist in the type 5712 // system causes unfortunate widespread consistency problems. (For example, 5713 // they're not considered compatible types, and we mangle them identicially 5714 // as template arguments.) These problems are all individually fixable, 5715 // but it's easier to just not add the qualifier and instead sniff it out 5716 // in specific places using isObjCInertUnsafeUnretainedType(). 5717 // 5718 // Doing this does means we miss some trivial consistency checks that 5719 // would've triggered in ARC, but that's better than trying to solve all 5720 // the coexistence problems with __unsafe_unretained. 5721 if (!S.getLangOpts().ObjCAutoRefCount && 5722 lifetime == Qualifiers::OCL_ExplicitNone) { 5723 type = S.Context.getAttributedType( 5724 AttributedType::attr_objc_inert_unsafe_unretained, 5725 type, type); 5726 return true; 5727 } 5728 5729 QualType origType = type; 5730 if (!NonObjCPointer) 5731 type = S.Context.getQualifiedType(underlyingType); 5732 5733 // If we have a valid source location for the attribute, use an 5734 // AttributedType instead. 5735 if (AttrLoc.isValid()) 5736 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, 5737 origType, type); 5738 5739 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, 5740 unsigned diagnostic, QualType type) { 5741 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 5742 S.DelayedDiagnostics.add( 5743 sema::DelayedDiagnostic::makeForbiddenType( 5744 S.getSourceManager().getExpansionLoc(loc), 5745 diagnostic, type, /*ignored*/ 0)); 5746 } else { 5747 S.Diag(loc, diagnostic); 5748 } 5749 }; 5750 5751 // Sometimes, __weak isn't allowed. 5752 if (lifetime == Qualifiers::OCL_Weak && 5753 !S.getLangOpts().ObjCWeak && !NonObjCPointer) { 5754 5755 // Use a specialized diagnostic if the runtime just doesn't support them. 5756 unsigned diagnostic = 5757 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled 5758 : diag::err_arc_weak_no_runtime); 5759 5760 // In any case, delay the diagnostic until we know what we're parsing. 5761 diagnoseOrDelay(S, AttrLoc, diagnostic, type); 5762 5763 attr.setInvalid(); 5764 return true; 5765 } 5766 5767 // Forbid __weak for class objects marked as 5768 // objc_arc_weak_reference_unavailable 5769 if (lifetime == Qualifiers::OCL_Weak) { 5770 if (const ObjCObjectPointerType *ObjT = 5771 type->getAs<ObjCObjectPointerType>()) { 5772 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 5773 if (Class->isArcWeakrefUnavailable()) { 5774 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 5775 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 5776 diag::note_class_declared); 5777 } 5778 } 5779 } 5780 } 5781 5782 return true; 5783 } 5784 5785 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 5786 /// attribute on the specified type. Returns true to indicate that 5787 /// the attribute was handled, false to indicate that the type does 5788 /// not permit the attribute. 5789 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 5790 AttributeList &attr, 5791 QualType &type) { 5792 Sema &S = state.getSema(); 5793 5794 // Delay if this isn't some kind of pointer. 5795 if (!type->isPointerType() && 5796 !type->isObjCObjectPointerType() && 5797 !type->isBlockPointerType()) 5798 return false; 5799 5800 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 5801 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 5802 attr.setInvalid(); 5803 return true; 5804 } 5805 5806 // Check the attribute arguments. 5807 if (!attr.isArgIdent(0)) { 5808 S.Diag(attr.getLoc(), diag::err_attribute_argument_type) 5809 << attr.getName() << AANT_ArgumentString; 5810 attr.setInvalid(); 5811 return true; 5812 } 5813 Qualifiers::GC GCAttr; 5814 if (attr.getNumArgs() > 1) { 5815 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) 5816 << attr.getName() << 1; 5817 attr.setInvalid(); 5818 return true; 5819 } 5820 5821 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 5822 if (II->isStr("weak")) 5823 GCAttr = Qualifiers::Weak; 5824 else if (II->isStr("strong")) 5825 GCAttr = Qualifiers::Strong; 5826 else { 5827 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 5828 << attr.getName() << II; 5829 attr.setInvalid(); 5830 return true; 5831 } 5832 5833 QualType origType = type; 5834 type = S.Context.getObjCGCQualType(origType, GCAttr); 5835 5836 // Make an attributed type to preserve the source information. 5837 if (attr.getLoc().isValid()) 5838 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 5839 origType, type); 5840 5841 return true; 5842 } 5843 5844 namespace { 5845 /// A helper class to unwrap a type down to a function for the 5846 /// purposes of applying attributes there. 5847 /// 5848 /// Use: 5849 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 5850 /// if (unwrapped.isFunctionType()) { 5851 /// const FunctionType *fn = unwrapped.get(); 5852 /// // change fn somehow 5853 /// T = unwrapped.wrap(fn); 5854 /// } 5855 struct FunctionTypeUnwrapper { 5856 enum WrapKind { 5857 Desugar, 5858 Attributed, 5859 Parens, 5860 Pointer, 5861 BlockPointer, 5862 Reference, 5863 MemberPointer 5864 }; 5865 5866 QualType Original; 5867 const FunctionType *Fn; 5868 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 5869 5870 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 5871 while (true) { 5872 const Type *Ty = T.getTypePtr(); 5873 if (isa<FunctionType>(Ty)) { 5874 Fn = cast<FunctionType>(Ty); 5875 return; 5876 } else if (isa<ParenType>(Ty)) { 5877 T = cast<ParenType>(Ty)->getInnerType(); 5878 Stack.push_back(Parens); 5879 } else if (isa<PointerType>(Ty)) { 5880 T = cast<PointerType>(Ty)->getPointeeType(); 5881 Stack.push_back(Pointer); 5882 } else if (isa<BlockPointerType>(Ty)) { 5883 T = cast<BlockPointerType>(Ty)->getPointeeType(); 5884 Stack.push_back(BlockPointer); 5885 } else if (isa<MemberPointerType>(Ty)) { 5886 T = cast<MemberPointerType>(Ty)->getPointeeType(); 5887 Stack.push_back(MemberPointer); 5888 } else if (isa<ReferenceType>(Ty)) { 5889 T = cast<ReferenceType>(Ty)->getPointeeType(); 5890 Stack.push_back(Reference); 5891 } else if (isa<AttributedType>(Ty)) { 5892 T = cast<AttributedType>(Ty)->getEquivalentType(); 5893 Stack.push_back(Attributed); 5894 } else { 5895 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 5896 if (Ty == DTy) { 5897 Fn = nullptr; 5898 return; 5899 } 5900 5901 T = QualType(DTy, 0); 5902 Stack.push_back(Desugar); 5903 } 5904 } 5905 } 5906 5907 bool isFunctionType() const { return (Fn != nullptr); } 5908 const FunctionType *get() const { return Fn; } 5909 5910 QualType wrap(Sema &S, const FunctionType *New) { 5911 // If T wasn't modified from the unwrapped type, do nothing. 5912 if (New == get()) return Original; 5913 5914 Fn = New; 5915 return wrap(S.Context, Original, 0); 5916 } 5917 5918 private: 5919 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 5920 if (I == Stack.size()) 5921 return C.getQualifiedType(Fn, Old.getQualifiers()); 5922 5923 // Build up the inner type, applying the qualifiers from the old 5924 // type to the new type. 5925 SplitQualType SplitOld = Old.split(); 5926 5927 // As a special case, tail-recurse if there are no qualifiers. 5928 if (SplitOld.Quals.empty()) 5929 return wrap(C, SplitOld.Ty, I); 5930 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 5931 } 5932 5933 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 5934 if (I == Stack.size()) return QualType(Fn, 0); 5935 5936 switch (static_cast<WrapKind>(Stack[I++])) { 5937 case Desugar: 5938 // This is the point at which we potentially lose source 5939 // information. 5940 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 5941 5942 case Attributed: 5943 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); 5944 5945 case Parens: { 5946 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 5947 return C.getParenType(New); 5948 } 5949 5950 case Pointer: { 5951 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 5952 return C.getPointerType(New); 5953 } 5954 5955 case BlockPointer: { 5956 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 5957 return C.getBlockPointerType(New); 5958 } 5959 5960 case MemberPointer: { 5961 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 5962 QualType New = wrap(C, OldMPT->getPointeeType(), I); 5963 return C.getMemberPointerType(New, OldMPT->getClass()); 5964 } 5965 5966 case Reference: { 5967 const ReferenceType *OldRef = cast<ReferenceType>(Old); 5968 QualType New = wrap(C, OldRef->getPointeeType(), I); 5969 if (isa<LValueReferenceType>(OldRef)) 5970 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 5971 else 5972 return C.getRValueReferenceType(New); 5973 } 5974 } 5975 5976 llvm_unreachable("unknown wrapping kind"); 5977 } 5978 }; 5979 } // end anonymous namespace 5980 5981 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, 5982 AttributeList &Attr, 5983 QualType &Type) { 5984 Sema &S = State.getSema(); 5985 5986 AttributeList::Kind Kind = Attr.getKind(); 5987 QualType Desugared = Type; 5988 const AttributedType *AT = dyn_cast<AttributedType>(Type); 5989 while (AT) { 5990 AttributedType::Kind CurAttrKind = AT->getAttrKind(); 5991 5992 // You cannot specify duplicate type attributes, so if the attribute has 5993 // already been applied, flag it. 5994 if (getAttrListKind(CurAttrKind) == Kind) { 5995 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact) 5996 << Attr.getName(); 5997 return true; 5998 } 5999 6000 // You cannot have both __sptr and __uptr on the same type, nor can you 6001 // have __ptr32 and __ptr64. 6002 if ((CurAttrKind == AttributedType::attr_ptr32 && 6003 Kind == AttributeList::AT_Ptr64) || 6004 (CurAttrKind == AttributedType::attr_ptr64 && 6005 Kind == AttributeList::AT_Ptr32)) { 6006 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 6007 << "'__ptr32'" << "'__ptr64'"; 6008 return true; 6009 } else if ((CurAttrKind == AttributedType::attr_sptr && 6010 Kind == AttributeList::AT_UPtr) || 6011 (CurAttrKind == AttributedType::attr_uptr && 6012 Kind == AttributeList::AT_SPtr)) { 6013 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 6014 << "'__sptr'" << "'__uptr'"; 6015 return true; 6016 } 6017 6018 Desugared = AT->getEquivalentType(); 6019 AT = dyn_cast<AttributedType>(Desugared); 6020 } 6021 6022 // Pointer type qualifiers can only operate on pointer types, but not 6023 // pointer-to-member types. 6024 if (!isa<PointerType>(Desugared)) { 6025 if (Type->isMemberPointerType()) 6026 S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers) 6027 << Attr.getName(); 6028 else 6029 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only) 6030 << Attr.getName() << 0; 6031 return true; 6032 } 6033 6034 AttributedType::Kind TAK; 6035 switch (Kind) { 6036 default: llvm_unreachable("Unknown attribute kind"); 6037 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break; 6038 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break; 6039 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break; 6040 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break; 6041 } 6042 6043 Type = S.Context.getAttributedType(TAK, Type, Type); 6044 return false; 6045 } 6046 6047 bool Sema::checkNullabilityTypeSpecifier(QualType &type, 6048 NullabilityKind nullability, 6049 SourceLocation nullabilityLoc, 6050 bool isContextSensitive, 6051 bool allowOnArrayType) { 6052 recordNullabilitySeen(*this, nullabilityLoc); 6053 6054 // Check for existing nullability attributes on the type. 6055 QualType desugared = type; 6056 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { 6057 // Check whether there is already a null 6058 if (auto existingNullability = attributed->getImmediateNullability()) { 6059 // Duplicated nullability. 6060 if (nullability == *existingNullability) { 6061 Diag(nullabilityLoc, diag::warn_nullability_duplicate) 6062 << DiagNullabilityKind(nullability, isContextSensitive) 6063 << FixItHint::CreateRemoval(nullabilityLoc); 6064 6065 break; 6066 } 6067 6068 // Conflicting nullability. 6069 Diag(nullabilityLoc, diag::err_nullability_conflicting) 6070 << DiagNullabilityKind(nullability, isContextSensitive) 6071 << DiagNullabilityKind(*existingNullability, false); 6072 return true; 6073 } 6074 6075 desugared = attributed->getModifiedType(); 6076 } 6077 6078 // If there is already a different nullability specifier, complain. 6079 // This (unlike the code above) looks through typedefs that might 6080 // have nullability specifiers on them, which means we cannot 6081 // provide a useful Fix-It. 6082 if (auto existingNullability = desugared->getNullability(Context)) { 6083 if (nullability != *existingNullability) { 6084 Diag(nullabilityLoc, diag::err_nullability_conflicting) 6085 << DiagNullabilityKind(nullability, isContextSensitive) 6086 << DiagNullabilityKind(*existingNullability, false); 6087 6088 // Try to find the typedef with the existing nullability specifier. 6089 if (auto typedefType = desugared->getAs<TypedefType>()) { 6090 TypedefNameDecl *typedefDecl = typedefType->getDecl(); 6091 QualType underlyingType = typedefDecl->getUnderlyingType(); 6092 if (auto typedefNullability 6093 = AttributedType::stripOuterNullability(underlyingType)) { 6094 if (*typedefNullability == *existingNullability) { 6095 Diag(typedefDecl->getLocation(), diag::note_nullability_here) 6096 << DiagNullabilityKind(*existingNullability, false); 6097 } 6098 } 6099 } 6100 6101 return true; 6102 } 6103 } 6104 6105 // If this definitely isn't a pointer type, reject the specifier. 6106 if (!desugared->canHaveNullability() && 6107 !(allowOnArrayType && desugared->isArrayType())) { 6108 Diag(nullabilityLoc, diag::err_nullability_nonpointer) 6109 << DiagNullabilityKind(nullability, isContextSensitive) << type; 6110 return true; 6111 } 6112 6113 // For the context-sensitive keywords/Objective-C property 6114 // attributes, require that the type be a single-level pointer. 6115 if (isContextSensitive) { 6116 // Make sure that the pointee isn't itself a pointer type. 6117 const Type *pointeeType; 6118 if (desugared->isArrayType()) 6119 pointeeType = desugared->getArrayElementTypeNoTypeQual(); 6120 else 6121 pointeeType = desugared->getPointeeType().getTypePtr(); 6122 6123 if (pointeeType->isAnyPointerType() || 6124 pointeeType->isObjCObjectPointerType() || 6125 pointeeType->isMemberPointerType()) { 6126 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) 6127 << DiagNullabilityKind(nullability, true) 6128 << type; 6129 Diag(nullabilityLoc, diag::note_nullability_type_specifier) 6130 << DiagNullabilityKind(nullability, false) 6131 << type 6132 << FixItHint::CreateReplacement(nullabilityLoc, 6133 getNullabilitySpelling(nullability)); 6134 return true; 6135 } 6136 } 6137 6138 // Form the attributed type. 6139 type = Context.getAttributedType( 6140 AttributedType::getNullabilityAttrKind(nullability), type, type); 6141 return false; 6142 } 6143 6144 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) { 6145 if (isa<ObjCTypeParamType>(type)) { 6146 // Build the attributed type to record where __kindof occurred. 6147 type = Context.getAttributedType(AttributedType::attr_objc_kindof, 6148 type, type); 6149 return false; 6150 } 6151 6152 // Find out if it's an Objective-C object or object pointer type; 6153 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); 6154 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() 6155 : type->getAs<ObjCObjectType>(); 6156 6157 // If not, we can't apply __kindof. 6158 if (!objType) { 6159 // FIXME: Handle dependent types that aren't yet object types. 6160 Diag(loc, diag::err_objc_kindof_nonobject) 6161 << type; 6162 return true; 6163 } 6164 6165 // Rebuild the "equivalent" type, which pushes __kindof down into 6166 // the object type. 6167 // There is no need to apply kindof on an unqualified id type. 6168 QualType equivType = Context.getObjCObjectType( 6169 objType->getBaseType(), objType->getTypeArgsAsWritten(), 6170 objType->getProtocols(), 6171 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); 6172 6173 // If we started with an object pointer type, rebuild it. 6174 if (ptrType) { 6175 equivType = Context.getObjCObjectPointerType(equivType); 6176 if (auto nullability = type->getNullability(Context)) { 6177 auto attrKind = AttributedType::getNullabilityAttrKind(*nullability); 6178 equivType = Context.getAttributedType(attrKind, equivType, equivType); 6179 } 6180 } 6181 6182 // Build the attributed type to record where __kindof occurred. 6183 type = Context.getAttributedType(AttributedType::attr_objc_kindof, 6184 type, 6185 equivType); 6186 6187 return false; 6188 } 6189 6190 /// Map a nullability attribute kind to a nullability kind. 6191 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) { 6192 switch (kind) { 6193 case AttributeList::AT_TypeNonNull: 6194 return NullabilityKind::NonNull; 6195 6196 case AttributeList::AT_TypeNullable: 6197 return NullabilityKind::Nullable; 6198 6199 case AttributeList::AT_TypeNullUnspecified: 6200 return NullabilityKind::Unspecified; 6201 6202 default: 6203 llvm_unreachable("not a nullability attribute kind"); 6204 } 6205 } 6206 6207 /// Distribute a nullability type attribute that cannot be applied to 6208 /// the type specifier to a pointer, block pointer, or member pointer 6209 /// declarator, complaining if necessary. 6210 /// 6211 /// \returns true if the nullability annotation was distributed, false 6212 /// otherwise. 6213 static bool distributeNullabilityTypeAttr(TypeProcessingState &state, 6214 QualType type, 6215 AttributeList &attr) { 6216 Declarator &declarator = state.getDeclarator(); 6217 6218 /// Attempt to move the attribute to the specified chunk. 6219 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { 6220 // If there is already a nullability attribute there, don't add 6221 // one. 6222 if (hasNullabilityAttr(chunk.getAttrListRef())) 6223 return false; 6224 6225 // Complain about the nullability qualifier being in the wrong 6226 // place. 6227 enum { 6228 PK_Pointer, 6229 PK_BlockPointer, 6230 PK_MemberPointer, 6231 PK_FunctionPointer, 6232 PK_MemberFunctionPointer, 6233 } pointerKind 6234 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer 6235 : PK_Pointer) 6236 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer 6237 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; 6238 6239 auto diag = state.getSema().Diag(attr.getLoc(), 6240 diag::warn_nullability_declspec) 6241 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), 6242 attr.isContextSensitiveKeywordAttribute()) 6243 << type 6244 << static_cast<unsigned>(pointerKind); 6245 6246 // FIXME: MemberPointer chunks don't carry the location of the *. 6247 if (chunk.Kind != DeclaratorChunk::MemberPointer) { 6248 diag << FixItHint::CreateRemoval(attr.getLoc()) 6249 << FixItHint::CreateInsertion( 6250 state.getSema().getPreprocessor() 6251 .getLocForEndOfToken(chunk.Loc), 6252 " " + attr.getName()->getName().str() + " "); 6253 } 6254 6255 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 6256 chunk.getAttrListRef()); 6257 return true; 6258 }; 6259 6260 // Move it to the outermost pointer, member pointer, or block 6261 // pointer declarator. 6262 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 6263 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 6264 switch (chunk.Kind) { 6265 case DeclaratorChunk::Pointer: 6266 case DeclaratorChunk::BlockPointer: 6267 case DeclaratorChunk::MemberPointer: 6268 return moveToChunk(chunk, false); 6269 6270 case DeclaratorChunk::Paren: 6271 case DeclaratorChunk::Array: 6272 continue; 6273 6274 case DeclaratorChunk::Function: 6275 // Try to move past the return type to a function/block/member 6276 // function pointer. 6277 if (DeclaratorChunk *dest = maybeMovePastReturnType( 6278 declarator, i, 6279 /*onlyBlockPointers=*/false)) { 6280 return moveToChunk(*dest, true); 6281 } 6282 6283 return false; 6284 6285 // Don't walk through these. 6286 case DeclaratorChunk::Reference: 6287 case DeclaratorChunk::Pipe: 6288 return false; 6289 } 6290 } 6291 6292 return false; 6293 } 6294 6295 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) { 6296 assert(!Attr.isInvalid()); 6297 switch (Attr.getKind()) { 6298 default: 6299 llvm_unreachable("not a calling convention attribute"); 6300 case AttributeList::AT_CDecl: 6301 return AttributedType::attr_cdecl; 6302 case AttributeList::AT_FastCall: 6303 return AttributedType::attr_fastcall; 6304 case AttributeList::AT_StdCall: 6305 return AttributedType::attr_stdcall; 6306 case AttributeList::AT_ThisCall: 6307 return AttributedType::attr_thiscall; 6308 case AttributeList::AT_RegCall: 6309 return AttributedType::attr_regcall; 6310 case AttributeList::AT_Pascal: 6311 return AttributedType::attr_pascal; 6312 case AttributeList::AT_SwiftCall: 6313 return AttributedType::attr_swiftcall; 6314 case AttributeList::AT_VectorCall: 6315 return AttributedType::attr_vectorcall; 6316 case AttributeList::AT_Pcs: { 6317 // The attribute may have had a fixit applied where we treated an 6318 // identifier as a string literal. The contents of the string are valid, 6319 // but the form may not be. 6320 StringRef Str; 6321 if (Attr.isArgExpr(0)) 6322 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); 6323 else 6324 Str = Attr.getArgAsIdent(0)->Ident->getName(); 6325 return llvm::StringSwitch<AttributedType::Kind>(Str) 6326 .Case("aapcs", AttributedType::attr_pcs) 6327 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp); 6328 } 6329 case AttributeList::AT_IntelOclBicc: 6330 return AttributedType::attr_inteloclbicc; 6331 case AttributeList::AT_MSABI: 6332 return AttributedType::attr_ms_abi; 6333 case AttributeList::AT_SysVABI: 6334 return AttributedType::attr_sysv_abi; 6335 case AttributeList::AT_PreserveMost: 6336 return AttributedType::attr_preserve_most; 6337 case AttributeList::AT_PreserveAll: 6338 return AttributedType::attr_preserve_all; 6339 } 6340 llvm_unreachable("unexpected attribute kind!"); 6341 } 6342 6343 /// Process an individual function attribute. Returns true to 6344 /// indicate that the attribute was handled, false if it wasn't. 6345 static bool handleFunctionTypeAttr(TypeProcessingState &state, 6346 AttributeList &attr, 6347 QualType &type) { 6348 Sema &S = state.getSema(); 6349 6350 FunctionTypeUnwrapper unwrapped(S, type); 6351 6352 if (attr.getKind() == AttributeList::AT_NoReturn) { 6353 if (S.CheckNoReturnAttr(attr)) 6354 return true; 6355 6356 // Delay if this is not a function type. 6357 if (!unwrapped.isFunctionType()) 6358 return false; 6359 6360 // Otherwise we can process right away. 6361 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 6362 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6363 return true; 6364 } 6365 6366 // ns_returns_retained is not always a type attribute, but if we got 6367 // here, we're treating it as one right now. 6368 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) { 6369 assert(S.getLangOpts().ObjCAutoRefCount && 6370 "ns_returns_retained treated as type attribute in non-ARC"); 6371 if (attr.getNumArgs()) return true; 6372 6373 // Delay if this is not a function type. 6374 if (!unwrapped.isFunctionType()) 6375 return false; 6376 6377 FunctionType::ExtInfo EI 6378 = unwrapped.get()->getExtInfo().withProducesResult(true); 6379 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6380 return true; 6381 } 6382 6383 if (attr.getKind() == AttributeList::AT_AnyX86NoCallerSavedRegisters) { 6384 if (S.CheckNoCallerSavedRegsAttr(attr)) 6385 return true; 6386 6387 // Delay if this is not a function type. 6388 if (!unwrapped.isFunctionType()) 6389 return false; 6390 6391 FunctionType::ExtInfo EI = 6392 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true); 6393 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6394 return true; 6395 } 6396 6397 if (attr.getKind() == AttributeList::AT_Regparm) { 6398 unsigned value; 6399 if (S.CheckRegparmAttr(attr, value)) 6400 return true; 6401 6402 // Delay if this is not a function type. 6403 if (!unwrapped.isFunctionType()) 6404 return false; 6405 6406 // Diagnose regparm with fastcall. 6407 const FunctionType *fn = unwrapped.get(); 6408 CallingConv CC = fn->getCallConv(); 6409 if (CC == CC_X86FastCall) { 6410 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6411 << FunctionType::getNameForCallConv(CC) 6412 << "regparm"; 6413 attr.setInvalid(); 6414 return true; 6415 } 6416 6417 FunctionType::ExtInfo EI = 6418 unwrapped.get()->getExtInfo().withRegParm(value); 6419 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6420 return true; 6421 } 6422 6423 // Delay if the type didn't work out to a function. 6424 if (!unwrapped.isFunctionType()) return false; 6425 6426 // Otherwise, a calling convention. 6427 CallingConv CC; 6428 if (S.CheckCallingConvAttr(attr, CC)) 6429 return true; 6430 6431 const FunctionType *fn = unwrapped.get(); 6432 CallingConv CCOld = fn->getCallConv(); 6433 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr); 6434 6435 if (CCOld != CC) { 6436 // Error out on when there's already an attribute on the type 6437 // and the CCs don't match. 6438 const AttributedType *AT = S.getCallingConvAttributedType(type); 6439 if (AT && AT->getAttrKind() != CCAttrKind) { 6440 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6441 << FunctionType::getNameForCallConv(CC) 6442 << FunctionType::getNameForCallConv(CCOld); 6443 attr.setInvalid(); 6444 return true; 6445 } 6446 } 6447 6448 // Diagnose use of variadic functions with calling conventions that 6449 // don't support them (e.g. because they're callee-cleanup). 6450 // We delay warning about this on unprototyped function declarations 6451 // until after redeclaration checking, just in case we pick up a 6452 // prototype that way. And apparently we also "delay" warning about 6453 // unprototyped function types in general, despite not necessarily having 6454 // much ability to diagnose it later. 6455 if (!supportsVariadicCall(CC)) { 6456 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); 6457 if (FnP && FnP->isVariadic()) { 6458 unsigned DiagID = diag::err_cconv_varargs; 6459 6460 // stdcall and fastcall are ignored with a warning for GCC and MS 6461 // compatibility. 6462 bool IsInvalid = true; 6463 if (CC == CC_X86StdCall || CC == CC_X86FastCall) { 6464 DiagID = diag::warn_cconv_varargs; 6465 IsInvalid = false; 6466 } 6467 6468 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC); 6469 if (IsInvalid) attr.setInvalid(); 6470 return true; 6471 } 6472 } 6473 6474 // Also diagnose fastcall with regparm. 6475 if (CC == CC_X86FastCall && fn->getHasRegParm()) { 6476 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6477 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); 6478 attr.setInvalid(); 6479 return true; 6480 } 6481 6482 // Modify the CC from the wrapped function type, wrap it all back, and then 6483 // wrap the whole thing in an AttributedType as written. The modified type 6484 // might have a different CC if we ignored the attribute. 6485 QualType Equivalent; 6486 if (CCOld == CC) { 6487 Equivalent = type; 6488 } else { 6489 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 6490 Equivalent = 6491 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6492 } 6493 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent); 6494 return true; 6495 } 6496 6497 bool Sema::hasExplicitCallingConv(QualType &T) { 6498 QualType R = T.IgnoreParens(); 6499 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) { 6500 if (AT->isCallingConv()) 6501 return true; 6502 R = AT->getModifiedType().IgnoreParens(); 6503 } 6504 return false; 6505 } 6506 6507 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, 6508 SourceLocation Loc) { 6509 FunctionTypeUnwrapper Unwrapped(*this, T); 6510 const FunctionType *FT = Unwrapped.get(); 6511 bool IsVariadic = (isa<FunctionProtoType>(FT) && 6512 cast<FunctionProtoType>(FT)->isVariadic()); 6513 CallingConv CurCC = FT->getCallConv(); 6514 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); 6515 6516 if (CurCC == ToCC) 6517 return; 6518 6519 // MS compiler ignores explicit calling convention attributes on structors. We 6520 // should do the same. 6521 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { 6522 // Issue a warning on ignored calling convention -- except of __stdcall. 6523 // Again, this is what MS compiler does. 6524 if (CurCC != CC_X86StdCall) 6525 Diag(Loc, diag::warn_cconv_structors) 6526 << FunctionType::getNameForCallConv(CurCC); 6527 // Default adjustment. 6528 } else { 6529 // Only adjust types with the default convention. For example, on Windows 6530 // we should adjust a __cdecl type to __thiscall for instance methods, and a 6531 // __thiscall type to __cdecl for static methods. 6532 CallingConv DefaultCC = 6533 Context.getDefaultCallingConvention(IsVariadic, IsStatic); 6534 6535 if (CurCC != DefaultCC || DefaultCC == ToCC) 6536 return; 6537 6538 if (hasExplicitCallingConv(T)) 6539 return; 6540 } 6541 6542 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); 6543 QualType Wrapped = Unwrapped.wrap(*this, FT); 6544 T = Context.getAdjustedType(T, Wrapped); 6545 } 6546 6547 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 6548 /// and float scalars, although arrays, pointers, and function return values are 6549 /// allowed in conjunction with this construct. Aggregates with this attribute 6550 /// are invalid, even if they are of the same size as a corresponding scalar. 6551 /// The raw attribute should contain precisely 1 argument, the vector size for 6552 /// the variable, measured in bytes. If curType and rawAttr are well formed, 6553 /// this routine will return a new vector type. 6554 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 6555 Sema &S) { 6556 // Check the attribute arguments. 6557 if (Attr.getNumArgs() != 1) { 6558 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6559 << Attr.getName() << 1; 6560 Attr.setInvalid(); 6561 return; 6562 } 6563 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 6564 llvm::APSInt vecSize(32); 6565 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 6566 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 6567 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 6568 << Attr.getName() << AANT_ArgumentIntegerConstant 6569 << sizeExpr->getSourceRange(); 6570 Attr.setInvalid(); 6571 return; 6572 } 6573 // The base type must be integer (not Boolean or enumeration) or float, and 6574 // can't already be a vector. 6575 if (!CurType->isBuiltinType() || CurType->isBooleanType() || 6576 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) { 6577 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 6578 Attr.setInvalid(); 6579 return; 6580 } 6581 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 6582 // vecSize is specified in bytes - convert to bits. 6583 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 6584 6585 // the vector size needs to be an integral multiple of the type size. 6586 if (vectorSize % typeSize) { 6587 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 6588 << sizeExpr->getSourceRange(); 6589 Attr.setInvalid(); 6590 return; 6591 } 6592 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) { 6593 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large) 6594 << sizeExpr->getSourceRange(); 6595 Attr.setInvalid(); 6596 return; 6597 } 6598 if (vectorSize == 0) { 6599 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 6600 << sizeExpr->getSourceRange(); 6601 Attr.setInvalid(); 6602 return; 6603 } 6604 6605 // Success! Instantiate the vector type, the number of elements is > 0, and 6606 // not required to be a power of 2, unlike GCC. 6607 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 6608 VectorType::GenericVector); 6609 } 6610 6611 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on 6612 /// a type. 6613 static void HandleExtVectorTypeAttr(QualType &CurType, 6614 const AttributeList &Attr, 6615 Sema &S) { 6616 // check the attribute arguments. 6617 if (Attr.getNumArgs() != 1) { 6618 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6619 << Attr.getName() << 1; 6620 return; 6621 } 6622 6623 Expr *sizeExpr; 6624 6625 // Special case where the argument is a template id. 6626 if (Attr.isArgIdent(0)) { 6627 CXXScopeSpec SS; 6628 SourceLocation TemplateKWLoc; 6629 UnqualifiedId id; 6630 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); 6631 6632 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 6633 id, false, false); 6634 if (Size.isInvalid()) 6635 return; 6636 6637 sizeExpr = Size.get(); 6638 } else { 6639 sizeExpr = Attr.getArgAsExpr(0); 6640 } 6641 6642 // Create the vector type. 6643 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 6644 if (!T.isNull()) 6645 CurType = T; 6646 } 6647 6648 static bool isPermittedNeonBaseType(QualType &Ty, 6649 VectorType::VectorKind VecKind, Sema &S) { 6650 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 6651 if (!BTy) 6652 return false; 6653 6654 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 6655 6656 // Signed poly is mathematically wrong, but has been baked into some ABIs by 6657 // now. 6658 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || 6659 Triple.getArch() == llvm::Triple::aarch64_be; 6660 if (VecKind == VectorType::NeonPolyVector) { 6661 if (IsPolyUnsigned) { 6662 // AArch64 polynomial vectors are unsigned and support poly64. 6663 return BTy->getKind() == BuiltinType::UChar || 6664 BTy->getKind() == BuiltinType::UShort || 6665 BTy->getKind() == BuiltinType::ULong || 6666 BTy->getKind() == BuiltinType::ULongLong; 6667 } else { 6668 // AArch32 polynomial vector are signed. 6669 return BTy->getKind() == BuiltinType::SChar || 6670 BTy->getKind() == BuiltinType::Short; 6671 } 6672 } 6673 6674 // Non-polynomial vector types: the usual suspects are allowed, as well as 6675 // float64_t on AArch64. 6676 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 || 6677 Triple.getArch() == llvm::Triple::aarch64_be; 6678 6679 if (Is64Bit && BTy->getKind() == BuiltinType::Double) 6680 return true; 6681 6682 return BTy->getKind() == BuiltinType::SChar || 6683 BTy->getKind() == BuiltinType::UChar || 6684 BTy->getKind() == BuiltinType::Short || 6685 BTy->getKind() == BuiltinType::UShort || 6686 BTy->getKind() == BuiltinType::Int || 6687 BTy->getKind() == BuiltinType::UInt || 6688 BTy->getKind() == BuiltinType::Long || 6689 BTy->getKind() == BuiltinType::ULong || 6690 BTy->getKind() == BuiltinType::LongLong || 6691 BTy->getKind() == BuiltinType::ULongLong || 6692 BTy->getKind() == BuiltinType::Float || 6693 BTy->getKind() == BuiltinType::Half; 6694 } 6695 6696 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 6697 /// "neon_polyvector_type" attributes are used to create vector types that 6698 /// are mangled according to ARM's ABI. Otherwise, these types are identical 6699 /// to those created with the "vector_size" attribute. Unlike "vector_size" 6700 /// the argument to these Neon attributes is the number of vector elements, 6701 /// not the vector size in bytes. The vector width and element type must 6702 /// match one of the standard Neon vector types. 6703 static void HandleNeonVectorTypeAttr(QualType& CurType, 6704 const AttributeList &Attr, Sema &S, 6705 VectorType::VectorKind VecKind) { 6706 // Target must have NEON 6707 if (!S.Context.getTargetInfo().hasFeature("neon")) { 6708 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName(); 6709 Attr.setInvalid(); 6710 return; 6711 } 6712 // Check the attribute arguments. 6713 if (Attr.getNumArgs() != 1) { 6714 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6715 << Attr.getName() << 1; 6716 Attr.setInvalid(); 6717 return; 6718 } 6719 // The number of elements must be an ICE. 6720 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 6721 llvm::APSInt numEltsInt(32); 6722 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 6723 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 6724 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 6725 << Attr.getName() << AANT_ArgumentIntegerConstant 6726 << numEltsExpr->getSourceRange(); 6727 Attr.setInvalid(); 6728 return; 6729 } 6730 // Only certain element types are supported for Neon vectors. 6731 if (!isPermittedNeonBaseType(CurType, VecKind, S)) { 6732 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 6733 Attr.setInvalid(); 6734 return; 6735 } 6736 6737 // The total size of the vector must be 64 or 128 bits. 6738 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 6739 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 6740 unsigned vecSize = typeSize * numElts; 6741 if (vecSize != 64 && vecSize != 128) { 6742 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 6743 Attr.setInvalid(); 6744 return; 6745 } 6746 6747 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 6748 } 6749 6750 /// Handle OpenCL Access Qualifier Attribute. 6751 static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr, 6752 Sema &S) { 6753 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. 6754 if (!(CurType->isImageType() || CurType->isPipeType())) { 6755 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); 6756 Attr.setInvalid(); 6757 return; 6758 } 6759 6760 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { 6761 QualType PointeeTy = TypedefTy->desugar(); 6762 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); 6763 6764 std::string PrevAccessQual; 6765 switch (cast<BuiltinType>(PointeeTy.getTypePtr())->getKind()) { 6766 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6767 case BuiltinType::Id: \ 6768 PrevAccessQual = #Access; \ 6769 break; 6770 #include "clang/Basic/OpenCLImageTypes.def" 6771 default: 6772 assert(0 && "Unable to find corresponding image type."); 6773 } 6774 6775 S.Diag(TypedefTy->getDecl()->getLocStart(), 6776 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; 6777 } else if (CurType->isPipeType()) { 6778 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { 6779 QualType ElemType = CurType->getAs<PipeType>()->getElementType(); 6780 CurType = S.Context.getWritePipeType(ElemType); 6781 } 6782 } 6783 } 6784 6785 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 6786 TypeAttrLocation TAL, AttributeList *attrs) { 6787 // Scan through and apply attributes to this type where it makes sense. Some 6788 // attributes (such as __address_space__, __vector_size__, etc) apply to the 6789 // type, but others can be present in the type specifiers even though they 6790 // apply to the decl. Here we apply type attributes and ignore the rest. 6791 6792 bool hasOpenCLAddressSpace = false; 6793 while (attrs) { 6794 AttributeList &attr = *attrs; 6795 attrs = attr.getNext(); // reset to the next here due to early loop continue 6796 // stmts 6797 6798 // Skip attributes that were marked to be invalid. 6799 if (attr.isInvalid()) 6800 continue; 6801 6802 if (attr.isCXX11Attribute()) { 6803 // [[gnu::...]] attributes are treated as declaration attributes, so may 6804 // not appertain to a DeclaratorChunk, even if we handle them as type 6805 // attributes. 6806 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) { 6807 if (TAL == TAL_DeclChunk) { 6808 state.getSema().Diag(attr.getLoc(), 6809 diag::warn_cxx11_gnu_attribute_on_type) 6810 << attr.getName(); 6811 continue; 6812 } 6813 } else if (TAL != TAL_DeclChunk) { 6814 // Otherwise, only consider type processing for a C++11 attribute if 6815 // it's actually been applied to a type. 6816 continue; 6817 } 6818 } 6819 6820 // If this is an attribute we can handle, do so now, 6821 // otherwise, add it to the FnAttrs list for rechaining. 6822 switch (attr.getKind()) { 6823 default: 6824 // A C++11 attribute on a declarator chunk must appertain to a type. 6825 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { 6826 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 6827 << attr.getName(); 6828 attr.setUsedAsTypeAttr(); 6829 } 6830 break; 6831 6832 case AttributeList::UnknownAttribute: 6833 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) 6834 state.getSema().Diag(attr.getLoc(), 6835 diag::warn_unknown_attribute_ignored) 6836 << attr.getName(); 6837 break; 6838 6839 case AttributeList::IgnoredAttribute: 6840 break; 6841 6842 case AttributeList::AT_MayAlias: 6843 // FIXME: This attribute needs to actually be handled, but if we ignore 6844 // it it breaks large amounts of Linux software. 6845 attr.setUsedAsTypeAttr(); 6846 break; 6847 case AttributeList::AT_OpenCLPrivateAddressSpace: 6848 case AttributeList::AT_OpenCLGlobalAddressSpace: 6849 case AttributeList::AT_OpenCLLocalAddressSpace: 6850 case AttributeList::AT_OpenCLConstantAddressSpace: 6851 case AttributeList::AT_OpenCLGenericAddressSpace: 6852 case AttributeList::AT_AddressSpace: 6853 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 6854 attr.setUsedAsTypeAttr(); 6855 hasOpenCLAddressSpace = true; 6856 break; 6857 OBJC_POINTER_TYPE_ATTRS_CASELIST: 6858 if (!handleObjCPointerTypeAttr(state, attr, type)) 6859 distributeObjCPointerTypeAttr(state, attr, type); 6860 attr.setUsedAsTypeAttr(); 6861 break; 6862 case AttributeList::AT_VectorSize: 6863 HandleVectorSizeAttr(type, attr, state.getSema()); 6864 attr.setUsedAsTypeAttr(); 6865 break; 6866 case AttributeList::AT_ExtVectorType: 6867 HandleExtVectorTypeAttr(type, attr, state.getSema()); 6868 attr.setUsedAsTypeAttr(); 6869 break; 6870 case AttributeList::AT_NeonVectorType: 6871 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 6872 VectorType::NeonVector); 6873 attr.setUsedAsTypeAttr(); 6874 break; 6875 case AttributeList::AT_NeonPolyVectorType: 6876 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 6877 VectorType::NeonPolyVector); 6878 attr.setUsedAsTypeAttr(); 6879 break; 6880 case AttributeList::AT_OpenCLAccess: 6881 HandleOpenCLAccessAttr(type, attr, state.getSema()); 6882 attr.setUsedAsTypeAttr(); 6883 break; 6884 6885 MS_TYPE_ATTRS_CASELIST: 6886 if (!handleMSPointerTypeQualifierAttr(state, attr, type)) 6887 attr.setUsedAsTypeAttr(); 6888 break; 6889 6890 6891 NULLABILITY_TYPE_ATTRS_CASELIST: 6892 // Either add nullability here or try to distribute it. We 6893 // don't want to distribute the nullability specifier past any 6894 // dependent type, because that complicates the user model. 6895 if (type->canHaveNullability() || type->isDependentType() || 6896 type->isArrayType() || 6897 !distributeNullabilityTypeAttr(state, type, attr)) { 6898 unsigned endIndex; 6899 if (TAL == TAL_DeclChunk) 6900 endIndex = state.getCurrentChunkIndex(); 6901 else 6902 endIndex = state.getDeclarator().getNumTypeObjects(); 6903 bool allowOnArrayType = 6904 state.getDeclarator().isPrototypeContext() && 6905 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex); 6906 if (state.getSema().checkNullabilityTypeSpecifier( 6907 type, 6908 mapNullabilityAttrKind(attr.getKind()), 6909 attr.getLoc(), 6910 attr.isContextSensitiveKeywordAttribute(), 6911 allowOnArrayType)) { 6912 attr.setInvalid(); 6913 } 6914 6915 attr.setUsedAsTypeAttr(); 6916 } 6917 break; 6918 6919 case AttributeList::AT_ObjCKindOf: 6920 // '__kindof' must be part of the decl-specifiers. 6921 switch (TAL) { 6922 case TAL_DeclSpec: 6923 break; 6924 6925 case TAL_DeclChunk: 6926 case TAL_DeclName: 6927 state.getSema().Diag(attr.getLoc(), 6928 diag::err_objc_kindof_wrong_position) 6929 << FixItHint::CreateRemoval(attr.getLoc()) 6930 << FixItHint::CreateInsertion( 6931 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof "); 6932 break; 6933 } 6934 6935 // Apply it regardless. 6936 if (state.getSema().checkObjCKindOfType(type, attr.getLoc())) 6937 attr.setInvalid(); 6938 attr.setUsedAsTypeAttr(); 6939 break; 6940 6941 case AttributeList::AT_NSReturnsRetained: 6942 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 6943 break; 6944 // fallthrough into the function attrs 6945 6946 FUNCTION_TYPE_ATTRS_CASELIST: 6947 attr.setUsedAsTypeAttr(); 6948 6949 // Never process function type attributes as part of the 6950 // declaration-specifiers. 6951 if (TAL == TAL_DeclSpec) 6952 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 6953 6954 // Otherwise, handle the possible delays. 6955 else if (!handleFunctionTypeAttr(state, attr, type)) 6956 distributeFunctionTypeAttr(state, attr, type); 6957 break; 6958 } 6959 } 6960 6961 // If address space is not set, OpenCL 2.0 defines non private default 6962 // address spaces for some cases: 6963 // OpenCL 2.0, section 6.5: 6964 // The address space for a variable at program scope or a static variable 6965 // inside a function can either be __global or __constant, but defaults to 6966 // __global if not specified. 6967 // (...) 6968 // Pointers that are declared without pointing to a named address space point 6969 // to the generic address space. 6970 if (state.getSema().getLangOpts().OpenCLVersion >= 200 && 6971 !hasOpenCLAddressSpace && type.getAddressSpace() == 0 && 6972 (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) { 6973 Declarator &D = state.getDeclarator(); 6974 if (state.getCurrentChunkIndex() > 0 && 6975 (D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind == 6976 DeclaratorChunk::Pointer || 6977 D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind == 6978 DeclaratorChunk::BlockPointer)) { 6979 type = state.getSema().Context.getAddrSpaceQualType( 6980 type, LangAS::opencl_generic); 6981 } else if (state.getCurrentChunkIndex() == 0 && 6982 D.getContext() == Declarator::FileContext && 6983 !D.isFunctionDeclarator() && !D.isFunctionDefinition() && 6984 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6985 !type->isSamplerT()) 6986 type = state.getSema().Context.getAddrSpaceQualType( 6987 type, LangAS::opencl_global); 6988 else if (state.getCurrentChunkIndex() == 0 && 6989 D.getContext() == Declarator::BlockContext && 6990 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) 6991 type = state.getSema().Context.getAddrSpaceQualType( 6992 type, LangAS::opencl_global); 6993 } 6994 } 6995 6996 void Sema::completeExprArrayBound(Expr *E) { 6997 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 6998 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 6999 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { 7000 SourceLocation PointOfInstantiation = E->getExprLoc(); 7001 7002 if (MemberSpecializationInfo *MSInfo = 7003 Var->getMemberSpecializationInfo()) { 7004 // If we don't already have a point of instantiation, this is it. 7005 if (MSInfo->getPointOfInstantiation().isInvalid()) { 7006 MSInfo->setPointOfInstantiation(PointOfInstantiation); 7007 7008 // This is a modification of an existing AST node. Notify 7009 // listeners. 7010 if (ASTMutationListener *L = getASTMutationListener()) 7011 L->StaticDataMemberInstantiated(Var); 7012 } 7013 } else { 7014 VarTemplateSpecializationDecl *VarSpec = 7015 cast<VarTemplateSpecializationDecl>(Var); 7016 if (VarSpec->getPointOfInstantiation().isInvalid()) 7017 VarSpec->setPointOfInstantiation(PointOfInstantiation); 7018 } 7019 7020 InstantiateVariableDefinition(PointOfInstantiation, Var); 7021 7022 // Update the type to the newly instantiated definition's type both 7023 // here and within the expression. 7024 if (VarDecl *Def = Var->getDefinition()) { 7025 DRE->setDecl(Def); 7026 QualType T = Def->getType(); 7027 DRE->setType(T); 7028 // FIXME: Update the type on all intervening expressions. 7029 E->setType(T); 7030 } 7031 7032 // We still go on to try to complete the type independently, as it 7033 // may also require instantiations or diagnostics if it remains 7034 // incomplete. 7035 } 7036 } 7037 } 7038 } 7039 7040 /// \brief Ensure that the type of the given expression is complete. 7041 /// 7042 /// This routine checks whether the expression \p E has a complete type. If the 7043 /// expression refers to an instantiable construct, that instantiation is 7044 /// performed as needed to complete its type. Furthermore 7045 /// Sema::RequireCompleteType is called for the expression's type (or in the 7046 /// case of a reference type, the referred-to type). 7047 /// 7048 /// \param E The expression whose type is required to be complete. 7049 /// \param Diagnoser The object that will emit a diagnostic if the type is 7050 /// incomplete. 7051 /// 7052 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 7053 /// otherwise. 7054 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) { 7055 QualType T = E->getType(); 7056 7057 // Incomplete array types may be completed by the initializer attached to 7058 // their definitions. For static data members of class templates and for 7059 // variable templates, we need to instantiate the definition to get this 7060 // initializer and complete the type. 7061 if (T->isIncompleteArrayType()) { 7062 completeExprArrayBound(E); 7063 T = E->getType(); 7064 } 7065 7066 // FIXME: Are there other cases which require instantiating something other 7067 // than the type to complete the type of an expression? 7068 7069 return RequireCompleteType(E->getExprLoc(), T, Diagnoser); 7070 } 7071 7072 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 7073 BoundTypeDiagnoser<> Diagnoser(DiagID); 7074 return RequireCompleteExprType(E, Diagnoser); 7075 } 7076 7077 /// @brief Ensure that the type T is a complete type. 7078 /// 7079 /// This routine checks whether the type @p T is complete in any 7080 /// context where a complete type is required. If @p T is a complete 7081 /// type, returns false. If @p T is a class template specialization, 7082 /// this routine then attempts to perform class template 7083 /// instantiation. If instantiation fails, or if @p T is incomplete 7084 /// and cannot be completed, issues the diagnostic @p diag (giving it 7085 /// the type @p T) and returns true. 7086 /// 7087 /// @param Loc The location in the source that the incomplete type 7088 /// diagnostic should refer to. 7089 /// 7090 /// @param T The type that this routine is examining for completeness. 7091 /// 7092 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 7093 /// @c false otherwise. 7094 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 7095 TypeDiagnoser &Diagnoser) { 7096 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser)) 7097 return true; 7098 if (const TagType *Tag = T->getAs<TagType>()) { 7099 if (!Tag->getDecl()->isCompleteDefinitionRequired()) { 7100 Tag->getDecl()->setCompleteDefinitionRequired(); 7101 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); 7102 } 7103 } 7104 return false; 7105 } 7106 7107 /// \brief Determine whether there is any declaration of \p D that was ever a 7108 /// definition (perhaps before module merging) and is currently visible. 7109 /// \param D The definition of the entity. 7110 /// \param Suggested Filled in with the declaration that should be made visible 7111 /// in order to provide a definition of this entity. 7112 /// \param OnlyNeedComplete If \c true, we only need the type to be complete, 7113 /// not defined. This only matters for enums with a fixed underlying 7114 /// type, since in all other cases, a type is complete if and only if it 7115 /// is defined. 7116 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 7117 bool OnlyNeedComplete) { 7118 // Easy case: if we don't have modules, all declarations are visible. 7119 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) 7120 return true; 7121 7122 // If this definition was instantiated from a template, map back to the 7123 // pattern from which it was instantiated. 7124 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { 7125 // We're in the middle of defining it; this definition should be treated 7126 // as visible. 7127 return true; 7128 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 7129 if (auto *Pattern = RD->getTemplateInstantiationPattern()) 7130 RD = Pattern; 7131 D = RD->getDefinition(); 7132 } else if (auto *ED = dyn_cast<EnumDecl>(D)) { 7133 if (auto *Pattern = ED->getTemplateInstantiationPattern()) 7134 ED = Pattern; 7135 if (OnlyNeedComplete && ED->isFixed()) { 7136 // If the enum has a fixed underlying type, and we're only looking for a 7137 // complete type (not a definition), any visible declaration of it will 7138 // do. 7139 *Suggested = nullptr; 7140 for (auto *Redecl : ED->redecls()) { 7141 if (isVisible(Redecl)) 7142 return true; 7143 if (Redecl->isThisDeclarationADefinition() || 7144 (Redecl->isCanonicalDecl() && !*Suggested)) 7145 *Suggested = Redecl; 7146 } 7147 return false; 7148 } 7149 D = ED->getDefinition(); 7150 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { 7151 if (auto *Pattern = FD->getTemplateInstantiationPattern()) 7152 FD = Pattern; 7153 D = FD->getDefinition(); 7154 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 7155 if (auto *Pattern = VD->getTemplateInstantiationPattern()) 7156 VD = Pattern; 7157 D = VD->getDefinition(); 7158 } 7159 assert(D && "missing definition for pattern of instantiated definition"); 7160 7161 *Suggested = D; 7162 if (isVisible(D)) 7163 return true; 7164 7165 // The external source may have additional definitions of this entity that are 7166 // visible, so complete the redeclaration chain now and ask again. 7167 if (auto *Source = Context.getExternalSource()) { 7168 Source->CompleteRedeclChain(D); 7169 return isVisible(D); 7170 } 7171 7172 return false; 7173 } 7174 7175 /// Locks in the inheritance model for the given class and all of its bases. 7176 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { 7177 RD = RD->getMostRecentDecl(); 7178 if (!RD->hasAttr<MSInheritanceAttr>()) { 7179 MSInheritanceAttr::Spelling IM; 7180 7181 switch (S.MSPointerToMemberRepresentationMethod) { 7182 case LangOptions::PPTMK_BestCase: 7183 IM = RD->calculateInheritanceModel(); 7184 break; 7185 case LangOptions::PPTMK_FullGeneralitySingleInheritance: 7186 IM = MSInheritanceAttr::Keyword_single_inheritance; 7187 break; 7188 case LangOptions::PPTMK_FullGeneralityMultipleInheritance: 7189 IM = MSInheritanceAttr::Keyword_multiple_inheritance; 7190 break; 7191 case LangOptions::PPTMK_FullGeneralityVirtualInheritance: 7192 IM = MSInheritanceAttr::Keyword_unspecified_inheritance; 7193 break; 7194 } 7195 7196 RD->addAttr(MSInheritanceAttr::CreateImplicit( 7197 S.getASTContext(), IM, 7198 /*BestCase=*/S.MSPointerToMemberRepresentationMethod == 7199 LangOptions::PPTMK_BestCase, 7200 S.ImplicitMSInheritanceAttrLoc.isValid() 7201 ? S.ImplicitMSInheritanceAttrLoc 7202 : RD->getSourceRange())); 7203 S.Consumer.AssignInheritanceModel(RD); 7204 } 7205 } 7206 7207 /// \brief The implementation of RequireCompleteType 7208 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 7209 TypeDiagnoser *Diagnoser) { 7210 // FIXME: Add this assertion to make sure we always get instantiation points. 7211 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 7212 // FIXME: Add this assertion to help us flush out problems with 7213 // checking for dependent types and type-dependent expressions. 7214 // 7215 // assert(!T->isDependentType() && 7216 // "Can't ask whether a dependent type is complete"); 7217 7218 // We lock in the inheritance model once somebody has asked us to ensure 7219 // that a pointer-to-member type is complete. 7220 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 7221 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { 7222 if (!MPTy->getClass()->isDependentType()) { 7223 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); 7224 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); 7225 } 7226 } 7227 } 7228 7229 NamedDecl *Def = nullptr; 7230 bool Incomplete = T->isIncompleteType(&Def); 7231 7232 // Check that any necessary explicit specializations are visible. For an 7233 // enum, we just need the declaration, so don't check this. 7234 if (Def && !isa<EnumDecl>(Def)) 7235 checkSpecializationVisibility(Loc, Def); 7236 7237 // If we have a complete type, we're done. 7238 if (!Incomplete) { 7239 // If we know about the definition but it is not visible, complain. 7240 NamedDecl *SuggestedDef = nullptr; 7241 if (Def && 7242 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { 7243 // If the user is going to see an error here, recover by making the 7244 // definition visible. 7245 bool TreatAsComplete = Diagnoser && !isSFINAEContext(); 7246 if (Diagnoser) 7247 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition, 7248 /*Recover*/TreatAsComplete); 7249 return !TreatAsComplete; 7250 } 7251 7252 return false; 7253 } 7254 7255 const TagType *Tag = T->getAs<TagType>(); 7256 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>(); 7257 7258 // If there's an unimported definition of this type in a module (for 7259 // instance, because we forward declared it, then imported the definition), 7260 // import that definition now. 7261 // 7262 // FIXME: What about other cases where an import extends a redeclaration 7263 // chain for a declaration that can be accessed through a mechanism other 7264 // than name lookup (eg, referenced in a template, or a variable whose type 7265 // could be completed by the module)? 7266 // 7267 // FIXME: Should we map through to the base array element type before 7268 // checking for a tag type? 7269 if (Tag || IFace) { 7270 NamedDecl *D = 7271 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl(); 7272 7273 // Avoid diagnosing invalid decls as incomplete. 7274 if (D->isInvalidDecl()) 7275 return true; 7276 7277 // Give the external AST source a chance to complete the type. 7278 if (auto *Source = Context.getExternalSource()) { 7279 if (Tag) 7280 Source->CompleteType(Tag->getDecl()); 7281 else 7282 Source->CompleteType(IFace->getDecl()); 7283 7284 // If the external source completed the type, go through the motions 7285 // again to ensure we're allowed to use the completed type. 7286 if (!T->isIncompleteType()) 7287 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 7288 } 7289 } 7290 7291 // If we have a class template specialization or a class member of a 7292 // class template specialization, or an array with known size of such, 7293 // try to instantiate it. 7294 QualType MaybeTemplate = T; 7295 while (const ConstantArrayType *Array 7296 = Context.getAsConstantArrayType(MaybeTemplate)) 7297 MaybeTemplate = Array->getElementType(); 7298 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 7299 bool Instantiated = false; 7300 bool Diagnosed = false; 7301 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 7302 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 7303 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 7304 Diagnosed = InstantiateClassTemplateSpecialization( 7305 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, 7306 /*Complain=*/Diagnoser); 7307 Instantiated = true; 7308 } 7309 } else if (CXXRecordDecl *Rec 7310 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 7311 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass(); 7312 if (!Rec->isBeingDefined() && Pattern) { 7313 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo(); 7314 assert(MSI && "Missing member specialization information?"); 7315 // This record was instantiated from a class within a template. 7316 if (MSI->getTemplateSpecializationKind() != 7317 TSK_ExplicitSpecialization) { 7318 Diagnosed = InstantiateClass(Loc, Rec, Pattern, 7319 getTemplateInstantiationArgs(Rec), 7320 TSK_ImplicitInstantiation, 7321 /*Complain=*/Diagnoser); 7322 Instantiated = true; 7323 } 7324 } 7325 } 7326 7327 if (Instantiated) { 7328 // Instantiate* might have already complained that the template is not 7329 // defined, if we asked it to. 7330 if (Diagnoser && Diagnosed) 7331 return true; 7332 // If we instantiated a definition, check that it's usable, even if 7333 // instantiation produced an error, so that repeated calls to this 7334 // function give consistent answers. 7335 if (!T->isIncompleteType()) 7336 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 7337 } 7338 } 7339 7340 // FIXME: If we didn't instantiate a definition because of an explicit 7341 // specialization declaration, check that it's visible. 7342 7343 if (!Diagnoser) 7344 return true; 7345 7346 Diagnoser->diagnose(*this, Loc, T); 7347 7348 // If the type was a forward declaration of a class/struct/union 7349 // type, produce a note. 7350 if (Tag && !Tag->getDecl()->isInvalidDecl()) 7351 Diag(Tag->getDecl()->getLocation(), 7352 Tag->isBeingDefined() ? diag::note_type_being_defined 7353 : diag::note_forward_declaration) 7354 << QualType(Tag, 0); 7355 7356 // If the Objective-C class was a forward declaration, produce a note. 7357 if (IFace && !IFace->getDecl()->isInvalidDecl()) 7358 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class); 7359 7360 // If we have external information that we can use to suggest a fix, 7361 // produce a note. 7362 if (ExternalSource) 7363 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); 7364 7365 return true; 7366 } 7367 7368 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 7369 unsigned DiagID) { 7370 BoundTypeDiagnoser<> Diagnoser(DiagID); 7371 return RequireCompleteType(Loc, T, Diagnoser); 7372 } 7373 7374 /// \brief Get diagnostic %select index for tag kind for 7375 /// literal type diagnostic message. 7376 /// WARNING: Indexes apply to particular diagnostics only! 7377 /// 7378 /// \returns diagnostic %select index. 7379 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 7380 switch (Tag) { 7381 case TTK_Struct: return 0; 7382 case TTK_Interface: return 1; 7383 case TTK_Class: return 2; 7384 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 7385 } 7386 } 7387 7388 /// @brief Ensure that the type T is a literal type. 7389 /// 7390 /// This routine checks whether the type @p T is a literal type. If @p T is an 7391 /// incomplete type, an attempt is made to complete it. If @p T is a literal 7392 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 7393 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 7394 /// it the type @p T), along with notes explaining why the type is not a 7395 /// literal type, and returns true. 7396 /// 7397 /// @param Loc The location in the source that the non-literal type 7398 /// diagnostic should refer to. 7399 /// 7400 /// @param T The type that this routine is examining for literalness. 7401 /// 7402 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 7403 /// 7404 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 7405 /// @c false otherwise. 7406 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 7407 TypeDiagnoser &Diagnoser) { 7408 assert(!T->isDependentType() && "type should not be dependent"); 7409 7410 QualType ElemType = Context.getBaseElementType(T); 7411 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && 7412 T->isLiteralType(Context)) 7413 return false; 7414 7415 Diagnoser.diagnose(*this, Loc, T); 7416 7417 if (T->isVariableArrayType()) 7418 return true; 7419 7420 const RecordType *RT = ElemType->getAs<RecordType>(); 7421 if (!RT) 7422 return true; 7423 7424 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 7425 7426 // A partially-defined class type can't be a literal type, because a literal 7427 // class type must have a trivial destructor (which can't be checked until 7428 // the class definition is complete). 7429 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) 7430 return true; 7431 7432 // If the class has virtual base classes, then it's not an aggregate, and 7433 // cannot have any constexpr constructors or a trivial default constructor, 7434 // so is non-literal. This is better to diagnose than the resulting absence 7435 // of constexpr constructors. 7436 if (RD->getNumVBases()) { 7437 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 7438 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 7439 for (const auto &I : RD->vbases()) 7440 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here) 7441 << I.getSourceRange(); 7442 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 7443 !RD->hasTrivialDefaultConstructor()) { 7444 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 7445 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 7446 for (const auto &I : RD->bases()) { 7447 if (!I.getType()->isLiteralType(Context)) { 7448 Diag(I.getLocStart(), 7449 diag::note_non_literal_base_class) 7450 << RD << I.getType() << I.getSourceRange(); 7451 return true; 7452 } 7453 } 7454 for (const auto *I : RD->fields()) { 7455 if (!I->getType()->isLiteralType(Context) || 7456 I->getType().isVolatileQualified()) { 7457 Diag(I->getLocation(), diag::note_non_literal_field) 7458 << RD << I << I->getType() 7459 << I->getType().isVolatileQualified(); 7460 return true; 7461 } 7462 } 7463 } else if (!RD->hasTrivialDestructor()) { 7464 // All fields and bases are of literal types, so have trivial destructors. 7465 // If this class's destructor is non-trivial it must be user-declared. 7466 CXXDestructorDecl *Dtor = RD->getDestructor(); 7467 assert(Dtor && "class has literal fields and bases but no dtor?"); 7468 if (!Dtor) 7469 return true; 7470 7471 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 7472 diag::note_non_literal_user_provided_dtor : 7473 diag::note_non_literal_nontrivial_dtor) << RD; 7474 if (!Dtor->isUserProvided()) 7475 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true); 7476 } 7477 7478 return true; 7479 } 7480 7481 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 7482 BoundTypeDiagnoser<> Diagnoser(DiagID); 7483 return RequireLiteralType(Loc, T, Diagnoser); 7484 } 7485 7486 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 7487 /// and qualified by the nested-name-specifier contained in SS. 7488 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 7489 const CXXScopeSpec &SS, QualType T) { 7490 if (T.isNull()) 7491 return T; 7492 NestedNameSpecifier *NNS; 7493 if (SS.isValid()) 7494 NNS = SS.getScopeRep(); 7495 else { 7496 if (Keyword == ETK_None) 7497 return T; 7498 NNS = nullptr; 7499 } 7500 return Context.getElaboratedType(Keyword, NNS, T); 7501 } 7502 7503 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 7504 ExprResult ER = CheckPlaceholderExpr(E); 7505 if (ER.isInvalid()) return QualType(); 7506 E = ER.get(); 7507 7508 if (!getLangOpts().CPlusPlus && E->refersToBitField()) 7509 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; 7510 7511 if (!E->isTypeDependent()) { 7512 QualType T = E->getType(); 7513 if (const TagType *TT = T->getAs<TagType>()) 7514 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 7515 } 7516 return Context.getTypeOfExprType(E); 7517 } 7518 7519 /// getDecltypeForExpr - Given an expr, will return the decltype for 7520 /// that expression, according to the rules in C++11 7521 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 7522 static QualType getDecltypeForExpr(Sema &S, Expr *E) { 7523 if (E->isTypeDependent()) 7524 return S.Context.DependentTy; 7525 7526 // C++11 [dcl.type.simple]p4: 7527 // The type denoted by decltype(e) is defined as follows: 7528 // 7529 // - if e is an unparenthesized id-expression or an unparenthesized class 7530 // member access (5.2.5), decltype(e) is the type of the entity named 7531 // by e. If there is no such entity, or if e names a set of overloaded 7532 // functions, the program is ill-formed; 7533 // 7534 // We apply the same rules for Objective-C ivar and property references. 7535 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 7536 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 7537 return VD->getType(); 7538 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 7539 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 7540 return FD->getType(); 7541 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { 7542 return IR->getDecl()->getType(); 7543 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { 7544 if (PR->isExplicitProperty()) 7545 return PR->getExplicitProperty()->getType(); 7546 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { 7547 return PE->getType(); 7548 } 7549 7550 // C++11 [expr.lambda.prim]p18: 7551 // Every occurrence of decltype((x)) where x is a possibly 7552 // parenthesized id-expression that names an entity of automatic 7553 // storage duration is treated as if x were transformed into an 7554 // access to a corresponding data member of the closure type that 7555 // would have been declared if x were an odr-use of the denoted 7556 // entity. 7557 using namespace sema; 7558 if (S.getCurLambda()) { 7559 if (isa<ParenExpr>(E)) { 7560 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 7561 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 7562 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); 7563 if (!T.isNull()) 7564 return S.Context.getLValueReferenceType(T); 7565 } 7566 } 7567 } 7568 } 7569 7570 7571 // C++11 [dcl.type.simple]p4: 7572 // [...] 7573 QualType T = E->getType(); 7574 switch (E->getValueKind()) { 7575 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 7576 // type of e; 7577 case VK_XValue: T = S.Context.getRValueReferenceType(T); break; 7578 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 7579 // type of e; 7580 case VK_LValue: T = S.Context.getLValueReferenceType(T); break; 7581 // - otherwise, decltype(e) is the type of e. 7582 case VK_RValue: break; 7583 } 7584 7585 return T; 7586 } 7587 7588 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc, 7589 bool AsUnevaluated) { 7590 ExprResult ER = CheckPlaceholderExpr(E); 7591 if (ER.isInvalid()) return QualType(); 7592 E = ER.get(); 7593 7594 if (AsUnevaluated && CodeSynthesisContexts.empty() && 7595 E->HasSideEffects(Context, false)) { 7596 // The expression operand for decltype is in an unevaluated expression 7597 // context, so side effects could result in unintended consequences. 7598 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 7599 } 7600 7601 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); 7602 } 7603 7604 QualType Sema::BuildUnaryTransformType(QualType BaseType, 7605 UnaryTransformType::UTTKind UKind, 7606 SourceLocation Loc) { 7607 switch (UKind) { 7608 case UnaryTransformType::EnumUnderlyingType: 7609 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 7610 Diag(Loc, diag::err_only_enums_have_underlying_types); 7611 return QualType(); 7612 } else { 7613 QualType Underlying = BaseType; 7614 if (!BaseType->isDependentType()) { 7615 // The enum could be incomplete if we're parsing its definition or 7616 // recovering from an error. 7617 NamedDecl *FwdDecl = nullptr; 7618 if (BaseType->isIncompleteType(&FwdDecl)) { 7619 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; 7620 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; 7621 return QualType(); 7622 } 7623 7624 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 7625 assert(ED && "EnumType has no EnumDecl"); 7626 7627 DiagnoseUseOfDecl(ED, Loc); 7628 7629 Underlying = ED->getIntegerType(); 7630 assert(!Underlying.isNull()); 7631 } 7632 return Context.getUnaryTransformType(BaseType, Underlying, 7633 UnaryTransformType::EnumUnderlyingType); 7634 } 7635 } 7636 llvm_unreachable("unknown unary transform type"); 7637 } 7638 7639 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 7640 if (!T->isDependentType()) { 7641 // FIXME: It isn't entirely clear whether incomplete atomic types 7642 // are allowed or not; for simplicity, ban them for the moment. 7643 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 7644 return QualType(); 7645 7646 int DisallowedKind = -1; 7647 if (T->isArrayType()) 7648 DisallowedKind = 1; 7649 else if (T->isFunctionType()) 7650 DisallowedKind = 2; 7651 else if (T->isReferenceType()) 7652 DisallowedKind = 3; 7653 else if (T->isAtomicType()) 7654 DisallowedKind = 4; 7655 else if (T.hasQualifiers()) 7656 DisallowedKind = 5; 7657 else if (!T.isTriviallyCopyableType(Context)) 7658 // Some other non-trivially-copyable type (probably a C++ class) 7659 DisallowedKind = 6; 7660 7661 if (DisallowedKind != -1) { 7662 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 7663 return QualType(); 7664 } 7665 7666 // FIXME: Do we need any handling for ARC here? 7667 } 7668 7669 // Build the pointer type. 7670 return Context.getAtomicType(T); 7671 } 7672