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