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