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 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a 4047 // function. 4048 if (LangOpts.OpenCL && (T->isBlockPointerType() || T->isImageType() || 4049 T->isSamplerT() || T->isPipeType())) { 4050 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) 4051 << T << 1 /*hint off*/; 4052 D.setInvalidType(true); 4053 } 4054 4055 // Methods cannot return interface types. All ObjC objects are 4056 // passed by reference. 4057 if (T->isObjCObjectType()) { 4058 SourceLocation DiagLoc, FixitLoc; 4059 if (TInfo) { 4060 DiagLoc = TInfo->getTypeLoc().getLocStart(); 4061 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd()); 4062 } else { 4063 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 4064 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd()); 4065 } 4066 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) 4067 << 0 << T 4068 << FixItHint::CreateInsertion(FixitLoc, "*"); 4069 4070 T = Context.getObjCObjectPointerType(T); 4071 if (TInfo) { 4072 TypeLocBuilder TLB; 4073 TLB.pushFullCopy(TInfo->getTypeLoc()); 4074 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); 4075 TLoc.setStarLoc(FixitLoc); 4076 TInfo = TLB.getTypeSourceInfo(Context, T); 4077 } 4078 4079 D.setInvalidType(true); 4080 } 4081 4082 // cv-qualifiers on return types are pointless except when the type is a 4083 // class type in C++. 4084 if ((T.getCVRQualifiers() || T->isAtomicType()) && 4085 !(S.getLangOpts().CPlusPlus && 4086 (T->isDependentType() || T->isRecordType()))) { 4087 if (T->isVoidType() && !S.getLangOpts().CPlusPlus && 4088 D.getFunctionDefinitionKind() == FDK_Definition) { 4089 // [6.9.1/3] qualified void return is invalid on a C 4090 // function definition. Apparently ok on declarations and 4091 // in C++ though (!) 4092 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; 4093 } else 4094 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); 4095 } 4096 4097 // Objective-C ARC ownership qualifiers are ignored on the function 4098 // return type (by type canonicalization). Complain if this attribute 4099 // was written here. 4100 if (T.getQualifiers().hasObjCLifetime()) { 4101 SourceLocation AttrLoc; 4102 if (chunkIndex + 1 < D.getNumTypeObjects()) { 4103 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 4104 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs(); 4105 Attr; Attr = Attr->getNext()) { 4106 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 4107 AttrLoc = Attr->getLoc(); 4108 break; 4109 } 4110 } 4111 } 4112 if (AttrLoc.isInvalid()) { 4113 for (const AttributeList *Attr 4114 = D.getDeclSpec().getAttributes().getList(); 4115 Attr; Attr = Attr->getNext()) { 4116 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 4117 AttrLoc = Attr->getLoc(); 4118 break; 4119 } 4120 } 4121 } 4122 4123 if (AttrLoc.isValid()) { 4124 // The ownership attributes are almost always written via 4125 // the predefined 4126 // __strong/__weak/__autoreleasing/__unsafe_unretained. 4127 if (AttrLoc.isMacroID()) 4128 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first; 4129 4130 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 4131 << T.getQualifiers().getObjCLifetime(); 4132 } 4133 } 4134 4135 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { 4136 // C++ [dcl.fct]p6: 4137 // Types shall not be defined in return or parameter types. 4138 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 4139 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 4140 << Context.getTypeDeclType(Tag); 4141 } 4142 4143 // Exception specs are not allowed in typedefs. Complain, but add it 4144 // anyway. 4145 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus1z) 4146 S.Diag(FTI.getExceptionSpecLocBeg(), 4147 diag::err_exception_spec_in_typedef) 4148 << (D.getContext() == Declarator::AliasDeclContext || 4149 D.getContext() == Declarator::AliasTemplateContext); 4150 4151 // If we see "T var();" or "T var(T());" at block scope, it is probably 4152 // an attempt to initialize a variable, not a function declaration. 4153 if (FTI.isAmbiguous) 4154 warnAboutAmbiguousFunction(S, D, DeclType, T); 4155 4156 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex)); 4157 4158 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) { 4159 // Simple void foo(), where the incoming T is the result type. 4160 T = Context.getFunctionNoProtoType(T, EI); 4161 } else { 4162 // We allow a zero-parameter variadic function in C if the 4163 // function is marked with the "overloadable" attribute. Scan 4164 // for this attribute now. 4165 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) { 4166 bool Overloadable = false; 4167 for (const AttributeList *Attrs = D.getAttributes(); 4168 Attrs; Attrs = Attrs->getNext()) { 4169 if (Attrs->getKind() == AttributeList::AT_Overloadable) { 4170 Overloadable = true; 4171 break; 4172 } 4173 } 4174 4175 if (!Overloadable) 4176 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); 4177 } 4178 4179 if (FTI.NumParams && FTI.Params[0].Param == nullptr) { 4180 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 4181 // definition. 4182 S.Diag(FTI.Params[0].IdentLoc, 4183 diag::err_ident_list_in_fn_declaration); 4184 D.setInvalidType(true); 4185 // Recover by creating a K&R-style function type. 4186 T = Context.getFunctionNoProtoType(T, EI); 4187 break; 4188 } 4189 4190 FunctionProtoType::ExtProtoInfo EPI; 4191 EPI.ExtInfo = EI; 4192 EPI.Variadic = FTI.isVariadic; 4193 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 4194 EPI.TypeQuals = FTI.TypeQuals; 4195 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 4196 : FTI.RefQualifierIsLValueRef? RQ_LValue 4197 : RQ_RValue; 4198 4199 // Otherwise, we have a function with a parameter list that is 4200 // potentially variadic. 4201 SmallVector<QualType, 16> ParamTys; 4202 ParamTys.reserve(FTI.NumParams); 4203 4204 SmallVector<FunctionProtoType::ExtParameterInfo, 16> 4205 ExtParameterInfos(FTI.NumParams); 4206 bool HasAnyInterestingExtParameterInfos = false; 4207 4208 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 4209 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 4210 QualType ParamTy = Param->getType(); 4211 assert(!ParamTy.isNull() && "Couldn't parse type?"); 4212 4213 // Look for 'void'. void is allowed only as a single parameter to a 4214 // function with no other parameters (C99 6.7.5.3p10). We record 4215 // int(void) as a FunctionProtoType with an empty parameter list. 4216 if (ParamTy->isVoidType()) { 4217 // If this is something like 'float(int, void)', reject it. 'void' 4218 // is an incomplete type (C99 6.2.5p19) and function decls cannot 4219 // have parameters of incomplete type. 4220 if (FTI.NumParams != 1 || FTI.isVariadic) { 4221 S.Diag(DeclType.Loc, diag::err_void_only_param); 4222 ParamTy = Context.IntTy; 4223 Param->setType(ParamTy); 4224 } else if (FTI.Params[i].Ident) { 4225 // Reject, but continue to parse 'int(void abc)'. 4226 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); 4227 ParamTy = Context.IntTy; 4228 Param->setType(ParamTy); 4229 } else { 4230 // Reject, but continue to parse 'float(const void)'. 4231 if (ParamTy.hasQualifiers()) 4232 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 4233 4234 // Do not add 'void' to the list. 4235 break; 4236 } 4237 } else if (ParamTy->isHalfType()) { 4238 // Disallow half FP parameters. 4239 // FIXME: This really should be in BuildFunctionType. 4240 if (S.getLangOpts().OpenCL) { 4241 if (!S.getOpenCLOptions().cl_khr_fp16) { 4242 S.Diag(Param->getLocation(), 4243 diag::err_opencl_half_param) << ParamTy; 4244 D.setInvalidType(); 4245 Param->setInvalidDecl(); 4246 } 4247 } else if (!S.getLangOpts().HalfArgsAndReturns) { 4248 S.Diag(Param->getLocation(), 4249 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 4250 D.setInvalidType(); 4251 } 4252 } else if (!FTI.hasPrototype) { 4253 if (ParamTy->isPromotableIntegerType()) { 4254 ParamTy = Context.getPromotedIntegerType(ParamTy); 4255 Param->setKNRPromoted(true); 4256 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { 4257 if (BTy->getKind() == BuiltinType::Float) { 4258 ParamTy = Context.DoubleTy; 4259 Param->setKNRPromoted(true); 4260 } 4261 } 4262 } 4263 4264 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { 4265 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); 4266 HasAnyInterestingExtParameterInfos = true; 4267 } 4268 4269 if (auto attr = Param->getAttr<ParameterABIAttr>()) { 4270 ExtParameterInfos[i] = 4271 ExtParameterInfos[i].withABI(attr->getABI()); 4272 HasAnyInterestingExtParameterInfos = true; 4273 } 4274 4275 ParamTys.push_back(ParamTy); 4276 } 4277 4278 if (HasAnyInterestingExtParameterInfos) { 4279 EPI.ExtParameterInfos = ExtParameterInfos.data(); 4280 checkExtParameterInfos(S, ParamTys, EPI, 4281 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); 4282 } 4283 4284 SmallVector<QualType, 4> Exceptions; 4285 SmallVector<ParsedType, 2> DynamicExceptions; 4286 SmallVector<SourceRange, 2> DynamicExceptionRanges; 4287 Expr *NoexceptExpr = nullptr; 4288 4289 if (FTI.getExceptionSpecType() == EST_Dynamic) { 4290 // FIXME: It's rather inefficient to have to split into two vectors 4291 // here. 4292 unsigned N = FTI.NumExceptions; 4293 DynamicExceptions.reserve(N); 4294 DynamicExceptionRanges.reserve(N); 4295 for (unsigned I = 0; I != N; ++I) { 4296 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 4297 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 4298 } 4299 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 4300 NoexceptExpr = FTI.NoexceptExpr; 4301 } 4302 4303 S.checkExceptionSpecification(D.isFunctionDeclarationContext(), 4304 FTI.getExceptionSpecType(), 4305 DynamicExceptions, 4306 DynamicExceptionRanges, 4307 NoexceptExpr, 4308 Exceptions, 4309 EPI.ExceptionSpec); 4310 4311 T = Context.getFunctionType(T, ParamTys, EPI); 4312 } 4313 break; 4314 } 4315 case DeclaratorChunk::MemberPointer: { 4316 // The scope spec must refer to a class, or be dependent. 4317 CXXScopeSpec &SS = DeclType.Mem.Scope(); 4318 QualType ClsType; 4319 4320 // Handle pointer nullability. 4321 inferPointerNullability(SimplePointerKind::MemberPointer, 4322 DeclType.Loc, DeclType.getAttrListRef()); 4323 4324 if (SS.isInvalid()) { 4325 // Avoid emitting extra errors if we already errored on the scope. 4326 D.setInvalidType(true); 4327 } else if (S.isDependentScopeSpecifier(SS) || 4328 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 4329 NestedNameSpecifier *NNS = SS.getScopeRep(); 4330 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 4331 switch (NNS->getKind()) { 4332 case NestedNameSpecifier::Identifier: 4333 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 4334 NNS->getAsIdentifier()); 4335 break; 4336 4337 case NestedNameSpecifier::Namespace: 4338 case NestedNameSpecifier::NamespaceAlias: 4339 case NestedNameSpecifier::Global: 4340 case NestedNameSpecifier::Super: 4341 llvm_unreachable("Nested-name-specifier must name a type"); 4342 4343 case NestedNameSpecifier::TypeSpec: 4344 case NestedNameSpecifier::TypeSpecWithTemplate: 4345 ClsType = QualType(NNS->getAsType(), 0); 4346 // Note: if the NNS has a prefix and ClsType is a nondependent 4347 // TemplateSpecializationType, then the NNS prefix is NOT included 4348 // in ClsType; hence we wrap ClsType into an ElaboratedType. 4349 // NOTE: in particular, no wrap occurs if ClsType already is an 4350 // Elaborated, DependentName, or DependentTemplateSpecialization. 4351 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 4352 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 4353 break; 4354 } 4355 } else { 4356 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 4357 diag::err_illegal_decl_mempointer_in_nonclass) 4358 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 4359 << DeclType.Mem.Scope().getRange(); 4360 D.setInvalidType(true); 4361 } 4362 4363 if (!ClsType.isNull()) 4364 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, 4365 D.getIdentifier()); 4366 if (T.isNull()) { 4367 T = Context.IntTy; 4368 D.setInvalidType(true); 4369 } else if (DeclType.Mem.TypeQuals) { 4370 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 4371 } 4372 break; 4373 } 4374 4375 case DeclaratorChunk::Pipe: { 4376 T = S.BuildPipeType(T, DeclType.Loc ); 4377 break; 4378 } 4379 } 4380 4381 if (T.isNull()) { 4382 D.setInvalidType(true); 4383 T = Context.IntTy; 4384 } 4385 4386 // See if there are any attributes on this declarator chunk. 4387 processTypeAttrs(state, T, TAL_DeclChunk, 4388 const_cast<AttributeList *>(DeclType.getAttrs())); 4389 } 4390 4391 assert(!T.isNull() && "T must not be null after this point"); 4392 4393 if (LangOpts.CPlusPlus && T->isFunctionType()) { 4394 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 4395 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 4396 4397 // C++ 8.3.5p4: 4398 // A cv-qualifier-seq shall only be part of the function type 4399 // for a nonstatic member function, the function type to which a pointer 4400 // to member refers, or the top-level function type of a function typedef 4401 // declaration. 4402 // 4403 // Core issue 547 also allows cv-qualifiers on function types that are 4404 // top-level template type arguments. 4405 bool FreeFunction; 4406 if (!D.getCXXScopeSpec().isSet()) { 4407 FreeFunction = ((D.getContext() != Declarator::MemberContext && 4408 D.getContext() != Declarator::LambdaExprContext) || 4409 D.getDeclSpec().isFriendSpecified()); 4410 } else { 4411 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 4412 FreeFunction = (DC && !DC->isRecord()); 4413 } 4414 4415 // C++11 [dcl.fct]p6 (w/DR1417): 4416 // An attempt to specify a function type with a cv-qualifier-seq or a 4417 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 4418 // - the function type for a non-static member function, 4419 // - the function type to which a pointer to member refers, 4420 // - the top-level function type of a function typedef declaration or 4421 // alias-declaration, 4422 // - the type-id in the default argument of a type-parameter, or 4423 // - the type-id of a template-argument for a type-parameter 4424 // 4425 // FIXME: Checking this here is insufficient. We accept-invalid on: 4426 // 4427 // template<typename T> struct S { void f(T); }; 4428 // S<int() const> s; 4429 // 4430 // ... for instance. 4431 if (IsQualifiedFunction && 4432 !(!FreeFunction && 4433 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 4434 !IsTypedefName && 4435 D.getContext() != Declarator::TemplateTypeArgContext) { 4436 SourceLocation Loc = D.getLocStart(); 4437 SourceRange RemovalRange; 4438 unsigned I; 4439 if (D.isFunctionDeclarator(I)) { 4440 SmallVector<SourceLocation, 4> RemovalLocs; 4441 const DeclaratorChunk &Chunk = D.getTypeObject(I); 4442 assert(Chunk.Kind == DeclaratorChunk::Function); 4443 if (Chunk.Fun.hasRefQualifier()) 4444 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 4445 if (Chunk.Fun.TypeQuals & Qualifiers::Const) 4446 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); 4447 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) 4448 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); 4449 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) 4450 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); 4451 if (!RemovalLocs.empty()) { 4452 std::sort(RemovalLocs.begin(), RemovalLocs.end(), 4453 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 4454 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 4455 Loc = RemovalLocs.front(); 4456 } 4457 } 4458 4459 S.Diag(Loc, diag::err_invalid_qualified_function_type) 4460 << FreeFunction << D.isFunctionDeclarator() << T 4461 << getFunctionQualifiersAsString(FnTy) 4462 << FixItHint::CreateRemoval(RemovalRange); 4463 4464 // Strip the cv-qualifiers and ref-qualifiers from the type. 4465 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 4466 EPI.TypeQuals = 0; 4467 EPI.RefQualifier = RQ_None; 4468 4469 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), 4470 EPI); 4471 // Rebuild any parens around the identifier in the function type. 4472 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4473 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 4474 break; 4475 T = S.BuildParenType(T); 4476 } 4477 } 4478 } 4479 4480 // Apply any undistributed attributes from the declarator. 4481 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); 4482 4483 // Diagnose any ignored type attributes. 4484 state.diagnoseIgnoredTypeAttrs(T); 4485 4486 // C++0x [dcl.constexpr]p9: 4487 // A constexpr specifier used in an object declaration declares the object 4488 // as const. 4489 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 4490 T.addConst(); 4491 } 4492 4493 // If there was an ellipsis in the declarator, the declaration declares a 4494 // parameter pack whose type may be a pack expansion type. 4495 if (D.hasEllipsis()) { 4496 // C++0x [dcl.fct]p13: 4497 // A declarator-id or abstract-declarator containing an ellipsis shall 4498 // only be used in a parameter-declaration. Such a parameter-declaration 4499 // is a parameter pack (14.5.3). [...] 4500 switch (D.getContext()) { 4501 case Declarator::PrototypeContext: 4502 case Declarator::LambdaExprParameterContext: 4503 // C++0x [dcl.fct]p13: 4504 // [...] When it is part of a parameter-declaration-clause, the 4505 // parameter pack is a function parameter pack (14.5.3). The type T 4506 // of the declarator-id of the function parameter pack shall contain 4507 // a template parameter pack; each template parameter pack in T is 4508 // expanded by the function parameter pack. 4509 // 4510 // We represent function parameter packs as function parameters whose 4511 // type is a pack expansion. 4512 if (!T->containsUnexpandedParameterPack()) { 4513 S.Diag(D.getEllipsisLoc(), 4514 diag::err_function_parameter_pack_without_parameter_packs) 4515 << T << D.getSourceRange(); 4516 D.setEllipsisLoc(SourceLocation()); 4517 } else { 4518 T = Context.getPackExpansionType(T, None); 4519 } 4520 break; 4521 case Declarator::TemplateParamContext: 4522 // C++0x [temp.param]p15: 4523 // If a template-parameter is a [...] is a parameter-declaration that 4524 // declares a parameter pack (8.3.5), then the template-parameter is a 4525 // template parameter pack (14.5.3). 4526 // 4527 // Note: core issue 778 clarifies that, if there are any unexpanded 4528 // parameter packs in the type of the non-type template parameter, then 4529 // it expands those parameter packs. 4530 if (T->containsUnexpandedParameterPack()) 4531 T = Context.getPackExpansionType(T, None); 4532 else 4533 S.Diag(D.getEllipsisLoc(), 4534 LangOpts.CPlusPlus11 4535 ? diag::warn_cxx98_compat_variadic_templates 4536 : diag::ext_variadic_templates); 4537 break; 4538 4539 case Declarator::FileContext: 4540 case Declarator::KNRTypeListContext: 4541 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here? 4542 case Declarator::ObjCResultContext: // FIXME: special diagnostic here? 4543 case Declarator::TypeNameContext: 4544 case Declarator::CXXNewContext: 4545 case Declarator::AliasDeclContext: 4546 case Declarator::AliasTemplateContext: 4547 case Declarator::MemberContext: 4548 case Declarator::BlockContext: 4549 case Declarator::ForContext: 4550 case Declarator::InitStmtContext: 4551 case Declarator::ConditionContext: 4552 case Declarator::CXXCatchContext: 4553 case Declarator::ObjCCatchContext: 4554 case Declarator::BlockLiteralContext: 4555 case Declarator::LambdaExprContext: 4556 case Declarator::ConversionIdContext: 4557 case Declarator::TrailingReturnContext: 4558 case Declarator::TemplateTypeArgContext: 4559 // FIXME: We may want to allow parameter packs in block-literal contexts 4560 // in the future. 4561 S.Diag(D.getEllipsisLoc(), 4562 diag::err_ellipsis_in_declarator_not_parameter); 4563 D.setEllipsisLoc(SourceLocation()); 4564 break; 4565 } 4566 } 4567 4568 assert(!T.isNull() && "T must not be null at the end of this function"); 4569 if (D.isInvalidType()) 4570 return Context.getTrivialTypeSourceInfo(T); 4571 4572 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); 4573 } 4574 4575 /// GetTypeForDeclarator - Convert the type for the specified 4576 /// declarator to Type instances. 4577 /// 4578 /// The result of this call will never be null, but the associated 4579 /// type may be a null type if there's an unrecoverable error. 4580 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 4581 // Determine the type of the declarator. Not all forms of declarator 4582 // have a type. 4583 4584 TypeProcessingState state(*this, D); 4585 4586 TypeSourceInfo *ReturnTypeInfo = nullptr; 4587 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 4588 4589 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 4590 inferARCWriteback(state, T); 4591 4592 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 4593 } 4594 4595 static void transferARCOwnershipToDeclSpec(Sema &S, 4596 QualType &declSpecTy, 4597 Qualifiers::ObjCLifetime ownership) { 4598 if (declSpecTy->isObjCRetainableType() && 4599 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 4600 Qualifiers qs; 4601 qs.addObjCLifetime(ownership); 4602 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 4603 } 4604 } 4605 4606 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 4607 Qualifiers::ObjCLifetime ownership, 4608 unsigned chunkIndex) { 4609 Sema &S = state.getSema(); 4610 Declarator &D = state.getDeclarator(); 4611 4612 // Look for an explicit lifetime attribute. 4613 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 4614 for (const AttributeList *attr = chunk.getAttrs(); attr; 4615 attr = attr->getNext()) 4616 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 4617 return; 4618 4619 const char *attrStr = nullptr; 4620 switch (ownership) { 4621 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 4622 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 4623 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 4624 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 4625 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 4626 } 4627 4628 IdentifierLoc *Arg = new (S.Context) IdentifierLoc; 4629 Arg->Ident = &S.Context.Idents.get(attrStr); 4630 Arg->Loc = SourceLocation(); 4631 4632 ArgsUnion Args(Arg); 4633 4634 // If there wasn't one, add one (with an invalid source location 4635 // so that we don't make an AttributedType for it). 4636 AttributeList *attr = D.getAttributePool() 4637 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), 4638 /*scope*/ nullptr, SourceLocation(), 4639 /*args*/ &Args, 1, AttributeList::AS_GNU); 4640 spliceAttrIntoList(*attr, chunk.getAttrListRef()); 4641 4642 // TODO: mark whether we did this inference? 4643 } 4644 4645 /// \brief Used for transferring ownership in casts resulting in l-values. 4646 static void transferARCOwnership(TypeProcessingState &state, 4647 QualType &declSpecTy, 4648 Qualifiers::ObjCLifetime ownership) { 4649 Sema &S = state.getSema(); 4650 Declarator &D = state.getDeclarator(); 4651 4652 int inner = -1; 4653 bool hasIndirection = false; 4654 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4655 DeclaratorChunk &chunk = D.getTypeObject(i); 4656 switch (chunk.Kind) { 4657 case DeclaratorChunk::Paren: 4658 // Ignore parens. 4659 break; 4660 4661 case DeclaratorChunk::Array: 4662 case DeclaratorChunk::Reference: 4663 case DeclaratorChunk::Pointer: 4664 if (inner != -1) 4665 hasIndirection = true; 4666 inner = i; 4667 break; 4668 4669 case DeclaratorChunk::BlockPointer: 4670 if (inner != -1) 4671 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 4672 return; 4673 4674 case DeclaratorChunk::Function: 4675 case DeclaratorChunk::MemberPointer: 4676 case DeclaratorChunk::Pipe: 4677 return; 4678 } 4679 } 4680 4681 if (inner == -1) 4682 return; 4683 4684 DeclaratorChunk &chunk = D.getTypeObject(inner); 4685 if (chunk.Kind == DeclaratorChunk::Pointer) { 4686 if (declSpecTy->isObjCRetainableType()) 4687 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 4688 if (declSpecTy->isObjCObjectType() && hasIndirection) 4689 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 4690 } else { 4691 assert(chunk.Kind == DeclaratorChunk::Array || 4692 chunk.Kind == DeclaratorChunk::Reference); 4693 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 4694 } 4695 } 4696 4697 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 4698 TypeProcessingState state(*this, D); 4699 4700 TypeSourceInfo *ReturnTypeInfo = nullptr; 4701 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 4702 4703 if (getLangOpts().ObjC1) { 4704 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 4705 if (ownership != Qualifiers::OCL_None) 4706 transferARCOwnership(state, declSpecTy, ownership); 4707 } 4708 4709 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 4710 } 4711 4712 /// Map an AttributedType::Kind to an AttributeList::Kind. 4713 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 4714 switch (kind) { 4715 case AttributedType::attr_address_space: 4716 return AttributeList::AT_AddressSpace; 4717 case AttributedType::attr_regparm: 4718 return AttributeList::AT_Regparm; 4719 case AttributedType::attr_vector_size: 4720 return AttributeList::AT_VectorSize; 4721 case AttributedType::attr_neon_vector_type: 4722 return AttributeList::AT_NeonVectorType; 4723 case AttributedType::attr_neon_polyvector_type: 4724 return AttributeList::AT_NeonPolyVectorType; 4725 case AttributedType::attr_objc_gc: 4726 return AttributeList::AT_ObjCGC; 4727 case AttributedType::attr_objc_ownership: 4728 case AttributedType::attr_objc_inert_unsafe_unretained: 4729 return AttributeList::AT_ObjCOwnership; 4730 case AttributedType::attr_noreturn: 4731 return AttributeList::AT_NoReturn; 4732 case AttributedType::attr_cdecl: 4733 return AttributeList::AT_CDecl; 4734 case AttributedType::attr_fastcall: 4735 return AttributeList::AT_FastCall; 4736 case AttributedType::attr_stdcall: 4737 return AttributeList::AT_StdCall; 4738 case AttributedType::attr_thiscall: 4739 return AttributeList::AT_ThisCall; 4740 case AttributedType::attr_pascal: 4741 return AttributeList::AT_Pascal; 4742 case AttributedType::attr_swiftcall: 4743 return AttributeList::AT_SwiftCall; 4744 case AttributedType::attr_vectorcall: 4745 return AttributeList::AT_VectorCall; 4746 case AttributedType::attr_pcs: 4747 case AttributedType::attr_pcs_vfp: 4748 return AttributeList::AT_Pcs; 4749 case AttributedType::attr_inteloclbicc: 4750 return AttributeList::AT_IntelOclBicc; 4751 case AttributedType::attr_ms_abi: 4752 return AttributeList::AT_MSABI; 4753 case AttributedType::attr_sysv_abi: 4754 return AttributeList::AT_SysVABI; 4755 case AttributedType::attr_preserve_most: 4756 return AttributeList::AT_PreserveMost; 4757 case AttributedType::attr_preserve_all: 4758 return AttributeList::AT_PreserveAll; 4759 case AttributedType::attr_ptr32: 4760 return AttributeList::AT_Ptr32; 4761 case AttributedType::attr_ptr64: 4762 return AttributeList::AT_Ptr64; 4763 case AttributedType::attr_sptr: 4764 return AttributeList::AT_SPtr; 4765 case AttributedType::attr_uptr: 4766 return AttributeList::AT_UPtr; 4767 case AttributedType::attr_nonnull: 4768 return AttributeList::AT_TypeNonNull; 4769 case AttributedType::attr_nullable: 4770 return AttributeList::AT_TypeNullable; 4771 case AttributedType::attr_null_unspecified: 4772 return AttributeList::AT_TypeNullUnspecified; 4773 case AttributedType::attr_objc_kindof: 4774 return AttributeList::AT_ObjCKindOf; 4775 } 4776 llvm_unreachable("unexpected attribute kind!"); 4777 } 4778 4779 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 4780 const AttributeList *attrs, 4781 const AttributeList *DeclAttrs = nullptr) { 4782 // DeclAttrs and attrs cannot be both empty. 4783 assert((attrs || DeclAttrs) && 4784 "no type attributes in the expected location!"); 4785 4786 AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind()); 4787 // Try to search for an attribute of matching kind in attrs list. 4788 while (attrs && attrs->getKind() != parsedKind) 4789 attrs = attrs->getNext(); 4790 if (!attrs) { 4791 // No matching type attribute in attrs list found. 4792 // Try searching through C++11 attributes in the declarator attribute list. 4793 while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() || 4794 DeclAttrs->getKind() != parsedKind)) 4795 DeclAttrs = DeclAttrs->getNext(); 4796 attrs = DeclAttrs; 4797 } 4798 4799 assert(attrs && "no matching type attribute in expected location!"); 4800 4801 TL.setAttrNameLoc(attrs->getLoc()); 4802 if (TL.hasAttrExprOperand()) { 4803 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind"); 4804 TL.setAttrExprOperand(attrs->getArgAsExpr(0)); 4805 } else if (TL.hasAttrEnumOperand()) { 4806 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) && 4807 "unexpected attribute operand kind"); 4808 if (attrs->isArgIdent(0)) 4809 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc); 4810 else 4811 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc()); 4812 } 4813 4814 // FIXME: preserve this information to here. 4815 if (TL.hasAttrOperand()) 4816 TL.setAttrOperandParensRange(SourceRange()); 4817 } 4818 4819 namespace { 4820 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 4821 ASTContext &Context; 4822 const DeclSpec &DS; 4823 4824 public: 4825 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 4826 : Context(Context), DS(DS) {} 4827 4828 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 4829 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 4830 Visit(TL.getModifiedLoc()); 4831 } 4832 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 4833 Visit(TL.getUnqualifiedLoc()); 4834 } 4835 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 4836 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 4837 } 4838 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 4839 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 4840 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 4841 // addition field. What we have is good enough for dispay of location 4842 // of 'fixit' on interface name. 4843 TL.setNameEndLoc(DS.getLocEnd()); 4844 } 4845 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 4846 TypeSourceInfo *RepTInfo = nullptr; 4847 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 4848 TL.copy(RepTInfo->getTypeLoc()); 4849 } 4850 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 4851 TypeSourceInfo *RepTInfo = nullptr; 4852 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 4853 TL.copy(RepTInfo->getTypeLoc()); 4854 } 4855 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 4856 TypeSourceInfo *TInfo = nullptr; 4857 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4858 4859 // If we got no declarator info from previous Sema routines, 4860 // just fill with the typespec loc. 4861 if (!TInfo) { 4862 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 4863 return; 4864 } 4865 4866 TypeLoc OldTL = TInfo->getTypeLoc(); 4867 if (TInfo->getType()->getAs<ElaboratedType>()) { 4868 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 4869 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 4870 .castAs<TemplateSpecializationTypeLoc>(); 4871 TL.copy(NamedTL); 4872 } else { 4873 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 4874 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); 4875 } 4876 4877 } 4878 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 4879 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 4880 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 4881 TL.setParensRange(DS.getTypeofParensRange()); 4882 } 4883 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 4884 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 4885 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 4886 TL.setParensRange(DS.getTypeofParensRange()); 4887 assert(DS.getRepAsType()); 4888 TypeSourceInfo *TInfo = nullptr; 4889 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4890 TL.setUnderlyingTInfo(TInfo); 4891 } 4892 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 4893 // FIXME: This holds only because we only have one unary transform. 4894 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 4895 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 4896 TL.setParensRange(DS.getTypeofParensRange()); 4897 assert(DS.getRepAsType()); 4898 TypeSourceInfo *TInfo = nullptr; 4899 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4900 TL.setUnderlyingTInfo(TInfo); 4901 } 4902 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 4903 // By default, use the source location of the type specifier. 4904 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 4905 if (TL.needsExtraLocalData()) { 4906 // Set info for the written builtin specifiers. 4907 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 4908 // Try to have a meaningful source location. 4909 if (TL.getWrittenSignSpec() != TSS_unspecified) 4910 TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); 4911 if (TL.getWrittenWidthSpec() != TSW_unspecified) 4912 TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); 4913 } 4914 } 4915 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 4916 ElaboratedTypeKeyword Keyword 4917 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 4918 if (DS.getTypeSpecType() == TST_typename) { 4919 TypeSourceInfo *TInfo = nullptr; 4920 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4921 if (TInfo) { 4922 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 4923 return; 4924 } 4925 } 4926 TL.setElaboratedKeywordLoc(Keyword != ETK_None 4927 ? DS.getTypeSpecTypeLoc() 4928 : SourceLocation()); 4929 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 4930 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4931 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 4932 } 4933 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 4934 assert(DS.getTypeSpecType() == TST_typename); 4935 TypeSourceInfo *TInfo = nullptr; 4936 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4937 assert(TInfo); 4938 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 4939 } 4940 void VisitDependentTemplateSpecializationTypeLoc( 4941 DependentTemplateSpecializationTypeLoc TL) { 4942 assert(DS.getTypeSpecType() == TST_typename); 4943 TypeSourceInfo *TInfo = nullptr; 4944 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4945 assert(TInfo); 4946 TL.copy( 4947 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 4948 } 4949 void VisitTagTypeLoc(TagTypeLoc TL) { 4950 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 4951 } 4952 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 4953 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 4954 // or an _Atomic qualifier. 4955 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 4956 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 4957 TL.setParensRange(DS.getTypeofParensRange()); 4958 4959 TypeSourceInfo *TInfo = nullptr; 4960 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4961 assert(TInfo); 4962 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 4963 } else { 4964 TL.setKWLoc(DS.getAtomicSpecLoc()); 4965 // No parens, to indicate this was spelled as an _Atomic qualifier. 4966 TL.setParensRange(SourceRange()); 4967 Visit(TL.getValueLoc()); 4968 } 4969 } 4970 4971 void VisitPipeTypeLoc(PipeTypeLoc TL) { 4972 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 4973 4974 TypeSourceInfo *TInfo = nullptr; 4975 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4976 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 4977 } 4978 4979 void VisitTypeLoc(TypeLoc TL) { 4980 // FIXME: add other typespec types and change this to an assert. 4981 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 4982 } 4983 }; 4984 4985 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 4986 ASTContext &Context; 4987 const DeclaratorChunk &Chunk; 4988 4989 public: 4990 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 4991 : Context(Context), Chunk(Chunk) {} 4992 4993 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 4994 llvm_unreachable("qualified type locs not expected here!"); 4995 } 4996 void VisitDecayedTypeLoc(DecayedTypeLoc TL) { 4997 llvm_unreachable("decayed type locs not expected here!"); 4998 } 4999 5000 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 5001 fillAttributedTypeLoc(TL, Chunk.getAttrs()); 5002 } 5003 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 5004 // nothing 5005 } 5006 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 5007 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 5008 TL.setCaretLoc(Chunk.Loc); 5009 } 5010 void VisitPointerTypeLoc(PointerTypeLoc TL) { 5011 assert(Chunk.Kind == DeclaratorChunk::Pointer); 5012 TL.setStarLoc(Chunk.Loc); 5013 } 5014 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 5015 assert(Chunk.Kind == DeclaratorChunk::Pointer); 5016 TL.setStarLoc(Chunk.Loc); 5017 } 5018 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 5019 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 5020 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 5021 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 5022 5023 const Type* ClsTy = TL.getClass(); 5024 QualType ClsQT = QualType(ClsTy, 0); 5025 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 5026 // Now copy source location info into the type loc component. 5027 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 5028 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 5029 case NestedNameSpecifier::Identifier: 5030 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 5031 { 5032 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 5033 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 5034 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 5035 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 5036 } 5037 break; 5038 5039 case NestedNameSpecifier::TypeSpec: 5040 case NestedNameSpecifier::TypeSpecWithTemplate: 5041 if (isa<ElaboratedType>(ClsTy)) { 5042 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 5043 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 5044 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 5045 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 5046 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 5047 } else { 5048 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 5049 } 5050 break; 5051 5052 case NestedNameSpecifier::Namespace: 5053 case NestedNameSpecifier::NamespaceAlias: 5054 case NestedNameSpecifier::Global: 5055 case NestedNameSpecifier::Super: 5056 llvm_unreachable("Nested-name-specifier must name a type"); 5057 } 5058 5059 // Finally fill in MemberPointerLocInfo fields. 5060 TL.setStarLoc(Chunk.Loc); 5061 TL.setClassTInfo(ClsTInfo); 5062 } 5063 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 5064 assert(Chunk.Kind == DeclaratorChunk::Reference); 5065 // 'Amp' is misleading: this might have been originally 5066 /// spelled with AmpAmp. 5067 TL.setAmpLoc(Chunk.Loc); 5068 } 5069 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 5070 assert(Chunk.Kind == DeclaratorChunk::Reference); 5071 assert(!Chunk.Ref.LValueRef); 5072 TL.setAmpAmpLoc(Chunk.Loc); 5073 } 5074 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 5075 assert(Chunk.Kind == DeclaratorChunk::Array); 5076 TL.setLBracketLoc(Chunk.Loc); 5077 TL.setRBracketLoc(Chunk.EndLoc); 5078 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 5079 } 5080 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 5081 assert(Chunk.Kind == DeclaratorChunk::Function); 5082 TL.setLocalRangeBegin(Chunk.Loc); 5083 TL.setLocalRangeEnd(Chunk.EndLoc); 5084 5085 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 5086 TL.setLParenLoc(FTI.getLParenLoc()); 5087 TL.setRParenLoc(FTI.getRParenLoc()); 5088 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { 5089 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 5090 TL.setParam(tpi++, Param); 5091 } 5092 // FIXME: exception specs 5093 } 5094 void VisitParenTypeLoc(ParenTypeLoc TL) { 5095 assert(Chunk.Kind == DeclaratorChunk::Paren); 5096 TL.setLParenLoc(Chunk.Loc); 5097 TL.setRParenLoc(Chunk.EndLoc); 5098 } 5099 void VisitPipeTypeLoc(PipeTypeLoc TL) { 5100 assert(Chunk.Kind == DeclaratorChunk::Pipe); 5101 TL.setKWLoc(Chunk.Loc); 5102 } 5103 5104 void VisitTypeLoc(TypeLoc TL) { 5105 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 5106 } 5107 }; 5108 } // end anonymous namespace 5109 5110 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 5111 SourceLocation Loc; 5112 switch (Chunk.Kind) { 5113 case DeclaratorChunk::Function: 5114 case DeclaratorChunk::Array: 5115 case DeclaratorChunk::Paren: 5116 case DeclaratorChunk::Pipe: 5117 llvm_unreachable("cannot be _Atomic qualified"); 5118 5119 case DeclaratorChunk::Pointer: 5120 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); 5121 break; 5122 5123 case DeclaratorChunk::BlockPointer: 5124 case DeclaratorChunk::Reference: 5125 case DeclaratorChunk::MemberPointer: 5126 // FIXME: Provide a source location for the _Atomic keyword. 5127 break; 5128 } 5129 5130 ATL.setKWLoc(Loc); 5131 ATL.setParensRange(SourceRange()); 5132 } 5133 5134 /// \brief Create and instantiate a TypeSourceInfo with type source information. 5135 /// 5136 /// \param T QualType referring to the type as written in source code. 5137 /// 5138 /// \param ReturnTypeInfo For declarators whose return type does not show 5139 /// up in the normal place in the declaration specifiers (such as a C++ 5140 /// conversion function), this pointer will refer to a type source information 5141 /// for that return type. 5142 TypeSourceInfo * 5143 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 5144 TypeSourceInfo *ReturnTypeInfo) { 5145 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 5146 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 5147 const AttributeList *DeclAttrs = D.getAttributes(); 5148 5149 // Handle parameter packs whose type is a pack expansion. 5150 if (isa<PackExpansionType>(T)) { 5151 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 5152 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 5153 } 5154 5155 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 5156 // An AtomicTypeLoc might be produced by an atomic qualifier in this 5157 // declarator chunk. 5158 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 5159 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 5160 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 5161 } 5162 5163 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 5164 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs); 5165 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 5166 } 5167 5168 // FIXME: Ordering here? 5169 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) 5170 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 5171 5172 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 5173 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 5174 } 5175 5176 // If we have different source information for the return type, use 5177 // that. This really only applies to C++ conversion functions. 5178 if (ReturnTypeInfo) { 5179 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 5180 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 5181 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 5182 } else { 5183 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 5184 } 5185 5186 return TInfo; 5187 } 5188 5189 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 5190 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 5191 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 5192 // and Sema during declaration parsing. Try deallocating/caching them when 5193 // it's appropriate, instead of allocating them and keeping them around. 5194 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 5195 TypeAlignment); 5196 new (LocT) LocInfoType(T, TInfo); 5197 assert(LocT->getTypeClass() != T->getTypeClass() && 5198 "LocInfoType's TypeClass conflicts with an existing Type class"); 5199 return ParsedType::make(QualType(LocT, 0)); 5200 } 5201 5202 void LocInfoType::getAsStringInternal(std::string &Str, 5203 const PrintingPolicy &Policy) const { 5204 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 5205 " was used directly instead of getting the QualType through" 5206 " GetTypeFromParser"); 5207 } 5208 5209 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 5210 // C99 6.7.6: Type names have no identifier. This is already validated by 5211 // the parser. 5212 assert(D.getIdentifier() == nullptr && 5213 "Type name should have no identifier!"); 5214 5215 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5216 QualType T = TInfo->getType(); 5217 if (D.isInvalidType()) 5218 return true; 5219 5220 // Make sure there are no unused decl attributes on the declarator. 5221 // We don't want to do this for ObjC parameters because we're going 5222 // to apply them to the actual parameter declaration. 5223 // Likewise, we don't want to do this for alias declarations, because 5224 // we are actually going to build a declaration from this eventually. 5225 if (D.getContext() != Declarator::ObjCParameterContext && 5226 D.getContext() != Declarator::AliasDeclContext && 5227 D.getContext() != Declarator::AliasTemplateContext) 5228 checkUnusedDeclAttributes(D); 5229 5230 if (getLangOpts().CPlusPlus) { 5231 // Check that there are no default arguments (C++ only). 5232 CheckExtraCXXDefaultArguments(D); 5233 } 5234 5235 return CreateParsedType(T, TInfo); 5236 } 5237 5238 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 5239 QualType T = Context.getObjCInstanceType(); 5240 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 5241 return CreateParsedType(T, TInfo); 5242 } 5243 5244 //===----------------------------------------------------------------------===// 5245 // Type Attribute Processing 5246 //===----------------------------------------------------------------------===// 5247 5248 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 5249 /// specified type. The attribute contains 1 argument, the id of the address 5250 /// space for the type. 5251 static void HandleAddressSpaceTypeAttribute(QualType &Type, 5252 const AttributeList &Attr, Sema &S){ 5253 5254 // If this type is already address space qualified, reject it. 5255 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by 5256 // qualifiers for two or more different address spaces." 5257 if (Type.getAddressSpace()) { 5258 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 5259 Attr.setInvalid(); 5260 return; 5261 } 5262 5263 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 5264 // qualified by an address-space qualifier." 5265 if (Type->isFunctionType()) { 5266 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 5267 Attr.setInvalid(); 5268 return; 5269 } 5270 5271 unsigned ASIdx; 5272 if (Attr.getKind() == AttributeList::AT_AddressSpace) { 5273 // Check the attribute arguments. 5274 if (Attr.getNumArgs() != 1) { 5275 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 5276 << Attr.getName() << 1; 5277 Attr.setInvalid(); 5278 return; 5279 } 5280 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 5281 llvm::APSInt addrSpace(32); 5282 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 5283 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 5284 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 5285 << Attr.getName() << AANT_ArgumentIntegerConstant 5286 << ASArgExpr->getSourceRange(); 5287 Attr.setInvalid(); 5288 return; 5289 } 5290 5291 // Bounds checking. 5292 if (addrSpace.isSigned()) { 5293 if (addrSpace.isNegative()) { 5294 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 5295 << ASArgExpr->getSourceRange(); 5296 Attr.setInvalid(); 5297 return; 5298 } 5299 addrSpace.setIsSigned(false); 5300 } 5301 llvm::APSInt max(addrSpace.getBitWidth()); 5302 max = Qualifiers::MaxAddressSpace; 5303 if (addrSpace > max) { 5304 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 5305 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange(); 5306 Attr.setInvalid(); 5307 return; 5308 } 5309 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 5310 } else { 5311 // The keyword-based type attributes imply which address space to use. 5312 switch (Attr.getKind()) { 5313 case AttributeList::AT_OpenCLGlobalAddressSpace: 5314 ASIdx = LangAS::opencl_global; break; 5315 case AttributeList::AT_OpenCLLocalAddressSpace: 5316 ASIdx = LangAS::opencl_local; break; 5317 case AttributeList::AT_OpenCLConstantAddressSpace: 5318 ASIdx = LangAS::opencl_constant; break; 5319 case AttributeList::AT_OpenCLGenericAddressSpace: 5320 ASIdx = LangAS::opencl_generic; break; 5321 default: 5322 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace); 5323 ASIdx = 0; break; 5324 } 5325 } 5326 5327 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 5328 } 5329 5330 /// Does this type have a "direct" ownership qualifier? That is, 5331 /// is it written like "__strong id", as opposed to something like 5332 /// "typeof(foo)", where that happens to be strong? 5333 static bool hasDirectOwnershipQualifier(QualType type) { 5334 // Fast path: no qualifier at all. 5335 assert(type.getQualifiers().hasObjCLifetime()); 5336 5337 while (true) { 5338 // __strong id 5339 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { 5340 if (attr->getAttrKind() == AttributedType::attr_objc_ownership) 5341 return true; 5342 5343 type = attr->getModifiedType(); 5344 5345 // X *__strong (...) 5346 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { 5347 type = paren->getInnerType(); 5348 5349 // That's it for things we want to complain about. In particular, 5350 // we do not want to look through typedefs, typeof(expr), 5351 // typeof(type), or any other way that the type is somehow 5352 // abstracted. 5353 } else { 5354 5355 return false; 5356 } 5357 } 5358 } 5359 5360 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 5361 /// attribute on the specified type. 5362 /// 5363 /// Returns 'true' if the attribute was handled. 5364 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 5365 AttributeList &attr, 5366 QualType &type) { 5367 bool NonObjCPointer = false; 5368 5369 if (!type->isDependentType() && !type->isUndeducedType()) { 5370 if (const PointerType *ptr = type->getAs<PointerType>()) { 5371 QualType pointee = ptr->getPointeeType(); 5372 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 5373 return false; 5374 // It is important not to lose the source info that there was an attribute 5375 // applied to non-objc pointer. We will create an attributed type but 5376 // its type will be the same as the original type. 5377 NonObjCPointer = true; 5378 } else if (!type->isObjCRetainableType()) { 5379 return false; 5380 } 5381 5382 // Don't accept an ownership attribute in the declspec if it would 5383 // just be the return type of a block pointer. 5384 if (state.isProcessingDeclSpec()) { 5385 Declarator &D = state.getDeclarator(); 5386 if (maybeMovePastReturnType(D, D.getNumTypeObjects(), 5387 /*onlyBlockPointers=*/true)) 5388 return false; 5389 } 5390 } 5391 5392 Sema &S = state.getSema(); 5393 SourceLocation AttrLoc = attr.getLoc(); 5394 if (AttrLoc.isMacroID()) 5395 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first; 5396 5397 if (!attr.isArgIdent(0)) { 5398 S.Diag(AttrLoc, diag::err_attribute_argument_type) 5399 << attr.getName() << AANT_ArgumentString; 5400 attr.setInvalid(); 5401 return true; 5402 } 5403 5404 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 5405 Qualifiers::ObjCLifetime lifetime; 5406 if (II->isStr("none")) 5407 lifetime = Qualifiers::OCL_ExplicitNone; 5408 else if (II->isStr("strong")) 5409 lifetime = Qualifiers::OCL_Strong; 5410 else if (II->isStr("weak")) 5411 lifetime = Qualifiers::OCL_Weak; 5412 else if (II->isStr("autoreleasing")) 5413 lifetime = Qualifiers::OCL_Autoreleasing; 5414 else { 5415 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 5416 << attr.getName() << II; 5417 attr.setInvalid(); 5418 return true; 5419 } 5420 5421 // Just ignore lifetime attributes other than __weak and __unsafe_unretained 5422 // outside of ARC mode. 5423 if (!S.getLangOpts().ObjCAutoRefCount && 5424 lifetime != Qualifiers::OCL_Weak && 5425 lifetime != Qualifiers::OCL_ExplicitNone) { 5426 return true; 5427 } 5428 5429 SplitQualType underlyingType = type.split(); 5430 5431 // Check for redundant/conflicting ownership qualifiers. 5432 if (Qualifiers::ObjCLifetime previousLifetime 5433 = type.getQualifiers().getObjCLifetime()) { 5434 // If it's written directly, that's an error. 5435 if (hasDirectOwnershipQualifier(type)) { 5436 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 5437 << type; 5438 return true; 5439 } 5440 5441 // Otherwise, if the qualifiers actually conflict, pull sugar off 5442 // and remove the ObjCLifetime qualifiers. 5443 if (previousLifetime != lifetime) { 5444 // It's possible to have multiple local ObjCLifetime qualifiers. We 5445 // can't stop after we reach a type that is directly qualified. 5446 const Type *prevTy = nullptr; 5447 while (!prevTy || prevTy != underlyingType.Ty) { 5448 prevTy = underlyingType.Ty; 5449 underlyingType = underlyingType.getSingleStepDesugaredType(); 5450 } 5451 underlyingType.Quals.removeObjCLifetime(); 5452 } 5453 } 5454 5455 underlyingType.Quals.addObjCLifetime(lifetime); 5456 5457 if (NonObjCPointer) { 5458 StringRef name = attr.getName()->getName(); 5459 switch (lifetime) { 5460 case Qualifiers::OCL_None: 5461 case Qualifiers::OCL_ExplicitNone: 5462 break; 5463 case Qualifiers::OCL_Strong: name = "__strong"; break; 5464 case Qualifiers::OCL_Weak: name = "__weak"; break; 5465 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 5466 } 5467 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name 5468 << TDS_ObjCObjOrBlock << type; 5469 } 5470 5471 // Don't actually add the __unsafe_unretained qualifier in non-ARC files, 5472 // because having both 'T' and '__unsafe_unretained T' exist in the type 5473 // system causes unfortunate widespread consistency problems. (For example, 5474 // they're not considered compatible types, and we mangle them identicially 5475 // as template arguments.) These problems are all individually fixable, 5476 // but it's easier to just not add the qualifier and instead sniff it out 5477 // in specific places using isObjCInertUnsafeUnretainedType(). 5478 // 5479 // Doing this does means we miss some trivial consistency checks that 5480 // would've triggered in ARC, but that's better than trying to solve all 5481 // the coexistence problems with __unsafe_unretained. 5482 if (!S.getLangOpts().ObjCAutoRefCount && 5483 lifetime == Qualifiers::OCL_ExplicitNone) { 5484 type = S.Context.getAttributedType( 5485 AttributedType::attr_objc_inert_unsafe_unretained, 5486 type, type); 5487 return true; 5488 } 5489 5490 QualType origType = type; 5491 if (!NonObjCPointer) 5492 type = S.Context.getQualifiedType(underlyingType); 5493 5494 // If we have a valid source location for the attribute, use an 5495 // AttributedType instead. 5496 if (AttrLoc.isValid()) 5497 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, 5498 origType, type); 5499 5500 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, 5501 unsigned diagnostic, QualType type) { 5502 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 5503 S.DelayedDiagnostics.add( 5504 sema::DelayedDiagnostic::makeForbiddenType( 5505 S.getSourceManager().getExpansionLoc(loc), 5506 diagnostic, type, /*ignored*/ 0)); 5507 } else { 5508 S.Diag(loc, diagnostic); 5509 } 5510 }; 5511 5512 // Sometimes, __weak isn't allowed. 5513 if (lifetime == Qualifiers::OCL_Weak && 5514 !S.getLangOpts().ObjCWeak && !NonObjCPointer) { 5515 5516 // Use a specialized diagnostic if the runtime just doesn't support them. 5517 unsigned diagnostic = 5518 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled 5519 : diag::err_arc_weak_no_runtime); 5520 5521 // In any case, delay the diagnostic until we know what we're parsing. 5522 diagnoseOrDelay(S, AttrLoc, diagnostic, type); 5523 5524 attr.setInvalid(); 5525 return true; 5526 } 5527 5528 // Forbid __weak for class objects marked as 5529 // objc_arc_weak_reference_unavailable 5530 if (lifetime == Qualifiers::OCL_Weak) { 5531 if (const ObjCObjectPointerType *ObjT = 5532 type->getAs<ObjCObjectPointerType>()) { 5533 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 5534 if (Class->isArcWeakrefUnavailable()) { 5535 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 5536 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 5537 diag::note_class_declared); 5538 } 5539 } 5540 } 5541 } 5542 5543 return true; 5544 } 5545 5546 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 5547 /// attribute on the specified type. Returns true to indicate that 5548 /// the attribute was handled, false to indicate that the type does 5549 /// not permit the attribute. 5550 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 5551 AttributeList &attr, 5552 QualType &type) { 5553 Sema &S = state.getSema(); 5554 5555 // Delay if this isn't some kind of pointer. 5556 if (!type->isPointerType() && 5557 !type->isObjCObjectPointerType() && 5558 !type->isBlockPointerType()) 5559 return false; 5560 5561 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 5562 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 5563 attr.setInvalid(); 5564 return true; 5565 } 5566 5567 // Check the attribute arguments. 5568 if (!attr.isArgIdent(0)) { 5569 S.Diag(attr.getLoc(), diag::err_attribute_argument_type) 5570 << attr.getName() << AANT_ArgumentString; 5571 attr.setInvalid(); 5572 return true; 5573 } 5574 Qualifiers::GC GCAttr; 5575 if (attr.getNumArgs() > 1) { 5576 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) 5577 << attr.getName() << 1; 5578 attr.setInvalid(); 5579 return true; 5580 } 5581 5582 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 5583 if (II->isStr("weak")) 5584 GCAttr = Qualifiers::Weak; 5585 else if (II->isStr("strong")) 5586 GCAttr = Qualifiers::Strong; 5587 else { 5588 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 5589 << attr.getName() << II; 5590 attr.setInvalid(); 5591 return true; 5592 } 5593 5594 QualType origType = type; 5595 type = S.Context.getObjCGCQualType(origType, GCAttr); 5596 5597 // Make an attributed type to preserve the source information. 5598 if (attr.getLoc().isValid()) 5599 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 5600 origType, type); 5601 5602 return true; 5603 } 5604 5605 namespace { 5606 /// A helper class to unwrap a type down to a function for the 5607 /// purposes of applying attributes there. 5608 /// 5609 /// Use: 5610 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 5611 /// if (unwrapped.isFunctionType()) { 5612 /// const FunctionType *fn = unwrapped.get(); 5613 /// // change fn somehow 5614 /// T = unwrapped.wrap(fn); 5615 /// } 5616 struct FunctionTypeUnwrapper { 5617 enum WrapKind { 5618 Desugar, 5619 Attributed, 5620 Parens, 5621 Pointer, 5622 BlockPointer, 5623 Reference, 5624 MemberPointer 5625 }; 5626 5627 QualType Original; 5628 const FunctionType *Fn; 5629 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 5630 5631 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 5632 while (true) { 5633 const Type *Ty = T.getTypePtr(); 5634 if (isa<FunctionType>(Ty)) { 5635 Fn = cast<FunctionType>(Ty); 5636 return; 5637 } else if (isa<ParenType>(Ty)) { 5638 T = cast<ParenType>(Ty)->getInnerType(); 5639 Stack.push_back(Parens); 5640 } else if (isa<PointerType>(Ty)) { 5641 T = cast<PointerType>(Ty)->getPointeeType(); 5642 Stack.push_back(Pointer); 5643 } else if (isa<BlockPointerType>(Ty)) { 5644 T = cast<BlockPointerType>(Ty)->getPointeeType(); 5645 Stack.push_back(BlockPointer); 5646 } else if (isa<MemberPointerType>(Ty)) { 5647 T = cast<MemberPointerType>(Ty)->getPointeeType(); 5648 Stack.push_back(MemberPointer); 5649 } else if (isa<ReferenceType>(Ty)) { 5650 T = cast<ReferenceType>(Ty)->getPointeeType(); 5651 Stack.push_back(Reference); 5652 } else if (isa<AttributedType>(Ty)) { 5653 T = cast<AttributedType>(Ty)->getEquivalentType(); 5654 Stack.push_back(Attributed); 5655 } else { 5656 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 5657 if (Ty == DTy) { 5658 Fn = nullptr; 5659 return; 5660 } 5661 5662 T = QualType(DTy, 0); 5663 Stack.push_back(Desugar); 5664 } 5665 } 5666 } 5667 5668 bool isFunctionType() const { return (Fn != nullptr); } 5669 const FunctionType *get() const { return Fn; } 5670 5671 QualType wrap(Sema &S, const FunctionType *New) { 5672 // If T wasn't modified from the unwrapped type, do nothing. 5673 if (New == get()) return Original; 5674 5675 Fn = New; 5676 return wrap(S.Context, Original, 0); 5677 } 5678 5679 private: 5680 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 5681 if (I == Stack.size()) 5682 return C.getQualifiedType(Fn, Old.getQualifiers()); 5683 5684 // Build up the inner type, applying the qualifiers from the old 5685 // type to the new type. 5686 SplitQualType SplitOld = Old.split(); 5687 5688 // As a special case, tail-recurse if there are no qualifiers. 5689 if (SplitOld.Quals.empty()) 5690 return wrap(C, SplitOld.Ty, I); 5691 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 5692 } 5693 5694 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 5695 if (I == Stack.size()) return QualType(Fn, 0); 5696 5697 switch (static_cast<WrapKind>(Stack[I++])) { 5698 case Desugar: 5699 // This is the point at which we potentially lose source 5700 // information. 5701 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 5702 5703 case Attributed: 5704 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); 5705 5706 case Parens: { 5707 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 5708 return C.getParenType(New); 5709 } 5710 5711 case Pointer: { 5712 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 5713 return C.getPointerType(New); 5714 } 5715 5716 case BlockPointer: { 5717 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 5718 return C.getBlockPointerType(New); 5719 } 5720 5721 case MemberPointer: { 5722 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 5723 QualType New = wrap(C, OldMPT->getPointeeType(), I); 5724 return C.getMemberPointerType(New, OldMPT->getClass()); 5725 } 5726 5727 case Reference: { 5728 const ReferenceType *OldRef = cast<ReferenceType>(Old); 5729 QualType New = wrap(C, OldRef->getPointeeType(), I); 5730 if (isa<LValueReferenceType>(OldRef)) 5731 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 5732 else 5733 return C.getRValueReferenceType(New); 5734 } 5735 } 5736 5737 llvm_unreachable("unknown wrapping kind"); 5738 } 5739 }; 5740 } // end anonymous namespace 5741 5742 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, 5743 AttributeList &Attr, 5744 QualType &Type) { 5745 Sema &S = State.getSema(); 5746 5747 AttributeList::Kind Kind = Attr.getKind(); 5748 QualType Desugared = Type; 5749 const AttributedType *AT = dyn_cast<AttributedType>(Type); 5750 while (AT) { 5751 AttributedType::Kind CurAttrKind = AT->getAttrKind(); 5752 5753 // You cannot specify duplicate type attributes, so if the attribute has 5754 // already been applied, flag it. 5755 if (getAttrListKind(CurAttrKind) == Kind) { 5756 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact) 5757 << Attr.getName(); 5758 return true; 5759 } 5760 5761 // You cannot have both __sptr and __uptr on the same type, nor can you 5762 // have __ptr32 and __ptr64. 5763 if ((CurAttrKind == AttributedType::attr_ptr32 && 5764 Kind == AttributeList::AT_Ptr64) || 5765 (CurAttrKind == AttributedType::attr_ptr64 && 5766 Kind == AttributeList::AT_Ptr32)) { 5767 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 5768 << "'__ptr32'" << "'__ptr64'"; 5769 return true; 5770 } else if ((CurAttrKind == AttributedType::attr_sptr && 5771 Kind == AttributeList::AT_UPtr) || 5772 (CurAttrKind == AttributedType::attr_uptr && 5773 Kind == AttributeList::AT_SPtr)) { 5774 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 5775 << "'__sptr'" << "'__uptr'"; 5776 return true; 5777 } 5778 5779 Desugared = AT->getEquivalentType(); 5780 AT = dyn_cast<AttributedType>(Desugared); 5781 } 5782 5783 // Pointer type qualifiers can only operate on pointer types, but not 5784 // pointer-to-member types. 5785 if (!isa<PointerType>(Desugared)) { 5786 if (Type->isMemberPointerType()) 5787 S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers) 5788 << Attr.getName(); 5789 else 5790 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only) 5791 << Attr.getName() << 0; 5792 return true; 5793 } 5794 5795 AttributedType::Kind TAK; 5796 switch (Kind) { 5797 default: llvm_unreachable("Unknown attribute kind"); 5798 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break; 5799 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break; 5800 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break; 5801 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break; 5802 } 5803 5804 Type = S.Context.getAttributedType(TAK, Type, Type); 5805 return false; 5806 } 5807 5808 bool Sema::checkNullabilityTypeSpecifier(QualType &type, 5809 NullabilityKind nullability, 5810 SourceLocation nullabilityLoc, 5811 bool isContextSensitive) { 5812 // We saw a nullability type specifier. If this is the first one for 5813 // this file, note that. 5814 FileID file = getNullabilityCompletenessCheckFileID(*this, nullabilityLoc); 5815 if (!file.isInvalid()) { 5816 FileNullability &fileNullability = NullabilityMap[file]; 5817 if (!fileNullability.SawTypeNullability) { 5818 // If we have already seen a pointer declarator without a nullability 5819 // annotation, complain about it. 5820 if (fileNullability.PointerLoc.isValid()) { 5821 Diag(fileNullability.PointerLoc, diag::warn_nullability_missing) 5822 << static_cast<unsigned>(fileNullability.PointerKind); 5823 } 5824 5825 fileNullability.SawTypeNullability = true; 5826 } 5827 } 5828 5829 // Check for existing nullability attributes on the type. 5830 QualType desugared = type; 5831 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { 5832 // Check whether there is already a null 5833 if (auto existingNullability = attributed->getImmediateNullability()) { 5834 // Duplicated nullability. 5835 if (nullability == *existingNullability) { 5836 Diag(nullabilityLoc, diag::warn_nullability_duplicate) 5837 << DiagNullabilityKind(nullability, isContextSensitive) 5838 << FixItHint::CreateRemoval(nullabilityLoc); 5839 5840 break; 5841 } 5842 5843 // Conflicting nullability. 5844 Diag(nullabilityLoc, diag::err_nullability_conflicting) 5845 << DiagNullabilityKind(nullability, isContextSensitive) 5846 << DiagNullabilityKind(*existingNullability, false); 5847 return true; 5848 } 5849 5850 desugared = attributed->getModifiedType(); 5851 } 5852 5853 // If there is already a different nullability specifier, complain. 5854 // This (unlike the code above) looks through typedefs that might 5855 // have nullability specifiers on them, which means we cannot 5856 // provide a useful Fix-It. 5857 if (auto existingNullability = desugared->getNullability(Context)) { 5858 if (nullability != *existingNullability) { 5859 Diag(nullabilityLoc, diag::err_nullability_conflicting) 5860 << DiagNullabilityKind(nullability, isContextSensitive) 5861 << DiagNullabilityKind(*existingNullability, false); 5862 5863 // Try to find the typedef with the existing nullability specifier. 5864 if (auto typedefType = desugared->getAs<TypedefType>()) { 5865 TypedefNameDecl *typedefDecl = typedefType->getDecl(); 5866 QualType underlyingType = typedefDecl->getUnderlyingType(); 5867 if (auto typedefNullability 5868 = AttributedType::stripOuterNullability(underlyingType)) { 5869 if (*typedefNullability == *existingNullability) { 5870 Diag(typedefDecl->getLocation(), diag::note_nullability_here) 5871 << DiagNullabilityKind(*existingNullability, false); 5872 } 5873 } 5874 } 5875 5876 return true; 5877 } 5878 } 5879 5880 // If this definitely isn't a pointer type, reject the specifier. 5881 if (!desugared->canHaveNullability()) { 5882 Diag(nullabilityLoc, diag::err_nullability_nonpointer) 5883 << DiagNullabilityKind(nullability, isContextSensitive) << type; 5884 return true; 5885 } 5886 5887 // For the context-sensitive keywords/Objective-C property 5888 // attributes, require that the type be a single-level pointer. 5889 if (isContextSensitive) { 5890 QualType pointeeType = desugared->getPointeeType(); 5891 if (pointeeType->isAnyPointerType() || 5892 pointeeType->isObjCObjectPointerType() || 5893 pointeeType->isMemberPointerType()) { 5894 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) 5895 << DiagNullabilityKind(nullability, true) 5896 << type; 5897 Diag(nullabilityLoc, diag::note_nullability_type_specifier) 5898 << DiagNullabilityKind(nullability, false) 5899 << type 5900 << FixItHint::CreateReplacement(nullabilityLoc, 5901 getNullabilitySpelling(nullability)); 5902 return true; 5903 } 5904 } 5905 5906 // Form the attributed type. 5907 type = Context.getAttributedType( 5908 AttributedType::getNullabilityAttrKind(nullability), type, type); 5909 return false; 5910 } 5911 5912 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) { 5913 if (isa<ObjCTypeParamType>(type)) { 5914 // Build the attributed type to record where __kindof occurred. 5915 type = Context.getAttributedType(AttributedType::attr_objc_kindof, 5916 type, type); 5917 return false; 5918 } 5919 5920 // Find out if it's an Objective-C object or object pointer type; 5921 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); 5922 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() 5923 : type->getAs<ObjCObjectType>(); 5924 5925 // If not, we can't apply __kindof. 5926 if (!objType) { 5927 // FIXME: Handle dependent types that aren't yet object types. 5928 Diag(loc, diag::err_objc_kindof_nonobject) 5929 << type; 5930 return true; 5931 } 5932 5933 // Rebuild the "equivalent" type, which pushes __kindof down into 5934 // the object type. 5935 // There is no need to apply kindof on an unqualified id type. 5936 QualType equivType = Context.getObjCObjectType( 5937 objType->getBaseType(), objType->getTypeArgsAsWritten(), 5938 objType->getProtocols(), 5939 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); 5940 5941 // If we started with an object pointer type, rebuild it. 5942 if (ptrType) { 5943 equivType = Context.getObjCObjectPointerType(equivType); 5944 if (auto nullability = type->getNullability(Context)) { 5945 auto attrKind = AttributedType::getNullabilityAttrKind(*nullability); 5946 equivType = Context.getAttributedType(attrKind, equivType, equivType); 5947 } 5948 } 5949 5950 // Build the attributed type to record where __kindof occurred. 5951 type = Context.getAttributedType(AttributedType::attr_objc_kindof, 5952 type, 5953 equivType); 5954 5955 return false; 5956 } 5957 5958 /// Map a nullability attribute kind to a nullability kind. 5959 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) { 5960 switch (kind) { 5961 case AttributeList::AT_TypeNonNull: 5962 return NullabilityKind::NonNull; 5963 5964 case AttributeList::AT_TypeNullable: 5965 return NullabilityKind::Nullable; 5966 5967 case AttributeList::AT_TypeNullUnspecified: 5968 return NullabilityKind::Unspecified; 5969 5970 default: 5971 llvm_unreachable("not a nullability attribute kind"); 5972 } 5973 } 5974 5975 /// Distribute a nullability type attribute that cannot be applied to 5976 /// the type specifier to a pointer, block pointer, or member pointer 5977 /// declarator, complaining if necessary. 5978 /// 5979 /// \returns true if the nullability annotation was distributed, false 5980 /// otherwise. 5981 static bool distributeNullabilityTypeAttr(TypeProcessingState &state, 5982 QualType type, 5983 AttributeList &attr) { 5984 Declarator &declarator = state.getDeclarator(); 5985 5986 /// Attempt to move the attribute to the specified chunk. 5987 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { 5988 // If there is already a nullability attribute there, don't add 5989 // one. 5990 if (hasNullabilityAttr(chunk.getAttrListRef())) 5991 return false; 5992 5993 // Complain about the nullability qualifier being in the wrong 5994 // place. 5995 enum { 5996 PK_Pointer, 5997 PK_BlockPointer, 5998 PK_MemberPointer, 5999 PK_FunctionPointer, 6000 PK_MemberFunctionPointer, 6001 } pointerKind 6002 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer 6003 : PK_Pointer) 6004 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer 6005 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; 6006 6007 auto diag = state.getSema().Diag(attr.getLoc(), 6008 diag::warn_nullability_declspec) 6009 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), 6010 attr.isContextSensitiveKeywordAttribute()) 6011 << type 6012 << static_cast<unsigned>(pointerKind); 6013 6014 // FIXME: MemberPointer chunks don't carry the location of the *. 6015 if (chunk.Kind != DeclaratorChunk::MemberPointer) { 6016 diag << FixItHint::CreateRemoval(attr.getLoc()) 6017 << FixItHint::CreateInsertion( 6018 state.getSema().getPreprocessor() 6019 .getLocForEndOfToken(chunk.Loc), 6020 " " + attr.getName()->getName().str() + " "); 6021 } 6022 6023 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 6024 chunk.getAttrListRef()); 6025 return true; 6026 }; 6027 6028 // Move it to the outermost pointer, member pointer, or block 6029 // pointer declarator. 6030 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 6031 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 6032 switch (chunk.Kind) { 6033 case DeclaratorChunk::Pointer: 6034 case DeclaratorChunk::BlockPointer: 6035 case DeclaratorChunk::MemberPointer: 6036 return moveToChunk(chunk, false); 6037 6038 case DeclaratorChunk::Paren: 6039 case DeclaratorChunk::Array: 6040 continue; 6041 6042 case DeclaratorChunk::Function: 6043 // Try to move past the return type to a function/block/member 6044 // function pointer. 6045 if (DeclaratorChunk *dest = maybeMovePastReturnType( 6046 declarator, i, 6047 /*onlyBlockPointers=*/false)) { 6048 return moveToChunk(*dest, true); 6049 } 6050 6051 return false; 6052 6053 // Don't walk through these. 6054 case DeclaratorChunk::Reference: 6055 case DeclaratorChunk::Pipe: 6056 return false; 6057 } 6058 } 6059 6060 return false; 6061 } 6062 6063 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) { 6064 assert(!Attr.isInvalid()); 6065 switch (Attr.getKind()) { 6066 default: 6067 llvm_unreachable("not a calling convention attribute"); 6068 case AttributeList::AT_CDecl: 6069 return AttributedType::attr_cdecl; 6070 case AttributeList::AT_FastCall: 6071 return AttributedType::attr_fastcall; 6072 case AttributeList::AT_StdCall: 6073 return AttributedType::attr_stdcall; 6074 case AttributeList::AT_ThisCall: 6075 return AttributedType::attr_thiscall; 6076 case AttributeList::AT_Pascal: 6077 return AttributedType::attr_pascal; 6078 case AttributeList::AT_SwiftCall: 6079 return AttributedType::attr_swiftcall; 6080 case AttributeList::AT_VectorCall: 6081 return AttributedType::attr_vectorcall; 6082 case AttributeList::AT_Pcs: { 6083 // The attribute may have had a fixit applied where we treated an 6084 // identifier as a string literal. The contents of the string are valid, 6085 // but the form may not be. 6086 StringRef Str; 6087 if (Attr.isArgExpr(0)) 6088 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); 6089 else 6090 Str = Attr.getArgAsIdent(0)->Ident->getName(); 6091 return llvm::StringSwitch<AttributedType::Kind>(Str) 6092 .Case("aapcs", AttributedType::attr_pcs) 6093 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp); 6094 } 6095 case AttributeList::AT_IntelOclBicc: 6096 return AttributedType::attr_inteloclbicc; 6097 case AttributeList::AT_MSABI: 6098 return AttributedType::attr_ms_abi; 6099 case AttributeList::AT_SysVABI: 6100 return AttributedType::attr_sysv_abi; 6101 case AttributeList::AT_PreserveMost: 6102 return AttributedType::attr_preserve_most; 6103 case AttributeList::AT_PreserveAll: 6104 return AttributedType::attr_preserve_all; 6105 } 6106 llvm_unreachable("unexpected attribute kind!"); 6107 } 6108 6109 /// Process an individual function attribute. Returns true to 6110 /// indicate that the attribute was handled, false if it wasn't. 6111 static bool handleFunctionTypeAttr(TypeProcessingState &state, 6112 AttributeList &attr, 6113 QualType &type) { 6114 Sema &S = state.getSema(); 6115 6116 FunctionTypeUnwrapper unwrapped(S, type); 6117 6118 if (attr.getKind() == AttributeList::AT_NoReturn) { 6119 if (S.CheckNoReturnAttr(attr)) 6120 return true; 6121 6122 // Delay if this is not a function type. 6123 if (!unwrapped.isFunctionType()) 6124 return false; 6125 6126 // Otherwise we can process right away. 6127 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 6128 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6129 return true; 6130 } 6131 6132 // ns_returns_retained is not always a type attribute, but if we got 6133 // here, we're treating it as one right now. 6134 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) { 6135 assert(S.getLangOpts().ObjCAutoRefCount && 6136 "ns_returns_retained treated as type attribute in non-ARC"); 6137 if (attr.getNumArgs()) return true; 6138 6139 // Delay if this is not a function type. 6140 if (!unwrapped.isFunctionType()) 6141 return false; 6142 6143 FunctionType::ExtInfo EI 6144 = unwrapped.get()->getExtInfo().withProducesResult(true); 6145 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6146 return true; 6147 } 6148 6149 if (attr.getKind() == AttributeList::AT_Regparm) { 6150 unsigned value; 6151 if (S.CheckRegparmAttr(attr, value)) 6152 return true; 6153 6154 // Delay if this is not a function type. 6155 if (!unwrapped.isFunctionType()) 6156 return false; 6157 6158 // Diagnose regparm with fastcall. 6159 const FunctionType *fn = unwrapped.get(); 6160 CallingConv CC = fn->getCallConv(); 6161 if (CC == CC_X86FastCall) { 6162 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6163 << FunctionType::getNameForCallConv(CC) 6164 << "regparm"; 6165 attr.setInvalid(); 6166 return true; 6167 } 6168 6169 FunctionType::ExtInfo EI = 6170 unwrapped.get()->getExtInfo().withRegParm(value); 6171 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6172 return true; 6173 } 6174 6175 // Delay if the type didn't work out to a function. 6176 if (!unwrapped.isFunctionType()) return false; 6177 6178 // Otherwise, a calling convention. 6179 CallingConv CC; 6180 if (S.CheckCallingConvAttr(attr, CC)) 6181 return true; 6182 6183 const FunctionType *fn = unwrapped.get(); 6184 CallingConv CCOld = fn->getCallConv(); 6185 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr); 6186 6187 if (CCOld != CC) { 6188 // Error out on when there's already an attribute on the type 6189 // and the CCs don't match. 6190 const AttributedType *AT = S.getCallingConvAttributedType(type); 6191 if (AT && AT->getAttrKind() != CCAttrKind) { 6192 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6193 << FunctionType::getNameForCallConv(CC) 6194 << FunctionType::getNameForCallConv(CCOld); 6195 attr.setInvalid(); 6196 return true; 6197 } 6198 } 6199 6200 // Diagnose use of variadic functions with calling conventions that 6201 // don't support them (e.g. because they're callee-cleanup). 6202 // We delay warning about this on unprototyped function declarations 6203 // until after redeclaration checking, just in case we pick up a 6204 // prototype that way. And apparently we also "delay" warning about 6205 // unprototyped function types in general, despite not necessarily having 6206 // much ability to diagnose it later. 6207 if (!supportsVariadicCall(CC)) { 6208 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); 6209 if (FnP && FnP->isVariadic()) { 6210 unsigned DiagID = diag::err_cconv_varargs; 6211 6212 // stdcall and fastcall are ignored with a warning for GCC and MS 6213 // compatibility. 6214 bool IsInvalid = true; 6215 if (CC == CC_X86StdCall || CC == CC_X86FastCall) { 6216 DiagID = diag::warn_cconv_varargs; 6217 IsInvalid = false; 6218 } 6219 6220 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC); 6221 if (IsInvalid) attr.setInvalid(); 6222 return true; 6223 } 6224 } 6225 6226 // Also diagnose fastcall with regparm. 6227 if (CC == CC_X86FastCall && fn->getHasRegParm()) { 6228 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 6229 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); 6230 attr.setInvalid(); 6231 return true; 6232 } 6233 6234 // Modify the CC from the wrapped function type, wrap it all back, and then 6235 // wrap the whole thing in an AttributedType as written. The modified type 6236 // might have a different CC if we ignored the attribute. 6237 QualType Equivalent; 6238 if (CCOld == CC) { 6239 Equivalent = type; 6240 } else { 6241 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 6242 Equivalent = 6243 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 6244 } 6245 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent); 6246 return true; 6247 } 6248 6249 bool Sema::hasExplicitCallingConv(QualType &T) { 6250 QualType R = T.IgnoreParens(); 6251 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) { 6252 if (AT->isCallingConv()) 6253 return true; 6254 R = AT->getModifiedType().IgnoreParens(); 6255 } 6256 return false; 6257 } 6258 6259 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, 6260 SourceLocation Loc) { 6261 FunctionTypeUnwrapper Unwrapped(*this, T); 6262 const FunctionType *FT = Unwrapped.get(); 6263 bool IsVariadic = (isa<FunctionProtoType>(FT) && 6264 cast<FunctionProtoType>(FT)->isVariadic()); 6265 CallingConv CurCC = FT->getCallConv(); 6266 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); 6267 6268 if (CurCC == ToCC) 6269 return; 6270 6271 // MS compiler ignores explicit calling convention attributes on structors. We 6272 // should do the same. 6273 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { 6274 // Issue a warning on ignored calling convention -- except of __stdcall. 6275 // Again, this is what MS compiler does. 6276 if (CurCC != CC_X86StdCall) 6277 Diag(Loc, diag::warn_cconv_structors) 6278 << FunctionType::getNameForCallConv(CurCC); 6279 // Default adjustment. 6280 } else { 6281 // Only adjust types with the default convention. For example, on Windows 6282 // we should adjust a __cdecl type to __thiscall for instance methods, and a 6283 // __thiscall type to __cdecl for static methods. 6284 CallingConv DefaultCC = 6285 Context.getDefaultCallingConvention(IsVariadic, IsStatic); 6286 6287 if (CurCC != DefaultCC || DefaultCC == ToCC) 6288 return; 6289 6290 if (hasExplicitCallingConv(T)) 6291 return; 6292 } 6293 6294 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); 6295 QualType Wrapped = Unwrapped.wrap(*this, FT); 6296 T = Context.getAdjustedType(T, Wrapped); 6297 } 6298 6299 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 6300 /// and float scalars, although arrays, pointers, and function return values are 6301 /// allowed in conjunction with this construct. Aggregates with this attribute 6302 /// are invalid, even if they are of the same size as a corresponding scalar. 6303 /// The raw attribute should contain precisely 1 argument, the vector size for 6304 /// the variable, measured in bytes. If curType and rawAttr are well formed, 6305 /// this routine will return a new vector type. 6306 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 6307 Sema &S) { 6308 // Check the attribute arguments. 6309 if (Attr.getNumArgs() != 1) { 6310 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6311 << Attr.getName() << 1; 6312 Attr.setInvalid(); 6313 return; 6314 } 6315 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 6316 llvm::APSInt vecSize(32); 6317 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 6318 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 6319 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 6320 << Attr.getName() << AANT_ArgumentIntegerConstant 6321 << sizeExpr->getSourceRange(); 6322 Attr.setInvalid(); 6323 return; 6324 } 6325 // The base type must be integer (not Boolean or enumeration) or float, and 6326 // can't already be a vector. 6327 if (!CurType->isBuiltinType() || CurType->isBooleanType() || 6328 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) { 6329 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 6330 Attr.setInvalid(); 6331 return; 6332 } 6333 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 6334 // vecSize is specified in bytes - convert to bits. 6335 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 6336 6337 // the vector size needs to be an integral multiple of the type size. 6338 if (vectorSize % typeSize) { 6339 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 6340 << sizeExpr->getSourceRange(); 6341 Attr.setInvalid(); 6342 return; 6343 } 6344 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) { 6345 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large) 6346 << sizeExpr->getSourceRange(); 6347 Attr.setInvalid(); 6348 return; 6349 } 6350 if (vectorSize == 0) { 6351 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 6352 << sizeExpr->getSourceRange(); 6353 Attr.setInvalid(); 6354 return; 6355 } 6356 6357 // Success! Instantiate the vector type, the number of elements is > 0, and 6358 // not required to be a power of 2, unlike GCC. 6359 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 6360 VectorType::GenericVector); 6361 } 6362 6363 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on 6364 /// a type. 6365 static void HandleExtVectorTypeAttr(QualType &CurType, 6366 const AttributeList &Attr, 6367 Sema &S) { 6368 // check the attribute arguments. 6369 if (Attr.getNumArgs() != 1) { 6370 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6371 << Attr.getName() << 1; 6372 return; 6373 } 6374 6375 Expr *sizeExpr; 6376 6377 // Special case where the argument is a template id. 6378 if (Attr.isArgIdent(0)) { 6379 CXXScopeSpec SS; 6380 SourceLocation TemplateKWLoc; 6381 UnqualifiedId id; 6382 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); 6383 6384 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 6385 id, false, false); 6386 if (Size.isInvalid()) 6387 return; 6388 6389 sizeExpr = Size.get(); 6390 } else { 6391 sizeExpr = Attr.getArgAsExpr(0); 6392 } 6393 6394 // Create the vector type. 6395 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 6396 if (!T.isNull()) 6397 CurType = T; 6398 } 6399 6400 static bool isPermittedNeonBaseType(QualType &Ty, 6401 VectorType::VectorKind VecKind, Sema &S) { 6402 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 6403 if (!BTy) 6404 return false; 6405 6406 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 6407 6408 // Signed poly is mathematically wrong, but has been baked into some ABIs by 6409 // now. 6410 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || 6411 Triple.getArch() == llvm::Triple::aarch64_be; 6412 if (VecKind == VectorType::NeonPolyVector) { 6413 if (IsPolyUnsigned) { 6414 // AArch64 polynomial vectors are unsigned and support poly64. 6415 return BTy->getKind() == BuiltinType::UChar || 6416 BTy->getKind() == BuiltinType::UShort || 6417 BTy->getKind() == BuiltinType::ULong || 6418 BTy->getKind() == BuiltinType::ULongLong; 6419 } else { 6420 // AArch32 polynomial vector are signed. 6421 return BTy->getKind() == BuiltinType::SChar || 6422 BTy->getKind() == BuiltinType::Short; 6423 } 6424 } 6425 6426 // Non-polynomial vector types: the usual suspects are allowed, as well as 6427 // float64_t on AArch64. 6428 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 || 6429 Triple.getArch() == llvm::Triple::aarch64_be; 6430 6431 if (Is64Bit && BTy->getKind() == BuiltinType::Double) 6432 return true; 6433 6434 return BTy->getKind() == BuiltinType::SChar || 6435 BTy->getKind() == BuiltinType::UChar || 6436 BTy->getKind() == BuiltinType::Short || 6437 BTy->getKind() == BuiltinType::UShort || 6438 BTy->getKind() == BuiltinType::Int || 6439 BTy->getKind() == BuiltinType::UInt || 6440 BTy->getKind() == BuiltinType::Long || 6441 BTy->getKind() == BuiltinType::ULong || 6442 BTy->getKind() == BuiltinType::LongLong || 6443 BTy->getKind() == BuiltinType::ULongLong || 6444 BTy->getKind() == BuiltinType::Float || 6445 BTy->getKind() == BuiltinType::Half; 6446 } 6447 6448 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 6449 /// "neon_polyvector_type" attributes are used to create vector types that 6450 /// are mangled according to ARM's ABI. Otherwise, these types are identical 6451 /// to those created with the "vector_size" attribute. Unlike "vector_size" 6452 /// the argument to these Neon attributes is the number of vector elements, 6453 /// not the vector size in bytes. The vector width and element type must 6454 /// match one of the standard Neon vector types. 6455 static void HandleNeonVectorTypeAttr(QualType& CurType, 6456 const AttributeList &Attr, Sema &S, 6457 VectorType::VectorKind VecKind) { 6458 // Target must have NEON 6459 if (!S.Context.getTargetInfo().hasFeature("neon")) { 6460 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName(); 6461 Attr.setInvalid(); 6462 return; 6463 } 6464 // Check the attribute arguments. 6465 if (Attr.getNumArgs() != 1) { 6466 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6467 << Attr.getName() << 1; 6468 Attr.setInvalid(); 6469 return; 6470 } 6471 // The number of elements must be an ICE. 6472 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 6473 llvm::APSInt numEltsInt(32); 6474 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 6475 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 6476 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 6477 << Attr.getName() << AANT_ArgumentIntegerConstant 6478 << numEltsExpr->getSourceRange(); 6479 Attr.setInvalid(); 6480 return; 6481 } 6482 // Only certain element types are supported for Neon vectors. 6483 if (!isPermittedNeonBaseType(CurType, VecKind, S)) { 6484 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 6485 Attr.setInvalid(); 6486 return; 6487 } 6488 6489 // The total size of the vector must be 64 or 128 bits. 6490 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 6491 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 6492 unsigned vecSize = typeSize * numElts; 6493 if (vecSize != 64 && vecSize != 128) { 6494 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 6495 Attr.setInvalid(); 6496 return; 6497 } 6498 6499 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 6500 } 6501 6502 /// Handle OpenCL Access Qualifier Attribute. 6503 static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr, 6504 Sema &S) { 6505 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. 6506 if (!(CurType->isImageType() || CurType->isPipeType())) { 6507 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); 6508 Attr.setInvalid(); 6509 return; 6510 } 6511 6512 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { 6513 QualType PointeeTy = TypedefTy->desugar(); 6514 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); 6515 6516 std::string PrevAccessQual; 6517 switch (cast<BuiltinType>(PointeeTy.getTypePtr())->getKind()) { 6518 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6519 case BuiltinType::Id: \ 6520 PrevAccessQual = #Access; \ 6521 break; 6522 #include "clang/Basic/OpenCLImageTypes.def" 6523 default: 6524 assert(0 && "Unable to find corresponding image type."); 6525 } 6526 6527 S.Diag(TypedefTy->getDecl()->getLocStart(), 6528 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; 6529 } 6530 } 6531 6532 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 6533 TypeAttrLocation TAL, AttributeList *attrs) { 6534 // Scan through and apply attributes to this type where it makes sense. Some 6535 // attributes (such as __address_space__, __vector_size__, etc) apply to the 6536 // type, but others can be present in the type specifiers even though they 6537 // apply to the decl. Here we apply type attributes and ignore the rest. 6538 6539 bool hasOpenCLAddressSpace = false; 6540 while (attrs) { 6541 AttributeList &attr = *attrs; 6542 attrs = attr.getNext(); // reset to the next here due to early loop continue 6543 // stmts 6544 6545 // Skip attributes that were marked to be invalid. 6546 if (attr.isInvalid()) 6547 continue; 6548 6549 if (attr.isCXX11Attribute()) { 6550 // [[gnu::...]] attributes are treated as declaration attributes, so may 6551 // not appertain to a DeclaratorChunk, even if we handle them as type 6552 // attributes. 6553 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) { 6554 if (TAL == TAL_DeclChunk) { 6555 state.getSema().Diag(attr.getLoc(), 6556 diag::warn_cxx11_gnu_attribute_on_type) 6557 << attr.getName(); 6558 continue; 6559 } 6560 } else if (TAL != TAL_DeclChunk) { 6561 // Otherwise, only consider type processing for a C++11 attribute if 6562 // it's actually been applied to a type. 6563 continue; 6564 } 6565 } 6566 6567 // If this is an attribute we can handle, do so now, 6568 // otherwise, add it to the FnAttrs list for rechaining. 6569 switch (attr.getKind()) { 6570 default: 6571 // A C++11 attribute on a declarator chunk must appertain to a type. 6572 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { 6573 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 6574 << attr.getName(); 6575 attr.setUsedAsTypeAttr(); 6576 } 6577 break; 6578 6579 case AttributeList::UnknownAttribute: 6580 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) 6581 state.getSema().Diag(attr.getLoc(), 6582 diag::warn_unknown_attribute_ignored) 6583 << attr.getName(); 6584 break; 6585 6586 case AttributeList::IgnoredAttribute: 6587 break; 6588 6589 case AttributeList::AT_MayAlias: 6590 // FIXME: This attribute needs to actually be handled, but if we ignore 6591 // it it breaks large amounts of Linux software. 6592 attr.setUsedAsTypeAttr(); 6593 break; 6594 case AttributeList::AT_OpenCLPrivateAddressSpace: 6595 case AttributeList::AT_OpenCLGlobalAddressSpace: 6596 case AttributeList::AT_OpenCLLocalAddressSpace: 6597 case AttributeList::AT_OpenCLConstantAddressSpace: 6598 case AttributeList::AT_OpenCLGenericAddressSpace: 6599 case AttributeList::AT_AddressSpace: 6600 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 6601 attr.setUsedAsTypeAttr(); 6602 hasOpenCLAddressSpace = true; 6603 break; 6604 OBJC_POINTER_TYPE_ATTRS_CASELIST: 6605 if (!handleObjCPointerTypeAttr(state, attr, type)) 6606 distributeObjCPointerTypeAttr(state, attr, type); 6607 attr.setUsedAsTypeAttr(); 6608 break; 6609 case AttributeList::AT_VectorSize: 6610 HandleVectorSizeAttr(type, attr, state.getSema()); 6611 attr.setUsedAsTypeAttr(); 6612 break; 6613 case AttributeList::AT_ExtVectorType: 6614 HandleExtVectorTypeAttr(type, attr, state.getSema()); 6615 attr.setUsedAsTypeAttr(); 6616 break; 6617 case AttributeList::AT_NeonVectorType: 6618 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 6619 VectorType::NeonVector); 6620 attr.setUsedAsTypeAttr(); 6621 break; 6622 case AttributeList::AT_NeonPolyVectorType: 6623 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 6624 VectorType::NeonPolyVector); 6625 attr.setUsedAsTypeAttr(); 6626 break; 6627 case AttributeList::AT_OpenCLAccess: 6628 HandleOpenCLAccessAttr(type, attr, state.getSema()); 6629 attr.setUsedAsTypeAttr(); 6630 break; 6631 6632 MS_TYPE_ATTRS_CASELIST: 6633 if (!handleMSPointerTypeQualifierAttr(state, attr, type)) 6634 attr.setUsedAsTypeAttr(); 6635 break; 6636 6637 6638 NULLABILITY_TYPE_ATTRS_CASELIST: 6639 // Either add nullability here or try to distribute it. We 6640 // don't want to distribute the nullability specifier past any 6641 // dependent type, because that complicates the user model. 6642 if (type->canHaveNullability() || type->isDependentType() || 6643 !distributeNullabilityTypeAttr(state, type, attr)) { 6644 if (state.getSema().checkNullabilityTypeSpecifier( 6645 type, 6646 mapNullabilityAttrKind(attr.getKind()), 6647 attr.getLoc(), 6648 attr.isContextSensitiveKeywordAttribute())) { 6649 attr.setInvalid(); 6650 } 6651 6652 attr.setUsedAsTypeAttr(); 6653 } 6654 break; 6655 6656 case AttributeList::AT_ObjCKindOf: 6657 // '__kindof' must be part of the decl-specifiers. 6658 switch (TAL) { 6659 case TAL_DeclSpec: 6660 break; 6661 6662 case TAL_DeclChunk: 6663 case TAL_DeclName: 6664 state.getSema().Diag(attr.getLoc(), 6665 diag::err_objc_kindof_wrong_position) 6666 << FixItHint::CreateRemoval(attr.getLoc()) 6667 << FixItHint::CreateInsertion( 6668 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof "); 6669 break; 6670 } 6671 6672 // Apply it regardless. 6673 if (state.getSema().checkObjCKindOfType(type, attr.getLoc())) 6674 attr.setInvalid(); 6675 attr.setUsedAsTypeAttr(); 6676 break; 6677 6678 case AttributeList::AT_NSReturnsRetained: 6679 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 6680 break; 6681 // fallthrough into the function attrs 6682 6683 FUNCTION_TYPE_ATTRS_CASELIST: 6684 attr.setUsedAsTypeAttr(); 6685 6686 // Never process function type attributes as part of the 6687 // declaration-specifiers. 6688 if (TAL == TAL_DeclSpec) 6689 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 6690 6691 // Otherwise, handle the possible delays. 6692 else if (!handleFunctionTypeAttr(state, attr, type)) 6693 distributeFunctionTypeAttr(state, attr, type); 6694 break; 6695 } 6696 } 6697 6698 // If address space is not set, OpenCL 2.0 defines non private default 6699 // address spaces for some cases: 6700 // OpenCL 2.0, section 6.5: 6701 // The address space for a variable at program scope or a static variable 6702 // inside a function can either be __global or __constant, but defaults to 6703 // __global if not specified. 6704 // (...) 6705 // Pointers that are declared without pointing to a named address space point 6706 // to the generic address space. 6707 if (state.getSema().getLangOpts().OpenCLVersion >= 200 && 6708 !hasOpenCLAddressSpace && type.getAddressSpace() == 0 && 6709 (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) { 6710 Declarator &D = state.getDeclarator(); 6711 if (state.getCurrentChunkIndex() > 0 && 6712 D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind == 6713 DeclaratorChunk::Pointer) { 6714 type = state.getSema().Context.getAddrSpaceQualType( 6715 type, LangAS::opencl_generic); 6716 } else if (state.getCurrentChunkIndex() == 0 && 6717 D.getContext() == Declarator::FileContext && 6718 !D.isFunctionDeclarator() && !D.isFunctionDefinition() && 6719 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6720 !type->isSamplerT()) 6721 type = state.getSema().Context.getAddrSpaceQualType( 6722 type, LangAS::opencl_global); 6723 else if (state.getCurrentChunkIndex() == 0 && 6724 D.getContext() == Declarator::BlockContext && 6725 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) 6726 type = state.getSema().Context.getAddrSpaceQualType( 6727 type, LangAS::opencl_global); 6728 } 6729 } 6730 6731 void Sema::completeExprArrayBound(Expr *E) { 6732 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 6733 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 6734 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { 6735 SourceLocation PointOfInstantiation = E->getExprLoc(); 6736 6737 if (MemberSpecializationInfo *MSInfo = 6738 Var->getMemberSpecializationInfo()) { 6739 // If we don't already have a point of instantiation, this is it. 6740 if (MSInfo->getPointOfInstantiation().isInvalid()) { 6741 MSInfo->setPointOfInstantiation(PointOfInstantiation); 6742 6743 // This is a modification of an existing AST node. Notify 6744 // listeners. 6745 if (ASTMutationListener *L = getASTMutationListener()) 6746 L->StaticDataMemberInstantiated(Var); 6747 } 6748 } else { 6749 VarTemplateSpecializationDecl *VarSpec = 6750 cast<VarTemplateSpecializationDecl>(Var); 6751 if (VarSpec->getPointOfInstantiation().isInvalid()) 6752 VarSpec->setPointOfInstantiation(PointOfInstantiation); 6753 } 6754 6755 InstantiateVariableDefinition(PointOfInstantiation, Var); 6756 6757 // Update the type to the newly instantiated definition's type both 6758 // here and within the expression. 6759 if (VarDecl *Def = Var->getDefinition()) { 6760 DRE->setDecl(Def); 6761 QualType T = Def->getType(); 6762 DRE->setType(T); 6763 // FIXME: Update the type on all intervening expressions. 6764 E->setType(T); 6765 } 6766 6767 // We still go on to try to complete the type independently, as it 6768 // may also require instantiations or diagnostics if it remains 6769 // incomplete. 6770 } 6771 } 6772 } 6773 } 6774 6775 /// \brief Ensure that the type of the given expression is complete. 6776 /// 6777 /// This routine checks whether the expression \p E has a complete type. If the 6778 /// expression refers to an instantiable construct, that instantiation is 6779 /// performed as needed to complete its type. Furthermore 6780 /// Sema::RequireCompleteType is called for the expression's type (or in the 6781 /// case of a reference type, the referred-to type). 6782 /// 6783 /// \param E The expression whose type is required to be complete. 6784 /// \param Diagnoser The object that will emit a diagnostic if the type is 6785 /// incomplete. 6786 /// 6787 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 6788 /// otherwise. 6789 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) { 6790 QualType T = E->getType(); 6791 6792 // Incomplete array types may be completed by the initializer attached to 6793 // their definitions. For static data members of class templates and for 6794 // variable templates, we need to instantiate the definition to get this 6795 // initializer and complete the type. 6796 if (T->isIncompleteArrayType()) { 6797 completeExprArrayBound(E); 6798 T = E->getType(); 6799 } 6800 6801 // FIXME: Are there other cases which require instantiating something other 6802 // than the type to complete the type of an expression? 6803 6804 return RequireCompleteType(E->getExprLoc(), T, Diagnoser); 6805 } 6806 6807 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 6808 BoundTypeDiagnoser<> Diagnoser(DiagID); 6809 return RequireCompleteExprType(E, Diagnoser); 6810 } 6811 6812 /// @brief Ensure that the type T is a complete type. 6813 /// 6814 /// This routine checks whether the type @p T is complete in any 6815 /// context where a complete type is required. If @p T is a complete 6816 /// type, returns false. If @p T is a class template specialization, 6817 /// this routine then attempts to perform class template 6818 /// instantiation. If instantiation fails, or if @p T is incomplete 6819 /// and cannot be completed, issues the diagnostic @p diag (giving it 6820 /// the type @p T) and returns true. 6821 /// 6822 /// @param Loc The location in the source that the incomplete type 6823 /// diagnostic should refer to. 6824 /// 6825 /// @param T The type that this routine is examining for completeness. 6826 /// 6827 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 6828 /// @c false otherwise. 6829 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 6830 TypeDiagnoser &Diagnoser) { 6831 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser)) 6832 return true; 6833 if (const TagType *Tag = T->getAs<TagType>()) { 6834 if (!Tag->getDecl()->isCompleteDefinitionRequired()) { 6835 Tag->getDecl()->setCompleteDefinitionRequired(); 6836 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); 6837 } 6838 } 6839 return false; 6840 } 6841 6842 /// \brief Determine whether there is any declaration of \p D that was ever a 6843 /// definition (perhaps before module merging) and is currently visible. 6844 /// \param D The definition of the entity. 6845 /// \param Suggested Filled in with the declaration that should be made visible 6846 /// in order to provide a definition of this entity. 6847 /// \param OnlyNeedComplete If \c true, we only need the type to be complete, 6848 /// not defined. This only matters for enums with a fixed underlying 6849 /// type, since in all other cases, a type is complete if and only if it 6850 /// is defined. 6851 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 6852 bool OnlyNeedComplete) { 6853 // Easy case: if we don't have modules, all declarations are visible. 6854 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) 6855 return true; 6856 6857 // If this definition was instantiated from a template, map back to the 6858 // pattern from which it was instantiated. 6859 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { 6860 // We're in the middle of defining it; this definition should be treated 6861 // as visible. 6862 return true; 6863 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 6864 if (auto *Pattern = RD->getTemplateInstantiationPattern()) 6865 RD = Pattern; 6866 D = RD->getDefinition(); 6867 } else if (auto *ED = dyn_cast<EnumDecl>(D)) { 6868 if (auto *Pattern = ED->getTemplateInstantiationPattern()) 6869 ED = Pattern; 6870 if (OnlyNeedComplete && ED->isFixed()) { 6871 // If the enum has a fixed underlying type, and we're only looking for a 6872 // complete type (not a definition), any visible declaration of it will 6873 // do. 6874 *Suggested = nullptr; 6875 for (auto *Redecl : ED->redecls()) { 6876 if (isVisible(Redecl)) 6877 return true; 6878 if (Redecl->isThisDeclarationADefinition() || 6879 (Redecl->isCanonicalDecl() && !*Suggested)) 6880 *Suggested = Redecl; 6881 } 6882 return false; 6883 } 6884 D = ED->getDefinition(); 6885 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { 6886 if (auto *Pattern = FD->getTemplateInstantiationPattern()) 6887 FD = Pattern; 6888 D = FD->getDefinition(); 6889 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 6890 if (auto *Pattern = VD->getTemplateInstantiationPattern()) 6891 VD = Pattern; 6892 D = VD->getDefinition(); 6893 } 6894 assert(D && "missing definition for pattern of instantiated definition"); 6895 6896 *Suggested = D; 6897 if (isVisible(D)) 6898 return true; 6899 6900 // The external source may have additional definitions of this entity that are 6901 // visible, so complete the redeclaration chain now and ask again. 6902 if (auto *Source = Context.getExternalSource()) { 6903 Source->CompleteRedeclChain(D); 6904 return isVisible(D); 6905 } 6906 6907 return false; 6908 } 6909 6910 /// Locks in the inheritance model for the given class and all of its bases. 6911 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { 6912 RD = RD->getMostRecentDecl(); 6913 if (!RD->hasAttr<MSInheritanceAttr>()) { 6914 MSInheritanceAttr::Spelling IM; 6915 6916 switch (S.MSPointerToMemberRepresentationMethod) { 6917 case LangOptions::PPTMK_BestCase: 6918 IM = RD->calculateInheritanceModel(); 6919 break; 6920 case LangOptions::PPTMK_FullGeneralitySingleInheritance: 6921 IM = MSInheritanceAttr::Keyword_single_inheritance; 6922 break; 6923 case LangOptions::PPTMK_FullGeneralityMultipleInheritance: 6924 IM = MSInheritanceAttr::Keyword_multiple_inheritance; 6925 break; 6926 case LangOptions::PPTMK_FullGeneralityVirtualInheritance: 6927 IM = MSInheritanceAttr::Keyword_unspecified_inheritance; 6928 break; 6929 } 6930 6931 RD->addAttr(MSInheritanceAttr::CreateImplicit( 6932 S.getASTContext(), IM, 6933 /*BestCase=*/S.MSPointerToMemberRepresentationMethod == 6934 LangOptions::PPTMK_BestCase, 6935 S.ImplicitMSInheritanceAttrLoc.isValid() 6936 ? S.ImplicitMSInheritanceAttrLoc 6937 : RD->getSourceRange())); 6938 S.Consumer.AssignInheritanceModel(RD); 6939 } 6940 } 6941 6942 /// \brief The implementation of RequireCompleteType 6943 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 6944 TypeDiagnoser *Diagnoser) { 6945 // FIXME: Add this assertion to make sure we always get instantiation points. 6946 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 6947 // FIXME: Add this assertion to help us flush out problems with 6948 // checking for dependent types and type-dependent expressions. 6949 // 6950 // assert(!T->isDependentType() && 6951 // "Can't ask whether a dependent type is complete"); 6952 6953 // We lock in the inheritance model once somebody has asked us to ensure 6954 // that a pointer-to-member type is complete. 6955 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 6956 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { 6957 if (!MPTy->getClass()->isDependentType()) { 6958 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); 6959 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); 6960 } 6961 } 6962 } 6963 6964 NamedDecl *Def = nullptr; 6965 bool Incomplete = T->isIncompleteType(&Def); 6966 6967 // Check that any necessary explicit specializations are visible. For an 6968 // enum, we just need the declaration, so don't check this. 6969 if (Def && !isa<EnumDecl>(Def)) 6970 checkSpecializationVisibility(Loc, Def); 6971 6972 // If we have a complete type, we're done. 6973 if (!Incomplete) { 6974 // If we know about the definition but it is not visible, complain. 6975 NamedDecl *SuggestedDef = nullptr; 6976 if (Def && 6977 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { 6978 // If the user is going to see an error here, recover by making the 6979 // definition visible. 6980 bool TreatAsComplete = Diagnoser && !isSFINAEContext(); 6981 if (Diagnoser) 6982 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition, 6983 /*Recover*/TreatAsComplete); 6984 return !TreatAsComplete; 6985 } 6986 6987 return false; 6988 } 6989 6990 const TagType *Tag = T->getAs<TagType>(); 6991 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>(); 6992 6993 // If there's an unimported definition of this type in a module (for 6994 // instance, because we forward declared it, then imported the definition), 6995 // import that definition now. 6996 // 6997 // FIXME: What about other cases where an import extends a redeclaration 6998 // chain for a declaration that can be accessed through a mechanism other 6999 // than name lookup (eg, referenced in a template, or a variable whose type 7000 // could be completed by the module)? 7001 // 7002 // FIXME: Should we map through to the base array element type before 7003 // checking for a tag type? 7004 if (Tag || IFace) { 7005 NamedDecl *D = 7006 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl(); 7007 7008 // Avoid diagnosing invalid decls as incomplete. 7009 if (D->isInvalidDecl()) 7010 return true; 7011 7012 // Give the external AST source a chance to complete the type. 7013 if (auto *Source = Context.getExternalSource()) { 7014 if (Tag) 7015 Source->CompleteType(Tag->getDecl()); 7016 else 7017 Source->CompleteType(IFace->getDecl()); 7018 7019 // If the external source completed the type, go through the motions 7020 // again to ensure we're allowed to use the completed type. 7021 if (!T->isIncompleteType()) 7022 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 7023 } 7024 } 7025 7026 // If we have a class template specialization or a class member of a 7027 // class template specialization, or an array with known size of such, 7028 // try to instantiate it. 7029 QualType MaybeTemplate = T; 7030 while (const ConstantArrayType *Array 7031 = Context.getAsConstantArrayType(MaybeTemplate)) 7032 MaybeTemplate = Array->getElementType(); 7033 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 7034 bool Instantiated = false; 7035 bool Diagnosed = false; 7036 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 7037 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 7038 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 7039 Diagnosed = InstantiateClassTemplateSpecialization( 7040 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, 7041 /*Complain=*/Diagnoser); 7042 Instantiated = true; 7043 } 7044 } else if (CXXRecordDecl *Rec 7045 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 7046 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass(); 7047 if (!Rec->isBeingDefined() && Pattern) { 7048 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo(); 7049 assert(MSI && "Missing member specialization information?"); 7050 // This record was instantiated from a class within a template. 7051 if (MSI->getTemplateSpecializationKind() != 7052 TSK_ExplicitSpecialization) { 7053 Diagnosed = InstantiateClass(Loc, Rec, Pattern, 7054 getTemplateInstantiationArgs(Rec), 7055 TSK_ImplicitInstantiation, 7056 /*Complain=*/Diagnoser); 7057 Instantiated = true; 7058 } 7059 } 7060 } 7061 7062 if (Instantiated) { 7063 // Instantiate* might have already complained that the template is not 7064 // defined, if we asked it to. 7065 if (Diagnoser && Diagnosed) 7066 return true; 7067 // If we instantiated a definition, check that it's usable, even if 7068 // instantiation produced an error, so that repeated calls to this 7069 // function give consistent answers. 7070 if (!T->isIncompleteType()) 7071 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 7072 } 7073 } 7074 7075 // FIXME: If we didn't instantiate a definition because of an explicit 7076 // specialization declaration, check that it's visible. 7077 7078 if (!Diagnoser) 7079 return true; 7080 7081 Diagnoser->diagnose(*this, Loc, T); 7082 7083 // If the type was a forward declaration of a class/struct/union 7084 // type, produce a note. 7085 if (Tag && !Tag->getDecl()->isInvalidDecl()) 7086 Diag(Tag->getDecl()->getLocation(), 7087 Tag->isBeingDefined() ? diag::note_type_being_defined 7088 : diag::note_forward_declaration) 7089 << QualType(Tag, 0); 7090 7091 // If the Objective-C class was a forward declaration, produce a note. 7092 if (IFace && !IFace->getDecl()->isInvalidDecl()) 7093 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class); 7094 7095 // If we have external information that we can use to suggest a fix, 7096 // produce a note. 7097 if (ExternalSource) 7098 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); 7099 7100 return true; 7101 } 7102 7103 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 7104 unsigned DiagID) { 7105 BoundTypeDiagnoser<> Diagnoser(DiagID); 7106 return RequireCompleteType(Loc, T, Diagnoser); 7107 } 7108 7109 /// \brief Get diagnostic %select index for tag kind for 7110 /// literal type diagnostic message. 7111 /// WARNING: Indexes apply to particular diagnostics only! 7112 /// 7113 /// \returns diagnostic %select index. 7114 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 7115 switch (Tag) { 7116 case TTK_Struct: return 0; 7117 case TTK_Interface: return 1; 7118 case TTK_Class: return 2; 7119 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 7120 } 7121 } 7122 7123 /// @brief Ensure that the type T is a literal type. 7124 /// 7125 /// This routine checks whether the type @p T is a literal type. If @p T is an 7126 /// incomplete type, an attempt is made to complete it. If @p T is a literal 7127 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 7128 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 7129 /// it the type @p T), along with notes explaining why the type is not a 7130 /// literal type, and returns true. 7131 /// 7132 /// @param Loc The location in the source that the non-literal type 7133 /// diagnostic should refer to. 7134 /// 7135 /// @param T The type that this routine is examining for literalness. 7136 /// 7137 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 7138 /// 7139 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 7140 /// @c false otherwise. 7141 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 7142 TypeDiagnoser &Diagnoser) { 7143 assert(!T->isDependentType() && "type should not be dependent"); 7144 7145 QualType ElemType = Context.getBaseElementType(T); 7146 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && 7147 T->isLiteralType(Context)) 7148 return false; 7149 7150 Diagnoser.diagnose(*this, Loc, T); 7151 7152 if (T->isVariableArrayType()) 7153 return true; 7154 7155 const RecordType *RT = ElemType->getAs<RecordType>(); 7156 if (!RT) 7157 return true; 7158 7159 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 7160 7161 // A partially-defined class type can't be a literal type, because a literal 7162 // class type must have a trivial destructor (which can't be checked until 7163 // the class definition is complete). 7164 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) 7165 return true; 7166 7167 // If the class has virtual base classes, then it's not an aggregate, and 7168 // cannot have any constexpr constructors or a trivial default constructor, 7169 // so is non-literal. This is better to diagnose than the resulting absence 7170 // of constexpr constructors. 7171 if (RD->getNumVBases()) { 7172 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 7173 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 7174 for (const auto &I : RD->vbases()) 7175 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here) 7176 << I.getSourceRange(); 7177 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 7178 !RD->hasTrivialDefaultConstructor()) { 7179 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 7180 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 7181 for (const auto &I : RD->bases()) { 7182 if (!I.getType()->isLiteralType(Context)) { 7183 Diag(I.getLocStart(), 7184 diag::note_non_literal_base_class) 7185 << RD << I.getType() << I.getSourceRange(); 7186 return true; 7187 } 7188 } 7189 for (const auto *I : RD->fields()) { 7190 if (!I->getType()->isLiteralType(Context) || 7191 I->getType().isVolatileQualified()) { 7192 Diag(I->getLocation(), diag::note_non_literal_field) 7193 << RD << I << I->getType() 7194 << I->getType().isVolatileQualified(); 7195 return true; 7196 } 7197 } 7198 } else if (!RD->hasTrivialDestructor()) { 7199 // All fields and bases are of literal types, so have trivial destructors. 7200 // If this class's destructor is non-trivial it must be user-declared. 7201 CXXDestructorDecl *Dtor = RD->getDestructor(); 7202 assert(Dtor && "class has literal fields and bases but no dtor?"); 7203 if (!Dtor) 7204 return true; 7205 7206 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 7207 diag::note_non_literal_user_provided_dtor : 7208 diag::note_non_literal_nontrivial_dtor) << RD; 7209 if (!Dtor->isUserProvided()) 7210 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true); 7211 } 7212 7213 return true; 7214 } 7215 7216 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 7217 BoundTypeDiagnoser<> Diagnoser(DiagID); 7218 return RequireLiteralType(Loc, T, Diagnoser); 7219 } 7220 7221 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 7222 /// and qualified by the nested-name-specifier contained in SS. 7223 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 7224 const CXXScopeSpec &SS, QualType T) { 7225 if (T.isNull()) 7226 return T; 7227 NestedNameSpecifier *NNS; 7228 if (SS.isValid()) 7229 NNS = SS.getScopeRep(); 7230 else { 7231 if (Keyword == ETK_None) 7232 return T; 7233 NNS = nullptr; 7234 } 7235 return Context.getElaboratedType(Keyword, NNS, T); 7236 } 7237 7238 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 7239 ExprResult ER = CheckPlaceholderExpr(E); 7240 if (ER.isInvalid()) return QualType(); 7241 E = ER.get(); 7242 7243 if (!getLangOpts().CPlusPlus && E->refersToBitField()) 7244 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; 7245 7246 if (!E->isTypeDependent()) { 7247 QualType T = E->getType(); 7248 if (const TagType *TT = T->getAs<TagType>()) 7249 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 7250 } 7251 return Context.getTypeOfExprType(E); 7252 } 7253 7254 /// getDecltypeForExpr - Given an expr, will return the decltype for 7255 /// that expression, according to the rules in C++11 7256 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 7257 static QualType getDecltypeForExpr(Sema &S, Expr *E) { 7258 if (E->isTypeDependent()) 7259 return S.Context.DependentTy; 7260 7261 // C++11 [dcl.type.simple]p4: 7262 // The type denoted by decltype(e) is defined as follows: 7263 // 7264 // - if e is an unparenthesized id-expression or an unparenthesized class 7265 // member access (5.2.5), decltype(e) is the type of the entity named 7266 // by e. If there is no such entity, or if e names a set of overloaded 7267 // functions, the program is ill-formed; 7268 // 7269 // We apply the same rules for Objective-C ivar and property references. 7270 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 7271 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 7272 return VD->getType(); 7273 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 7274 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 7275 return FD->getType(); 7276 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { 7277 return IR->getDecl()->getType(); 7278 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { 7279 if (PR->isExplicitProperty()) 7280 return PR->getExplicitProperty()->getType(); 7281 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { 7282 return PE->getType(); 7283 } 7284 7285 // C++11 [expr.lambda.prim]p18: 7286 // Every occurrence of decltype((x)) where x is a possibly 7287 // parenthesized id-expression that names an entity of automatic 7288 // storage duration is treated as if x were transformed into an 7289 // access to a corresponding data member of the closure type that 7290 // would have been declared if x were an odr-use of the denoted 7291 // entity. 7292 using namespace sema; 7293 if (S.getCurLambda()) { 7294 if (isa<ParenExpr>(E)) { 7295 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 7296 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 7297 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); 7298 if (!T.isNull()) 7299 return S.Context.getLValueReferenceType(T); 7300 } 7301 } 7302 } 7303 } 7304 7305 7306 // C++11 [dcl.type.simple]p4: 7307 // [...] 7308 QualType T = E->getType(); 7309 switch (E->getValueKind()) { 7310 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 7311 // type of e; 7312 case VK_XValue: T = S.Context.getRValueReferenceType(T); break; 7313 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 7314 // type of e; 7315 case VK_LValue: T = S.Context.getLValueReferenceType(T); break; 7316 // - otherwise, decltype(e) is the type of e. 7317 case VK_RValue: break; 7318 } 7319 7320 return T; 7321 } 7322 7323 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc, 7324 bool AsUnevaluated) { 7325 ExprResult ER = CheckPlaceholderExpr(E); 7326 if (ER.isInvalid()) return QualType(); 7327 E = ER.get(); 7328 7329 if (AsUnevaluated && ActiveTemplateInstantiations.empty() && 7330 E->HasSideEffects(Context, false)) { 7331 // The expression operand for decltype is in an unevaluated expression 7332 // context, so side effects could result in unintended consequences. 7333 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 7334 } 7335 7336 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); 7337 } 7338 7339 QualType Sema::BuildUnaryTransformType(QualType BaseType, 7340 UnaryTransformType::UTTKind UKind, 7341 SourceLocation Loc) { 7342 switch (UKind) { 7343 case UnaryTransformType::EnumUnderlyingType: 7344 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 7345 Diag(Loc, diag::err_only_enums_have_underlying_types); 7346 return QualType(); 7347 } else { 7348 QualType Underlying = BaseType; 7349 if (!BaseType->isDependentType()) { 7350 // The enum could be incomplete if we're parsing its definition or 7351 // recovering from an error. 7352 NamedDecl *FwdDecl = nullptr; 7353 if (BaseType->isIncompleteType(&FwdDecl)) { 7354 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; 7355 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; 7356 return QualType(); 7357 } 7358 7359 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 7360 assert(ED && "EnumType has no EnumDecl"); 7361 7362 DiagnoseUseOfDecl(ED, Loc); 7363 7364 Underlying = ED->getIntegerType(); 7365 assert(!Underlying.isNull()); 7366 } 7367 return Context.getUnaryTransformType(BaseType, Underlying, 7368 UnaryTransformType::EnumUnderlyingType); 7369 } 7370 } 7371 llvm_unreachable("unknown unary transform type"); 7372 } 7373 7374 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 7375 if (!T->isDependentType()) { 7376 // FIXME: It isn't entirely clear whether incomplete atomic types 7377 // are allowed or not; for simplicity, ban them for the moment. 7378 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 7379 return QualType(); 7380 7381 int DisallowedKind = -1; 7382 if (T->isArrayType()) 7383 DisallowedKind = 1; 7384 else if (T->isFunctionType()) 7385 DisallowedKind = 2; 7386 else if (T->isReferenceType()) 7387 DisallowedKind = 3; 7388 else if (T->isAtomicType()) 7389 DisallowedKind = 4; 7390 else if (T.hasQualifiers()) 7391 DisallowedKind = 5; 7392 else if (!T.isTriviallyCopyableType(Context)) 7393 // Some other non-trivially-copyable type (probably a C++ class) 7394 DisallowedKind = 6; 7395 7396 if (DisallowedKind != -1) { 7397 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 7398 return QualType(); 7399 } 7400 7401 // FIXME: Do we need any handling for ARC here? 7402 } 7403 7404 // Build the pointer type. 7405 return Context.getAtomicType(T); 7406 } 7407