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 (void)isCompleteType(Loc, T); 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() && isCompleteType(Loc, BaseT) && 2130 !BaseT.isPODType(Context) && !BaseT->isObjCLifetimeType()) { 2131 Diag(Loc, diag::err_vla_non_pod) << BaseT; 2132 return QualType(); 2133 } 2134 // Prohibit the use of VLAs during template argument deduction. 2135 else if (isSFINAEContext()) { 2136 Diag(Loc, diag::err_vla_in_sfinae); 2137 return QualType(); 2138 } 2139 // Just extwarn about VLAs. 2140 else 2141 Diag(Loc, diag::ext_vla); 2142 } else if (ASM != ArrayType::Normal || Quals != 0) 2143 Diag(Loc, 2144 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx 2145 : diag::ext_c99_array_usage) << ASM; 2146 } 2147 2148 if (T->isVariableArrayType()) { 2149 // Warn about VLAs for -Wvla. 2150 Diag(Loc, diag::warn_vla_used); 2151 } 2152 2153 return T; 2154 } 2155 2156 /// \brief Build an ext-vector type. 2157 /// 2158 /// Run the required checks for the extended vector type. 2159 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, 2160 SourceLocation AttrLoc) { 2161 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 2162 // in conjunction with complex types (pointers, arrays, functions, etc.). 2163 if (!T->isDependentType() && 2164 !T->isIntegerType() && !T->isRealFloatingType()) { 2165 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 2166 return QualType(); 2167 } 2168 2169 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { 2170 llvm::APSInt vecSize(32); 2171 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { 2172 Diag(AttrLoc, diag::err_attribute_argument_type) 2173 << "ext_vector_type" << AANT_ArgumentIntegerConstant 2174 << ArraySize->getSourceRange(); 2175 return QualType(); 2176 } 2177 2178 // unlike gcc's vector_size attribute, the size is specified as the 2179 // number of elements, not the number of bytes. 2180 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 2181 2182 if (vectorSize == 0) { 2183 Diag(AttrLoc, diag::err_attribute_zero_size) 2184 << ArraySize->getSourceRange(); 2185 return QualType(); 2186 } 2187 2188 if (VectorType::isVectorSizeTooLarge(vectorSize)) { 2189 Diag(AttrLoc, diag::err_attribute_size_too_large) 2190 << ArraySize->getSourceRange(); 2191 return QualType(); 2192 } 2193 2194 return Context.getExtVectorType(T, vectorSize); 2195 } 2196 2197 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); 2198 } 2199 2200 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { 2201 if (T->isArrayType() || T->isFunctionType()) { 2202 Diag(Loc, diag::err_func_returning_array_function) 2203 << T->isFunctionType() << T; 2204 return true; 2205 } 2206 2207 // Functions cannot return half FP. 2208 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) { 2209 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << 2210 FixItHint::CreateInsertion(Loc, "*"); 2211 return true; 2212 } 2213 2214 // Methods cannot return interface types. All ObjC objects are 2215 // passed by reference. 2216 if (T->isObjCObjectType()) { 2217 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T; 2218 return 0; 2219 } 2220 2221 return false; 2222 } 2223 2224 QualType Sema::BuildFunctionType(QualType T, 2225 MutableArrayRef<QualType> ParamTypes, 2226 SourceLocation Loc, DeclarationName Entity, 2227 const FunctionProtoType::ExtProtoInfo &EPI) { 2228 bool Invalid = false; 2229 2230 Invalid |= CheckFunctionReturnType(T, Loc); 2231 2232 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { 2233 // FIXME: Loc is too inprecise here, should use proper locations for args. 2234 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); 2235 if (ParamType->isVoidType()) { 2236 Diag(Loc, diag::err_param_with_void_type); 2237 Invalid = true; 2238 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) { 2239 // Disallow half FP arguments. 2240 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << 2241 FixItHint::CreateInsertion(Loc, "*"); 2242 Invalid = true; 2243 } 2244 2245 ParamTypes[Idx] = ParamType; 2246 } 2247 2248 if (Invalid) 2249 return QualType(); 2250 2251 return Context.getFunctionType(T, ParamTypes, EPI); 2252 } 2253 2254 /// \brief Build a member pointer type \c T Class::*. 2255 /// 2256 /// \param T the type to which the member pointer refers. 2257 /// \param Class the class type into which the member pointer points. 2258 /// \param Loc the location where this type begins 2259 /// \param Entity the name of the entity that will have this member pointer type 2260 /// 2261 /// \returns a member pointer type, if successful, or a NULL type if there was 2262 /// an error. 2263 QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 2264 SourceLocation Loc, 2265 DeclarationName Entity) { 2266 // Verify that we're not building a pointer to pointer to function with 2267 // exception specification. 2268 if (CheckDistantExceptionSpec(T)) { 2269 Diag(Loc, diag::err_distant_exception_spec); 2270 return QualType(); 2271 } 2272 2273 // C++ 8.3.3p3: A pointer to member shall not point to ... a member 2274 // with reference type, or "cv void." 2275 if (T->isReferenceType()) { 2276 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 2277 << getPrintableNameForEntity(Entity) << T; 2278 return QualType(); 2279 } 2280 2281 if (T->isVoidType()) { 2282 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 2283 << getPrintableNameForEntity(Entity); 2284 return QualType(); 2285 } 2286 2287 if (!Class->isDependentType() && !Class->isRecordType()) { 2288 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 2289 return QualType(); 2290 } 2291 2292 // Adjust the default free function calling convention to the default method 2293 // calling convention. 2294 bool IsCtorOrDtor = 2295 (Entity.getNameKind() == DeclarationName::CXXConstructorName) || 2296 (Entity.getNameKind() == DeclarationName::CXXDestructorName); 2297 if (T->isFunctionType()) 2298 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc); 2299 2300 return Context.getMemberPointerType(T, Class.getTypePtr()); 2301 } 2302 2303 /// \brief Build a block pointer type. 2304 /// 2305 /// \param T The type to which we'll be building a block pointer. 2306 /// 2307 /// \param Loc The source location, used for diagnostics. 2308 /// 2309 /// \param Entity The name of the entity that involves the block pointer 2310 /// type, if known. 2311 /// 2312 /// \returns A suitable block pointer type, if there are no 2313 /// errors. Otherwise, returns a NULL type. 2314 QualType Sema::BuildBlockPointerType(QualType T, 2315 SourceLocation Loc, 2316 DeclarationName Entity) { 2317 if (!T->isFunctionType()) { 2318 Diag(Loc, diag::err_nonfunction_block_type); 2319 return QualType(); 2320 } 2321 2322 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer)) 2323 return QualType(); 2324 2325 return Context.getBlockPointerType(T); 2326 } 2327 2328 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { 2329 QualType QT = Ty.get(); 2330 if (QT.isNull()) { 2331 if (TInfo) *TInfo = nullptr; 2332 return QualType(); 2333 } 2334 2335 TypeSourceInfo *DI = nullptr; 2336 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 2337 QT = LIT->getType(); 2338 DI = LIT->getTypeSourceInfo(); 2339 } 2340 2341 if (TInfo) *TInfo = DI; 2342 return QT; 2343 } 2344 2345 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 2346 Qualifiers::ObjCLifetime ownership, 2347 unsigned chunkIndex); 2348 2349 /// Given that this is the declaration of a parameter under ARC, 2350 /// attempt to infer attributes and such for pointer-to-whatever 2351 /// types. 2352 static void inferARCWriteback(TypeProcessingState &state, 2353 QualType &declSpecType) { 2354 Sema &S = state.getSema(); 2355 Declarator &declarator = state.getDeclarator(); 2356 2357 // TODO: should we care about decl qualifiers? 2358 2359 // Check whether the declarator has the expected form. We walk 2360 // from the inside out in order to make the block logic work. 2361 unsigned outermostPointerIndex = 0; 2362 bool isBlockPointer = false; 2363 unsigned numPointers = 0; 2364 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 2365 unsigned chunkIndex = i; 2366 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); 2367 switch (chunk.Kind) { 2368 case DeclaratorChunk::Paren: 2369 // Ignore parens. 2370 break; 2371 2372 case DeclaratorChunk::Reference: 2373 case DeclaratorChunk::Pointer: 2374 // Count the number of pointers. Treat references 2375 // interchangeably as pointers; if they're mis-ordered, normal 2376 // type building will discover that. 2377 outermostPointerIndex = chunkIndex; 2378 numPointers++; 2379 break; 2380 2381 case DeclaratorChunk::BlockPointer: 2382 // If we have a pointer to block pointer, that's an acceptable 2383 // indirect reference; anything else is not an application of 2384 // the rules. 2385 if (numPointers != 1) return; 2386 numPointers++; 2387 outermostPointerIndex = chunkIndex; 2388 isBlockPointer = true; 2389 2390 // We don't care about pointer structure in return values here. 2391 goto done; 2392 2393 case DeclaratorChunk::Array: // suppress if written (id[])? 2394 case DeclaratorChunk::Function: 2395 case DeclaratorChunk::MemberPointer: 2396 return; 2397 } 2398 } 2399 done: 2400 2401 // If we have *one* pointer, then we want to throw the qualifier on 2402 // the declaration-specifiers, which means that it needs to be a 2403 // retainable object type. 2404 if (numPointers == 1) { 2405 // If it's not a retainable object type, the rule doesn't apply. 2406 if (!declSpecType->isObjCRetainableType()) return; 2407 2408 // If it already has lifetime, don't do anything. 2409 if (declSpecType.getObjCLifetime()) return; 2410 2411 // Otherwise, modify the type in-place. 2412 Qualifiers qs; 2413 2414 if (declSpecType->isObjCARCImplicitlyUnretainedType()) 2415 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); 2416 else 2417 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); 2418 declSpecType = S.Context.getQualifiedType(declSpecType, qs); 2419 2420 // If we have *two* pointers, then we want to throw the qualifier on 2421 // the outermost pointer. 2422 } else if (numPointers == 2) { 2423 // If we don't have a block pointer, we need to check whether the 2424 // declaration-specifiers gave us something that will turn into a 2425 // retainable object pointer after we slap the first pointer on it. 2426 if (!isBlockPointer && !declSpecType->isObjCObjectType()) 2427 return; 2428 2429 // Look for an explicit lifetime attribute there. 2430 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); 2431 if (chunk.Kind != DeclaratorChunk::Pointer && 2432 chunk.Kind != DeclaratorChunk::BlockPointer) 2433 return; 2434 for (const AttributeList *attr = chunk.getAttrs(); attr; 2435 attr = attr->getNext()) 2436 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 2437 return; 2438 2439 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, 2440 outermostPointerIndex); 2441 2442 // Any other number of pointers/references does not trigger the rule. 2443 } else return; 2444 2445 // TODO: mark whether we did this inference? 2446 } 2447 2448 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 2449 SourceLocation FallbackLoc, 2450 SourceLocation ConstQualLoc, 2451 SourceLocation VolatileQualLoc, 2452 SourceLocation RestrictQualLoc, 2453 SourceLocation AtomicQualLoc) { 2454 if (!Quals) 2455 return; 2456 2457 struct Qual { 2458 const char *Name; 2459 unsigned Mask; 2460 SourceLocation Loc; 2461 } const QualKinds[4] = { 2462 { "const", DeclSpec::TQ_const, ConstQualLoc }, 2463 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc }, 2464 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc }, 2465 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc } 2466 }; 2467 2468 SmallString<32> QualStr; 2469 unsigned NumQuals = 0; 2470 SourceLocation Loc; 2471 FixItHint FixIts[4]; 2472 2473 // Build a string naming the redundant qualifiers. 2474 for (unsigned I = 0; I != 4; ++I) { 2475 if (Quals & QualKinds[I].Mask) { 2476 if (!QualStr.empty()) QualStr += ' '; 2477 QualStr += QualKinds[I].Name; 2478 2479 // If we have a location for the qualifier, offer a fixit. 2480 SourceLocation QualLoc = QualKinds[I].Loc; 2481 if (QualLoc.isValid()) { 2482 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); 2483 if (Loc.isInvalid() || 2484 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)) 2485 Loc = QualLoc; 2486 } 2487 2488 ++NumQuals; 2489 } 2490 } 2491 2492 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID) 2493 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; 2494 } 2495 2496 // Diagnose pointless type qualifiers on the return type of a function. 2497 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, 2498 Declarator &D, 2499 unsigned FunctionChunkIndex) { 2500 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) { 2501 // FIXME: TypeSourceInfo doesn't preserve location information for 2502 // qualifiers. 2503 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2504 RetTy.getLocalCVRQualifiers(), 2505 D.getIdentifierLoc()); 2506 return; 2507 } 2508 2509 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, 2510 End = D.getNumTypeObjects(); 2511 OuterChunkIndex != End; ++OuterChunkIndex) { 2512 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); 2513 switch (OuterChunk.Kind) { 2514 case DeclaratorChunk::Paren: 2515 continue; 2516 2517 case DeclaratorChunk::Pointer: { 2518 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; 2519 S.diagnoseIgnoredQualifiers( 2520 diag::warn_qual_return_type, 2521 PTI.TypeQuals, 2522 SourceLocation(), 2523 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), 2524 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), 2525 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), 2526 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc)); 2527 return; 2528 } 2529 2530 case DeclaratorChunk::Function: 2531 case DeclaratorChunk::BlockPointer: 2532 case DeclaratorChunk::Reference: 2533 case DeclaratorChunk::Array: 2534 case DeclaratorChunk::MemberPointer: 2535 // FIXME: We can't currently provide an accurate source location and a 2536 // fix-it hint for these. 2537 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; 2538 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2539 RetTy.getCVRQualifiers() | AtomicQual, 2540 D.getIdentifierLoc()); 2541 return; 2542 } 2543 2544 llvm_unreachable("unknown declarator chunk kind"); 2545 } 2546 2547 // If the qualifiers come from a conversion function type, don't diagnose 2548 // them -- they're not necessarily redundant, since such a conversion 2549 // operator can be explicitly called as "x.operator const int()". 2550 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 2551 return; 2552 2553 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers 2554 // which are present there. 2555 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, 2556 D.getDeclSpec().getTypeQualifiers(), 2557 D.getIdentifierLoc(), 2558 D.getDeclSpec().getConstSpecLoc(), 2559 D.getDeclSpec().getVolatileSpecLoc(), 2560 D.getDeclSpec().getRestrictSpecLoc(), 2561 D.getDeclSpec().getAtomicSpecLoc()); 2562 } 2563 2564 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, 2565 TypeSourceInfo *&ReturnTypeInfo) { 2566 Sema &SemaRef = state.getSema(); 2567 Declarator &D = state.getDeclarator(); 2568 QualType T; 2569 ReturnTypeInfo = nullptr; 2570 2571 // The TagDecl owned by the DeclSpec. 2572 TagDecl *OwnedTagDecl = nullptr; 2573 2574 switch (D.getName().getKind()) { 2575 case UnqualifiedId::IK_ImplicitSelfParam: 2576 case UnqualifiedId::IK_OperatorFunctionId: 2577 case UnqualifiedId::IK_Identifier: 2578 case UnqualifiedId::IK_LiteralOperatorId: 2579 case UnqualifiedId::IK_TemplateId: 2580 T = ConvertDeclSpecToType(state); 2581 2582 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 2583 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 2584 // Owned declaration is embedded in declarator. 2585 OwnedTagDecl->setEmbeddedInDeclarator(true); 2586 } 2587 break; 2588 2589 case UnqualifiedId::IK_ConstructorName: 2590 case UnqualifiedId::IK_ConstructorTemplateId: 2591 case UnqualifiedId::IK_DestructorName: 2592 // Constructors and destructors don't have return types. Use 2593 // "void" instead. 2594 T = SemaRef.Context.VoidTy; 2595 processTypeAttrs(state, T, TAL_DeclSpec, 2596 D.getDeclSpec().getAttributes().getList()); 2597 break; 2598 2599 case UnqualifiedId::IK_ConversionFunctionId: 2600 // The result type of a conversion function is the type that it 2601 // converts to. 2602 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, 2603 &ReturnTypeInfo); 2604 break; 2605 } 2606 2607 if (D.getAttributes()) 2608 distributeTypeAttrsFromDeclarator(state, T); 2609 2610 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. 2611 if (D.getDeclSpec().containsPlaceholderType()) { 2612 int Error = -1; 2613 2614 switch (D.getContext()) { 2615 case Declarator::LambdaExprContext: 2616 llvm_unreachable("Can't specify a type specifier in lambda grammar"); 2617 case Declarator::ObjCParameterContext: 2618 case Declarator::ObjCResultContext: 2619 case Declarator::PrototypeContext: 2620 Error = 0; 2621 break; 2622 case Declarator::LambdaExprParameterContext: 2623 // In C++14, generic lambdas allow 'auto' in their parameters. 2624 if (!(SemaRef.getLangOpts().CPlusPlus14 2625 && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto)) 2626 Error = 16; 2627 break; 2628 case Declarator::MemberContext: { 2629 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || 2630 D.isFunctionDeclarator()) 2631 break; 2632 bool Cxx = SemaRef.getLangOpts().CPlusPlus; 2633 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { 2634 case TTK_Enum: llvm_unreachable("unhandled tag kind"); 2635 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break; 2636 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break; 2637 case TTK_Class: Error = 5; /* Class member */ break; 2638 case TTK_Interface: Error = 6; /* Interface member */ break; 2639 } 2640 break; 2641 } 2642 case Declarator::CXXCatchContext: 2643 case Declarator::ObjCCatchContext: 2644 Error = 7; // Exception declaration 2645 break; 2646 case Declarator::TemplateParamContext: 2647 Error = 8; // Template parameter 2648 break; 2649 case Declarator::BlockLiteralContext: 2650 Error = 9; // Block literal 2651 break; 2652 case Declarator::TemplateTypeArgContext: 2653 Error = 10; // Template type argument 2654 break; 2655 case Declarator::AliasDeclContext: 2656 case Declarator::AliasTemplateContext: 2657 Error = 12; // Type alias 2658 break; 2659 case Declarator::TrailingReturnContext: 2660 if (!SemaRef.getLangOpts().CPlusPlus14 || 2661 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type) 2662 Error = 13; // Function return type 2663 break; 2664 case Declarator::ConversionIdContext: 2665 if (!SemaRef.getLangOpts().CPlusPlus14 || 2666 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type) 2667 Error = 14; // conversion-type-id 2668 break; 2669 case Declarator::TypeNameContext: 2670 Error = 15; // Generic 2671 break; 2672 case Declarator::FileContext: 2673 case Declarator::BlockContext: 2674 case Declarator::ForContext: 2675 case Declarator::ConditionContext: 2676 break; 2677 case Declarator::CXXNewContext: 2678 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type) 2679 Error = 17; // 'new' type 2680 break; 2681 case Declarator::KNRTypeListContext: 2682 Error = 18; // K&R function parameter 2683 break; 2684 } 2685 2686 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 2687 Error = 11; 2688 2689 // In Objective-C it is an error to use 'auto' on a function declarator 2690 // (and everywhere for '__auto_type'). 2691 if (D.isFunctionDeclarator() && 2692 (!SemaRef.getLangOpts().CPlusPlus11 || 2693 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)) 2694 Error = 13; 2695 2696 bool HaveTrailing = false; 2697 2698 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator 2699 // contains a trailing return type. That is only legal at the outermost 2700 // level. Check all declarator chunks (outermost first) anyway, to give 2701 // better diagnostics. 2702 // We don't support '__auto_type' with trailing return types. 2703 if (SemaRef.getLangOpts().CPlusPlus11 && 2704 D.getDeclSpec().getTypeSpecType() != DeclSpec::TST_auto_type) { 2705 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2706 unsigned chunkIndex = e - i - 1; 2707 state.setCurrentChunkIndex(chunkIndex); 2708 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 2709 if (DeclType.Kind == DeclaratorChunk::Function) { 2710 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2711 if (FTI.hasTrailingReturnType()) { 2712 HaveTrailing = true; 2713 Error = -1; 2714 break; 2715 } 2716 } 2717 } 2718 } 2719 2720 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); 2721 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 2722 AutoRange = D.getName().getSourceRange(); 2723 2724 if (Error != -1) { 2725 unsigned Keyword; 2726 switch (D.getDeclSpec().getTypeSpecType()) { 2727 case DeclSpec::TST_auto: Keyword = 0; break; 2728 case DeclSpec::TST_decltype_auto: Keyword = 1; break; 2729 case DeclSpec::TST_auto_type: Keyword = 2; break; 2730 default: llvm_unreachable("unknown auto TypeSpecType"); 2731 } 2732 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) 2733 << Keyword << Error << AutoRange; 2734 T = SemaRef.Context.IntTy; 2735 D.setInvalidType(true); 2736 } else if (!HaveTrailing) { 2737 // If there was a trailing return type, we already got 2738 // warn_cxx98_compat_trailing_return_type in the parser. 2739 SemaRef.Diag(AutoRange.getBegin(), 2740 diag::warn_cxx98_compat_auto_type_specifier) 2741 << AutoRange; 2742 } 2743 } 2744 2745 if (SemaRef.getLangOpts().CPlusPlus && 2746 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { 2747 // Check the contexts where C++ forbids the declaration of a new class 2748 // or enumeration in a type-specifier-seq. 2749 unsigned DiagID = 0; 2750 switch (D.getContext()) { 2751 case Declarator::TrailingReturnContext: 2752 // Class and enumeration definitions are syntactically not allowed in 2753 // trailing return types. 2754 llvm_unreachable("parser should not have allowed this"); 2755 break; 2756 case Declarator::FileContext: 2757 case Declarator::MemberContext: 2758 case Declarator::BlockContext: 2759 case Declarator::ForContext: 2760 case Declarator::BlockLiteralContext: 2761 case Declarator::LambdaExprContext: 2762 // C++11 [dcl.type]p3: 2763 // A type-specifier-seq shall not define a class or enumeration unless 2764 // it appears in the type-id of an alias-declaration (7.1.3) that is not 2765 // the declaration of a template-declaration. 2766 case Declarator::AliasDeclContext: 2767 break; 2768 case Declarator::AliasTemplateContext: 2769 DiagID = diag::err_type_defined_in_alias_template; 2770 break; 2771 case Declarator::TypeNameContext: 2772 case Declarator::ConversionIdContext: 2773 case Declarator::TemplateParamContext: 2774 case Declarator::CXXNewContext: 2775 case Declarator::CXXCatchContext: 2776 case Declarator::ObjCCatchContext: 2777 case Declarator::TemplateTypeArgContext: 2778 DiagID = diag::err_type_defined_in_type_specifier; 2779 break; 2780 case Declarator::PrototypeContext: 2781 case Declarator::LambdaExprParameterContext: 2782 case Declarator::ObjCParameterContext: 2783 case Declarator::ObjCResultContext: 2784 case Declarator::KNRTypeListContext: 2785 // C++ [dcl.fct]p6: 2786 // Types shall not be defined in return or parameter types. 2787 DiagID = diag::err_type_defined_in_param_type; 2788 break; 2789 case Declarator::ConditionContext: 2790 // C++ 6.4p2: 2791 // The type-specifier-seq shall not contain typedef and shall not declare 2792 // a new class or enumeration. 2793 DiagID = diag::err_type_defined_in_condition; 2794 break; 2795 } 2796 2797 if (DiagID != 0) { 2798 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID) 2799 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2800 D.setInvalidType(true); 2801 } 2802 } 2803 2804 assert(!T.isNull() && "This function should not return a null type"); 2805 return T; 2806 } 2807 2808 /// Produce an appropriate diagnostic for an ambiguity between a function 2809 /// declarator and a C++ direct-initializer. 2810 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, 2811 DeclaratorChunk &DeclType, QualType RT) { 2812 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2813 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity"); 2814 2815 // If the return type is void there is no ambiguity. 2816 if (RT->isVoidType()) 2817 return; 2818 2819 // An initializer for a non-class type can have at most one argument. 2820 if (!RT->isRecordType() && FTI.NumParams > 1) 2821 return; 2822 2823 // An initializer for a reference must have exactly one argument. 2824 if (RT->isReferenceType() && FTI.NumParams != 1) 2825 return; 2826 2827 // Only warn if this declarator is declaring a function at block scope, and 2828 // doesn't have a storage class (such as 'extern') specified. 2829 if (!D.isFunctionDeclarator() || 2830 D.getFunctionDefinitionKind() != FDK_Declaration || 2831 !S.CurContext->isFunctionOrMethod() || 2832 D.getDeclSpec().getStorageClassSpec() 2833 != DeclSpec::SCS_unspecified) 2834 return; 2835 2836 // Inside a condition, a direct initializer is not permitted. We allow one to 2837 // be parsed in order to give better diagnostics in condition parsing. 2838 if (D.getContext() == Declarator::ConditionContext) 2839 return; 2840 2841 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); 2842 2843 S.Diag(DeclType.Loc, 2844 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration 2845 : diag::warn_empty_parens_are_function_decl) 2846 << ParenRange; 2847 2848 // If the declaration looks like: 2849 // T var1, 2850 // f(); 2851 // and name lookup finds a function named 'f', then the ',' was 2852 // probably intended to be a ';'. 2853 if (!D.isFirstDeclarator() && D.getIdentifier()) { 2854 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); 2855 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); 2856 if (Comma.getFileID() != Name.getFileID() || 2857 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { 2858 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 2859 Sema::LookupOrdinaryName); 2860 if (S.LookupName(Result, S.getCurScope())) 2861 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) 2862 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") 2863 << D.getIdentifier(); 2864 } 2865 } 2866 2867 if (FTI.NumParams > 0) { 2868 // For a declaration with parameters, eg. "T var(T());", suggest adding 2869 // parens around the first parameter to turn the declaration into a 2870 // variable declaration. 2871 SourceRange Range = FTI.Params[0].Param->getSourceRange(); 2872 SourceLocation B = Range.getBegin(); 2873 SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); 2874 // FIXME: Maybe we should suggest adding braces instead of parens 2875 // in C++11 for classes that don't have an initializer_list constructor. 2876 S.Diag(B, diag::note_additional_parens_for_variable_declaration) 2877 << FixItHint::CreateInsertion(B, "(") 2878 << FixItHint::CreateInsertion(E, ")"); 2879 } else { 2880 // For a declaration without parameters, eg. "T var();", suggest replacing 2881 // the parens with an initializer to turn the declaration into a variable 2882 // declaration. 2883 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); 2884 2885 // Empty parens mean value-initialization, and no parens mean 2886 // default initialization. These are equivalent if the default 2887 // constructor is user-provided or if zero-initialization is a 2888 // no-op. 2889 if (RD && RD->hasDefinition() && 2890 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) 2891 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) 2892 << FixItHint::CreateRemoval(ParenRange); 2893 else { 2894 std::string Init = 2895 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); 2896 if (Init.empty() && S.LangOpts.CPlusPlus11) 2897 Init = "{}"; 2898 if (!Init.empty()) 2899 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) 2900 << FixItHint::CreateReplacement(ParenRange, Init); 2901 } 2902 } 2903 } 2904 2905 /// Helper for figuring out the default CC for a function declarator type. If 2906 /// this is the outermost chunk, then we can determine the CC from the 2907 /// declarator context. If not, then this could be either a member function 2908 /// type or normal function type. 2909 static CallingConv 2910 getCCForDeclaratorChunk(Sema &S, Declarator &D, 2911 const DeclaratorChunk::FunctionTypeInfo &FTI, 2912 unsigned ChunkIndex) { 2913 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function); 2914 2915 bool IsCXXInstanceMethod = false; 2916 2917 if (S.getLangOpts().CPlusPlus) { 2918 // Look inwards through parentheses to see if this chunk will form a 2919 // member pointer type or if we're the declarator. Any type attributes 2920 // between here and there will override the CC we choose here. 2921 unsigned I = ChunkIndex; 2922 bool FoundNonParen = false; 2923 while (I && !FoundNonParen) { 2924 --I; 2925 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) 2926 FoundNonParen = true; 2927 } 2928 2929 if (FoundNonParen) { 2930 // If we're not the declarator, we're a regular function type unless we're 2931 // in a member pointer. 2932 IsCXXInstanceMethod = 2933 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; 2934 } else if (D.getContext() == Declarator::LambdaExprContext) { 2935 // This can only be a call operator for a lambda, which is an instance 2936 // method. 2937 IsCXXInstanceMethod = true; 2938 } else { 2939 // We're the innermost decl chunk, so must be a function declarator. 2940 assert(D.isFunctionDeclarator()); 2941 2942 // If we're inside a record, we're declaring a method, but it could be 2943 // explicitly or implicitly static. 2944 IsCXXInstanceMethod = 2945 D.isFirstDeclarationOfMember() && 2946 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 2947 !D.isStaticMember(); 2948 } 2949 } 2950 2951 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic, 2952 IsCXXInstanceMethod); 2953 2954 // Attribute AT_OpenCLKernel affects the calling convention only on 2955 // the SPIR target, hence it cannot be treated as a calling 2956 // convention attribute. This is the simplest place to infer 2957 // "spir_kernel" for OpenCL kernels on SPIR. 2958 if (CC == CC_SpirFunction) { 2959 for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList(); 2960 Attr; Attr = Attr->getNext()) { 2961 if (Attr->getKind() == AttributeList::AT_OpenCLKernel) { 2962 CC = CC_SpirKernel; 2963 break; 2964 } 2965 } 2966 } 2967 2968 return CC; 2969 } 2970 2971 namespace { 2972 /// A simple notion of pointer kinds, which matches up with the various 2973 /// pointer declarators. 2974 enum class SimplePointerKind { 2975 Pointer, 2976 BlockPointer, 2977 MemberPointer, 2978 }; 2979 } 2980 2981 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { 2982 switch (nullability) { 2983 case NullabilityKind::NonNull: 2984 if (!Ident__Nonnull) 2985 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull"); 2986 return Ident__Nonnull; 2987 2988 case NullabilityKind::Nullable: 2989 if (!Ident__Nullable) 2990 Ident__Nullable = PP.getIdentifierInfo("_Nullable"); 2991 return Ident__Nullable; 2992 2993 case NullabilityKind::Unspecified: 2994 if (!Ident__Null_unspecified) 2995 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified"); 2996 return Ident__Null_unspecified; 2997 } 2998 llvm_unreachable("Unknown nullability kind."); 2999 } 3000 3001 /// Retrieve the identifier "NSError". 3002 IdentifierInfo *Sema::getNSErrorIdent() { 3003 if (!Ident_NSError) 3004 Ident_NSError = PP.getIdentifierInfo("NSError"); 3005 3006 return Ident_NSError; 3007 } 3008 3009 /// Check whether there is a nullability attribute of any kind in the given 3010 /// attribute list. 3011 static bool hasNullabilityAttr(const AttributeList *attrs) { 3012 for (const AttributeList *attr = attrs; attr; 3013 attr = attr->getNext()) { 3014 if (attr->getKind() == AttributeList::AT_TypeNonNull || 3015 attr->getKind() == AttributeList::AT_TypeNullable || 3016 attr->getKind() == AttributeList::AT_TypeNullUnspecified) 3017 return true; 3018 } 3019 3020 return false; 3021 } 3022 3023 namespace { 3024 /// Describes the kind of a pointer a declarator describes. 3025 enum class PointerDeclaratorKind { 3026 // Not a pointer. 3027 NonPointer, 3028 // Single-level pointer. 3029 SingleLevelPointer, 3030 // Multi-level pointer (of any pointer kind). 3031 MultiLevelPointer, 3032 // CFFooRef* 3033 MaybePointerToCFRef, 3034 // CFErrorRef* 3035 CFErrorRefPointer, 3036 // NSError** 3037 NSErrorPointerPointer, 3038 }; 3039 } 3040 3041 /// Classify the given declarator, whose type-specified is \c type, based on 3042 /// what kind of pointer it refers to. 3043 /// 3044 /// This is used to determine the default nullability. 3045 static PointerDeclaratorKind classifyPointerDeclarator(Sema &S, 3046 QualType type, 3047 Declarator &declarator) { 3048 unsigned numNormalPointers = 0; 3049 3050 // For any dependent type, we consider it a non-pointer. 3051 if (type->isDependentType()) 3052 return PointerDeclaratorKind::NonPointer; 3053 3054 // Look through the declarator chunks to identify pointers. 3055 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { 3056 DeclaratorChunk &chunk = declarator.getTypeObject(i); 3057 switch (chunk.Kind) { 3058 case DeclaratorChunk::Array: 3059 case DeclaratorChunk::Function: 3060 break; 3061 3062 case DeclaratorChunk::BlockPointer: 3063 case DeclaratorChunk::MemberPointer: 3064 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3065 : PointerDeclaratorKind::SingleLevelPointer; 3066 3067 case DeclaratorChunk::Paren: 3068 case DeclaratorChunk::Reference: 3069 continue; 3070 3071 case DeclaratorChunk::Pointer: 3072 ++numNormalPointers; 3073 if (numNormalPointers > 2) 3074 return PointerDeclaratorKind::MultiLevelPointer; 3075 continue; 3076 } 3077 } 3078 3079 // Then, dig into the type specifier itself. 3080 unsigned numTypeSpecifierPointers = 0; 3081 do { 3082 // Decompose normal pointers. 3083 if (auto ptrType = type->getAs<PointerType>()) { 3084 ++numNormalPointers; 3085 3086 if (numNormalPointers > 2) 3087 return PointerDeclaratorKind::MultiLevelPointer; 3088 3089 type = ptrType->getPointeeType(); 3090 ++numTypeSpecifierPointers; 3091 continue; 3092 } 3093 3094 // Decompose block pointers. 3095 if (type->getAs<BlockPointerType>()) { 3096 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3097 : PointerDeclaratorKind::SingleLevelPointer; 3098 } 3099 3100 // Decompose member pointers. 3101 if (type->getAs<MemberPointerType>()) { 3102 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer 3103 : PointerDeclaratorKind::SingleLevelPointer; 3104 } 3105 3106 // Look at Objective-C object pointers. 3107 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { 3108 ++numNormalPointers; 3109 ++numTypeSpecifierPointers; 3110 3111 // If this is NSError**, report that. 3112 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { 3113 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() && 3114 numNormalPointers == 2 && numTypeSpecifierPointers < 2) { 3115 return PointerDeclaratorKind::NSErrorPointerPointer; 3116 } 3117 } 3118 3119 break; 3120 } 3121 3122 // Look at Objective-C class types. 3123 if (auto objcClass = type->getAs<ObjCInterfaceType>()) { 3124 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) { 3125 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) 3126 return PointerDeclaratorKind::NSErrorPointerPointer;; 3127 } 3128 3129 break; 3130 } 3131 3132 // If at this point we haven't seen a pointer, we won't see one. 3133 if (numNormalPointers == 0) 3134 return PointerDeclaratorKind::NonPointer; 3135 3136 if (auto recordType = type->getAs<RecordType>()) { 3137 RecordDecl *recordDecl = recordType->getDecl(); 3138 3139 bool isCFError = false; 3140 if (S.CFError) { 3141 // If we already know about CFError, test it directly. 3142 isCFError = (S.CFError == recordDecl); 3143 } else { 3144 // Check whether this is CFError, which we identify based on its bridge 3145 // to NSError. 3146 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) { 3147 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) { 3148 if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) { 3149 S.CFError = recordDecl; 3150 isCFError = true; 3151 } 3152 } 3153 } 3154 } 3155 3156 // If this is CFErrorRef*, report it as such. 3157 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) { 3158 return PointerDeclaratorKind::CFErrorRefPointer; 3159 } 3160 break; 3161 } 3162 3163 break; 3164 } while (true); 3165 3166 3167 switch (numNormalPointers) { 3168 case 0: 3169 return PointerDeclaratorKind::NonPointer; 3170 3171 case 1: 3172 return PointerDeclaratorKind::SingleLevelPointer; 3173 3174 case 2: 3175 return PointerDeclaratorKind::MaybePointerToCFRef; 3176 3177 default: 3178 return PointerDeclaratorKind::MultiLevelPointer; 3179 } 3180 } 3181 3182 static FileID getNullabilityCompletenessCheckFileID(Sema &S, 3183 SourceLocation loc) { 3184 // If we're anywhere in a function, method, or closure context, don't perform 3185 // completeness checks. 3186 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { 3187 if (ctx->isFunctionOrMethod()) 3188 return FileID(); 3189 3190 if (ctx->isFileContext()) 3191 break; 3192 } 3193 3194 // We only care about the expansion location. 3195 loc = S.SourceMgr.getExpansionLoc(loc); 3196 FileID file = S.SourceMgr.getFileID(loc); 3197 if (file.isInvalid()) 3198 return FileID(); 3199 3200 // Retrieve file information. 3201 bool invalid = false; 3202 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid); 3203 if (invalid || !sloc.isFile()) 3204 return FileID(); 3205 3206 // We don't want to perform completeness checks on the main file or in 3207 // system headers. 3208 const SrcMgr::FileInfo &fileInfo = sloc.getFile(); 3209 if (fileInfo.getIncludeLoc().isInvalid()) 3210 return FileID(); 3211 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && 3212 S.Diags.getSuppressSystemWarnings()) { 3213 return FileID(); 3214 } 3215 3216 return file; 3217 } 3218 3219 /// Check for consistent use of nullability. 3220 static void checkNullabilityConsistency(TypeProcessingState &state, 3221 SimplePointerKind pointerKind, 3222 SourceLocation pointerLoc) { 3223 Sema &S = state.getSema(); 3224 3225 // Determine which file we're performing consistency checking for. 3226 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc); 3227 if (file.isInvalid()) 3228 return; 3229 3230 // If we haven't seen any type nullability in this file, we won't warn now 3231 // about anything. 3232 FileNullability &fileNullability = S.NullabilityMap[file]; 3233 if (!fileNullability.SawTypeNullability) { 3234 // If this is the first pointer declarator in the file, record it. 3235 if (fileNullability.PointerLoc.isInvalid() && 3236 !S.Context.getDiagnostics().isIgnored(diag::warn_nullability_missing, 3237 pointerLoc)) { 3238 fileNullability.PointerLoc = pointerLoc; 3239 fileNullability.PointerKind = static_cast<unsigned>(pointerKind); 3240 } 3241 3242 return; 3243 } 3244 3245 // Complain about missing nullability. 3246 S.Diag(pointerLoc, diag::warn_nullability_missing) 3247 << static_cast<unsigned>(pointerKind); 3248 } 3249 3250 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 3251 QualType declSpecType, 3252 TypeSourceInfo *TInfo) { 3253 // The TypeSourceInfo that this function returns will not be a null type. 3254 // If there is an error, this function will fill in a dummy type as fallback. 3255 QualType T = declSpecType; 3256 Declarator &D = state.getDeclarator(); 3257 Sema &S = state.getSema(); 3258 ASTContext &Context = S.Context; 3259 const LangOptions &LangOpts = S.getLangOpts(); 3260 3261 // The name we're declaring, if any. 3262 DeclarationName Name; 3263 if (D.getIdentifier()) 3264 Name = D.getIdentifier(); 3265 3266 // Does this declaration declare a typedef-name? 3267 bool IsTypedefName = 3268 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 3269 D.getContext() == Declarator::AliasDeclContext || 3270 D.getContext() == Declarator::AliasTemplateContext; 3271 3272 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 3273 bool IsQualifiedFunction = T->isFunctionProtoType() && 3274 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 || 3275 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); 3276 3277 // If T is 'decltype(auto)', the only declarators we can have are parens 3278 // and at most one function declarator if this is a function declaration. 3279 if (const AutoType *AT = T->getAs<AutoType>()) { 3280 if (AT->isDecltypeAuto()) { 3281 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3282 unsigned Index = E - I - 1; 3283 DeclaratorChunk &DeclChunk = D.getTypeObject(Index); 3284 unsigned DiagId = diag::err_decltype_auto_compound_type; 3285 unsigned DiagKind = 0; 3286 switch (DeclChunk.Kind) { 3287 case DeclaratorChunk::Paren: 3288 continue; 3289 case DeclaratorChunk::Function: { 3290 unsigned FnIndex; 3291 if (D.isFunctionDeclarationContext() && 3292 D.isFunctionDeclarator(FnIndex) && FnIndex == Index) 3293 continue; 3294 DiagId = diag::err_decltype_auto_function_declarator_not_declaration; 3295 break; 3296 } 3297 case DeclaratorChunk::Pointer: 3298 case DeclaratorChunk::BlockPointer: 3299 case DeclaratorChunk::MemberPointer: 3300 DiagKind = 0; 3301 break; 3302 case DeclaratorChunk::Reference: 3303 DiagKind = 1; 3304 break; 3305 case DeclaratorChunk::Array: 3306 DiagKind = 2; 3307 break; 3308 } 3309 3310 S.Diag(DeclChunk.Loc, DiagId) << DiagKind; 3311 D.setInvalidType(true); 3312 break; 3313 } 3314 } 3315 } 3316 3317 // Determine whether we should infer _Nonnull on pointer types. 3318 Optional<NullabilityKind> inferNullability; 3319 bool inferNullabilityCS = false; 3320 bool inferNullabilityInnerOnly = false; 3321 bool inferNullabilityInnerOnlyComplete = false; 3322 3323 // Are we in an assume-nonnull region? 3324 bool inAssumeNonNullRegion = false; 3325 if (S.PP.getPragmaAssumeNonNullLoc().isValid()) { 3326 inAssumeNonNullRegion = true; 3327 // Determine which file we saw the assume-nonnull region in. 3328 FileID file = getNullabilityCompletenessCheckFileID( 3329 S, S.PP.getPragmaAssumeNonNullLoc()); 3330 if (file.isValid()) { 3331 FileNullability &fileNullability = S.NullabilityMap[file]; 3332 3333 // If we haven't seen any type nullability before, now we have. 3334 if (!fileNullability.SawTypeNullability) { 3335 if (fileNullability.PointerLoc.isValid()) { 3336 S.Diag(fileNullability.PointerLoc, diag::warn_nullability_missing) 3337 << static_cast<unsigned>(fileNullability.PointerKind); 3338 } 3339 3340 fileNullability.SawTypeNullability = true; 3341 } 3342 } 3343 } 3344 3345 // Whether to complain about missing nullability specifiers or not. 3346 enum { 3347 /// Never complain. 3348 CAMN_No, 3349 /// Complain on the inner pointers (but not the outermost 3350 /// pointer). 3351 CAMN_InnerPointers, 3352 /// Complain about any pointers that don't have nullability 3353 /// specified or inferred. 3354 CAMN_Yes 3355 } complainAboutMissingNullability = CAMN_No; 3356 unsigned NumPointersRemaining = 0; 3357 3358 if (IsTypedefName) { 3359 // For typedefs, we do not infer any nullability (the default), 3360 // and we only complain about missing nullability specifiers on 3361 // inner pointers. 3362 complainAboutMissingNullability = CAMN_InnerPointers; 3363 3364 if (T->canHaveNullability() && !T->getNullability(S.Context)) { 3365 ++NumPointersRemaining; 3366 } 3367 3368 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { 3369 DeclaratorChunk &chunk = D.getTypeObject(i); 3370 switch (chunk.Kind) { 3371 case DeclaratorChunk::Array: 3372 case DeclaratorChunk::Function: 3373 break; 3374 3375 case DeclaratorChunk::BlockPointer: 3376 case DeclaratorChunk::MemberPointer: 3377 ++NumPointersRemaining; 3378 break; 3379 3380 case DeclaratorChunk::Paren: 3381 case DeclaratorChunk::Reference: 3382 continue; 3383 3384 case DeclaratorChunk::Pointer: 3385 ++NumPointersRemaining; 3386 continue; 3387 } 3388 } 3389 } else { 3390 bool isFunctionOrMethod = false; 3391 switch (auto context = state.getDeclarator().getContext()) { 3392 case Declarator::ObjCParameterContext: 3393 case Declarator::ObjCResultContext: 3394 case Declarator::PrototypeContext: 3395 case Declarator::TrailingReturnContext: 3396 isFunctionOrMethod = true; 3397 // fallthrough 3398 3399 case Declarator::MemberContext: 3400 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { 3401 complainAboutMissingNullability = CAMN_No; 3402 break; 3403 } 3404 3405 // Weak properties are inferred to be nullable. 3406 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) { 3407 inferNullability = NullabilityKind::Nullable; 3408 break; 3409 } 3410 3411 // fallthrough 3412 3413 case Declarator::FileContext: 3414 case Declarator::KNRTypeListContext: 3415 complainAboutMissingNullability = CAMN_Yes; 3416 3417 // Nullability inference depends on the type and declarator. 3418 switch (classifyPointerDeclarator(S, T, D)) { 3419 case PointerDeclaratorKind::NonPointer: 3420 case PointerDeclaratorKind::MultiLevelPointer: 3421 // Cannot infer nullability. 3422 break; 3423 3424 case PointerDeclaratorKind::SingleLevelPointer: 3425 // Infer _Nonnull if we are in an assumes-nonnull region. 3426 if (inAssumeNonNullRegion) { 3427 inferNullability = NullabilityKind::NonNull; 3428 inferNullabilityCS = (context == Declarator::ObjCParameterContext || 3429 context == Declarator::ObjCResultContext); 3430 } 3431 break; 3432 3433 case PointerDeclaratorKind::CFErrorRefPointer: 3434 case PointerDeclaratorKind::NSErrorPointerPointer: 3435 // Within a function or method signature, infer _Nullable at both 3436 // levels. 3437 if (isFunctionOrMethod && inAssumeNonNullRegion) 3438 inferNullability = NullabilityKind::Nullable; 3439 break; 3440 3441 case PointerDeclaratorKind::MaybePointerToCFRef: 3442 if (isFunctionOrMethod) { 3443 // On pointer-to-pointer parameters marked cf_returns_retained or 3444 // cf_returns_not_retained, if the outer pointer is explicit then 3445 // infer the inner pointer as _Nullable. 3446 auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool { 3447 while (NextAttr) { 3448 if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained || 3449 NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained) 3450 return true; 3451 NextAttr = NextAttr->getNext(); 3452 } 3453 return false; 3454 }; 3455 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { 3456 if (hasCFReturnsAttr(D.getAttributes()) || 3457 hasCFReturnsAttr(InnermostChunk->getAttrs()) || 3458 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) { 3459 inferNullability = NullabilityKind::Nullable; 3460 inferNullabilityInnerOnly = true; 3461 } 3462 } 3463 } 3464 break; 3465 } 3466 break; 3467 3468 case Declarator::ConversionIdContext: 3469 complainAboutMissingNullability = CAMN_Yes; 3470 break; 3471 3472 case Declarator::AliasDeclContext: 3473 case Declarator::AliasTemplateContext: 3474 case Declarator::BlockContext: 3475 case Declarator::BlockLiteralContext: 3476 case Declarator::ConditionContext: 3477 case Declarator::CXXCatchContext: 3478 case Declarator::CXXNewContext: 3479 case Declarator::ForContext: 3480 case Declarator::LambdaExprContext: 3481 case Declarator::LambdaExprParameterContext: 3482 case Declarator::ObjCCatchContext: 3483 case Declarator::TemplateParamContext: 3484 case Declarator::TemplateTypeArgContext: 3485 case Declarator::TypeNameContext: 3486 // Don't infer in these contexts. 3487 break; 3488 } 3489 } 3490 3491 // Local function that checks the nullability for a given pointer declarator. 3492 // Returns true if _Nonnull was inferred. 3493 auto inferPointerNullability = [&](SimplePointerKind pointerKind, 3494 SourceLocation pointerLoc, 3495 AttributeList *&attrs) -> AttributeList * { 3496 // We've seen a pointer. 3497 if (NumPointersRemaining > 0) 3498 --NumPointersRemaining; 3499 3500 // If a nullability attribute is present, there's nothing to do. 3501 if (hasNullabilityAttr(attrs)) 3502 return nullptr; 3503 3504 // If we're supposed to infer nullability, do so now. 3505 if (inferNullability && !inferNullabilityInnerOnlyComplete) { 3506 AttributeList::Syntax syntax 3507 = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword 3508 : AttributeList::AS_Keyword; 3509 AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool() 3510 .create( 3511 S.getNullabilityKeyword( 3512 *inferNullability), 3513 SourceRange(pointerLoc), 3514 nullptr, SourceLocation(), 3515 nullptr, 0, syntax); 3516 3517 spliceAttrIntoList(*nullabilityAttr, attrs); 3518 3519 if (inferNullabilityCS) { 3520 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() 3521 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); 3522 } 3523 3524 if (inferNullabilityInnerOnly) 3525 inferNullabilityInnerOnlyComplete = true; 3526 return nullabilityAttr; 3527 } 3528 3529 // If we're supposed to complain about missing nullability, do so 3530 // now if it's truly missing. 3531 switch (complainAboutMissingNullability) { 3532 case CAMN_No: 3533 break; 3534 3535 case CAMN_InnerPointers: 3536 if (NumPointersRemaining == 0) 3537 break; 3538 // Fallthrough. 3539 3540 case CAMN_Yes: 3541 checkNullabilityConsistency(state, pointerKind, pointerLoc); 3542 } 3543 return nullptr; 3544 }; 3545 3546 // If the type itself could have nullability but does not, infer pointer 3547 // nullability and perform consistency checking. 3548 if (T->canHaveNullability() && S.ActiveTemplateInstantiations.empty() && 3549 !T->getNullability(S.Context)) { 3550 SimplePointerKind pointerKind = SimplePointerKind::Pointer; 3551 if (T->isBlockPointerType()) 3552 pointerKind = SimplePointerKind::BlockPointer; 3553 else if (T->isMemberPointerType()) 3554 pointerKind = SimplePointerKind::MemberPointer; 3555 3556 if (auto *attr = inferPointerNullability( 3557 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), 3558 D.getMutableDeclSpec().getAttributes().getListRef())) { 3559 T = Context.getAttributedType( 3560 AttributedType::getNullabilityAttrKind(*inferNullability), T, T); 3561 attr->setUsedAsTypeAttr(); 3562 } 3563 } 3564 3565 // Walk the DeclTypeInfo, building the recursive type as we go. 3566 // DeclTypeInfos are ordered from the identifier out, which is 3567 // opposite of what we want :). 3568 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3569 unsigned chunkIndex = e - i - 1; 3570 state.setCurrentChunkIndex(chunkIndex); 3571 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 3572 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; 3573 switch (DeclType.Kind) { 3574 case DeclaratorChunk::Paren: 3575 T = S.BuildParenType(T); 3576 break; 3577 case DeclaratorChunk::BlockPointer: 3578 // If blocks are disabled, emit an error. 3579 if (!LangOpts.Blocks) 3580 S.Diag(DeclType.Loc, diag::err_blocks_disable); 3581 3582 // Handle pointer nullability. 3583 inferPointerNullability(SimplePointerKind::BlockPointer, 3584 DeclType.Loc, DeclType.getAttrListRef()); 3585 3586 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 3587 if (DeclType.Cls.TypeQuals) 3588 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 3589 break; 3590 case DeclaratorChunk::Pointer: 3591 // Verify that we're not building a pointer to pointer to function with 3592 // exception specification. 3593 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 3594 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 3595 D.setInvalidType(true); 3596 // Build the type anyway. 3597 } 3598 3599 // Handle pointer nullability 3600 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, 3601 DeclType.getAttrListRef()); 3602 3603 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) { 3604 T = Context.getObjCObjectPointerType(T); 3605 if (DeclType.Ptr.TypeQuals) 3606 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 3607 break; 3608 } 3609 T = S.BuildPointerType(T, DeclType.Loc, Name); 3610 if (DeclType.Ptr.TypeQuals) 3611 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 3612 3613 break; 3614 case DeclaratorChunk::Reference: { 3615 // Verify that we're not building a reference to pointer to function with 3616 // exception specification. 3617 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 3618 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 3619 D.setInvalidType(true); 3620 // Build the type anyway. 3621 } 3622 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 3623 3624 if (DeclType.Ref.HasRestrict) 3625 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 3626 break; 3627 } 3628 case DeclaratorChunk::Array: { 3629 // Verify that we're not building an array of pointers to function with 3630 // exception specification. 3631 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 3632 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 3633 D.setInvalidType(true); 3634 // Build the type anyway. 3635 } 3636 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 3637 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 3638 ArrayType::ArraySizeModifier ASM; 3639 if (ATI.isStar) 3640 ASM = ArrayType::Star; 3641 else if (ATI.hasStatic) 3642 ASM = ArrayType::Static; 3643 else 3644 ASM = ArrayType::Normal; 3645 if (ASM == ArrayType::Star && !D.isPrototypeContext()) { 3646 // FIXME: This check isn't quite right: it allows star in prototypes 3647 // for function definitions, and disallows some edge cases detailed 3648 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 3649 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 3650 ASM = ArrayType::Normal; 3651 D.setInvalidType(true); 3652 } 3653 3654 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static 3655 // shall appear only in a declaration of a function parameter with an 3656 // array type, ... 3657 if (ASM == ArrayType::Static || ATI.TypeQuals) { 3658 if (!(D.isPrototypeContext() || 3659 D.getContext() == Declarator::KNRTypeListContext)) { 3660 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << 3661 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 3662 // Remove the 'static' and the type qualifiers. 3663 if (ASM == ArrayType::Static) 3664 ASM = ArrayType::Normal; 3665 ATI.TypeQuals = 0; 3666 D.setInvalidType(true); 3667 } 3668 3669 // C99 6.7.5.2p1: ... and then only in the outermost array type 3670 // derivation. 3671 unsigned x = chunkIndex; 3672 while (x != 0) { 3673 // Walk outwards along the declarator chunks. 3674 x--; 3675 const DeclaratorChunk &DC = D.getTypeObject(x); 3676 switch (DC.Kind) { 3677 case DeclaratorChunk::Paren: 3678 continue; 3679 case DeclaratorChunk::Array: 3680 case DeclaratorChunk::Pointer: 3681 case DeclaratorChunk::Reference: 3682 case DeclaratorChunk::MemberPointer: 3683 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << 3684 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 3685 if (ASM == ArrayType::Static) 3686 ASM = ArrayType::Normal; 3687 ATI.TypeQuals = 0; 3688 D.setInvalidType(true); 3689 break; 3690 case DeclaratorChunk::Function: 3691 case DeclaratorChunk::BlockPointer: 3692 // These are invalid anyway, so just ignore. 3693 break; 3694 } 3695 } 3696 } 3697 const AutoType *AT = T->getContainedAutoType(); 3698 // Allow arrays of auto if we are a generic lambda parameter. 3699 // i.e. [](auto (&array)[5]) { return array[0]; }; OK 3700 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) { 3701 // We've already diagnosed this for decltype(auto). 3702 if (!AT->isDecltypeAuto()) 3703 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) 3704 << getPrintableNameForEntity(Name) << T; 3705 T = QualType(); 3706 break; 3707 } 3708 3709 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 3710 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 3711 break; 3712 } 3713 case DeclaratorChunk::Function: { 3714 // If the function declarator has a prototype (i.e. it is not () and 3715 // does not have a K&R-style identifier list), then the arguments are part 3716 // of the type, otherwise the argument list is (). 3717 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 3718 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier(); 3719 3720 // Check for auto functions and trailing return type and adjust the 3721 // return type accordingly. 3722 if (!D.isInvalidType()) { 3723 // trailing-return-type is only required if we're declaring a function, 3724 // and not, for instance, a pointer to a function. 3725 if (D.getDeclSpec().containsPlaceholderType() && 3726 !FTI.hasTrailingReturnType() && chunkIndex == 0 && 3727 !S.getLangOpts().CPlusPlus14) { 3728 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 3729 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto 3730 ? diag::err_auto_missing_trailing_return 3731 : diag::err_deduced_return_type); 3732 T = Context.IntTy; 3733 D.setInvalidType(true); 3734 } else if (FTI.hasTrailingReturnType()) { 3735 // T must be exactly 'auto' at this point. See CWG issue 681. 3736 if (isa<ParenType>(T)) { 3737 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 3738 diag::err_trailing_return_in_parens) 3739 << T << D.getDeclSpec().getSourceRange(); 3740 D.setInvalidType(true); 3741 } else if (D.getContext() != Declarator::LambdaExprContext && 3742 (T.hasQualifiers() || !isa<AutoType>(T) || 3743 cast<AutoType>(T)->getKeyword() != AutoTypeKeyword::Auto)) { 3744 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 3745 diag::err_trailing_return_without_auto) 3746 << T << D.getDeclSpec().getSourceRange(); 3747 D.setInvalidType(true); 3748 } 3749 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); 3750 if (T.isNull()) { 3751 // An error occurred parsing the trailing return type. 3752 T = Context.IntTy; 3753 D.setInvalidType(true); 3754 } 3755 } 3756 } 3757 3758 // C99 6.7.5.3p1: The return type may not be a function or array type. 3759 // For conversion functions, we'll diagnose this particular error later. 3760 if ((T->isArrayType() || T->isFunctionType()) && 3761 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 3762 unsigned diagID = diag::err_func_returning_array_function; 3763 // Last processing chunk in block context means this function chunk 3764 // represents the block. 3765 if (chunkIndex == 0 && 3766 D.getContext() == Declarator::BlockLiteralContext) 3767 diagID = diag::err_block_returning_array_function; 3768 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 3769 T = Context.IntTy; 3770 D.setInvalidType(true); 3771 } 3772 3773 // Do not allow returning half FP value. 3774 // FIXME: This really should be in BuildFunctionType. 3775 if (T->isHalfType()) { 3776 if (S.getLangOpts().OpenCL) { 3777 if (!S.getOpenCLOptions().cl_khr_fp16) { 3778 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T; 3779 D.setInvalidType(true); 3780 } 3781 } else if (!S.getLangOpts().HalfArgsAndReturns) { 3782 S.Diag(D.getIdentifierLoc(), 3783 diag::err_parameters_retval_cannot_have_fp16_type) << 1; 3784 D.setInvalidType(true); 3785 } 3786 } 3787 3788 // Methods cannot return interface types. All ObjC objects are 3789 // passed by reference. 3790 if (T->isObjCObjectType()) { 3791 SourceLocation DiagLoc, FixitLoc; 3792 if (TInfo) { 3793 DiagLoc = TInfo->getTypeLoc().getLocStart(); 3794 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd()); 3795 } else { 3796 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 3797 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd()); 3798 } 3799 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) 3800 << 0 << T 3801 << FixItHint::CreateInsertion(FixitLoc, "*"); 3802 3803 T = Context.getObjCObjectPointerType(T); 3804 if (TInfo) { 3805 TypeLocBuilder TLB; 3806 TLB.pushFullCopy(TInfo->getTypeLoc()); 3807 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); 3808 TLoc.setStarLoc(FixitLoc); 3809 TInfo = TLB.getTypeSourceInfo(Context, T); 3810 } 3811 3812 D.setInvalidType(true); 3813 } 3814 3815 // cv-qualifiers on return types are pointless except when the type is a 3816 // class type in C++. 3817 if ((T.getCVRQualifiers() || T->isAtomicType()) && 3818 !(S.getLangOpts().CPlusPlus && 3819 (T->isDependentType() || T->isRecordType()))) { 3820 if (T->isVoidType() && !S.getLangOpts().CPlusPlus && 3821 D.getFunctionDefinitionKind() == FDK_Definition) { 3822 // [6.9.1/3] qualified void return is invalid on a C 3823 // function definition. Apparently ok on declarations and 3824 // in C++ though (!) 3825 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; 3826 } else 3827 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); 3828 } 3829 3830 // Objective-C ARC ownership qualifiers are ignored on the function 3831 // return type (by type canonicalization). Complain if this attribute 3832 // was written here. 3833 if (T.getQualifiers().hasObjCLifetime()) { 3834 SourceLocation AttrLoc; 3835 if (chunkIndex + 1 < D.getNumTypeObjects()) { 3836 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 3837 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs(); 3838 Attr; Attr = Attr->getNext()) { 3839 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 3840 AttrLoc = Attr->getLoc(); 3841 break; 3842 } 3843 } 3844 } 3845 if (AttrLoc.isInvalid()) { 3846 for (const AttributeList *Attr 3847 = D.getDeclSpec().getAttributes().getList(); 3848 Attr; Attr = Attr->getNext()) { 3849 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 3850 AttrLoc = Attr->getLoc(); 3851 break; 3852 } 3853 } 3854 } 3855 3856 if (AttrLoc.isValid()) { 3857 // The ownership attributes are almost always written via 3858 // the predefined 3859 // __strong/__weak/__autoreleasing/__unsafe_unretained. 3860 if (AttrLoc.isMacroID()) 3861 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first; 3862 3863 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 3864 << T.getQualifiers().getObjCLifetime(); 3865 } 3866 } 3867 3868 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { 3869 // C++ [dcl.fct]p6: 3870 // Types shall not be defined in return or parameter types. 3871 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 3872 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 3873 << Context.getTypeDeclType(Tag); 3874 } 3875 3876 // Exception specs are not allowed in typedefs. Complain, but add it 3877 // anyway. 3878 if (IsTypedefName && FTI.getExceptionSpecType()) 3879 S.Diag(FTI.getExceptionSpecLocBeg(), 3880 diag::err_exception_spec_in_typedef) 3881 << (D.getContext() == Declarator::AliasDeclContext || 3882 D.getContext() == Declarator::AliasTemplateContext); 3883 3884 // If we see "T var();" or "T var(T());" at block scope, it is probably 3885 // an attempt to initialize a variable, not a function declaration. 3886 if (FTI.isAmbiguous) 3887 warnAboutAmbiguousFunction(S, D, DeclType, T); 3888 3889 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex)); 3890 3891 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) { 3892 // Simple void foo(), where the incoming T is the result type. 3893 T = Context.getFunctionNoProtoType(T, EI); 3894 } else { 3895 // We allow a zero-parameter variadic function in C if the 3896 // function is marked with the "overloadable" attribute. Scan 3897 // for this attribute now. 3898 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) { 3899 bool Overloadable = false; 3900 for (const AttributeList *Attrs = D.getAttributes(); 3901 Attrs; Attrs = Attrs->getNext()) { 3902 if (Attrs->getKind() == AttributeList::AT_Overloadable) { 3903 Overloadable = true; 3904 break; 3905 } 3906 } 3907 3908 if (!Overloadable) 3909 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); 3910 } 3911 3912 if (FTI.NumParams && FTI.Params[0].Param == nullptr) { 3913 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 3914 // definition. 3915 S.Diag(FTI.Params[0].IdentLoc, 3916 diag::err_ident_list_in_fn_declaration); 3917 D.setInvalidType(true); 3918 // Recover by creating a K&R-style function type. 3919 T = Context.getFunctionNoProtoType(T, EI); 3920 break; 3921 } 3922 3923 FunctionProtoType::ExtProtoInfo EPI; 3924 EPI.ExtInfo = EI; 3925 EPI.Variadic = FTI.isVariadic; 3926 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 3927 EPI.TypeQuals = FTI.TypeQuals; 3928 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 3929 : FTI.RefQualifierIsLValueRef? RQ_LValue 3930 : RQ_RValue; 3931 3932 // Otherwise, we have a function with a parameter list that is 3933 // potentially variadic. 3934 SmallVector<QualType, 16> ParamTys; 3935 ParamTys.reserve(FTI.NumParams); 3936 3937 SmallVector<bool, 16> ConsumedParameters; 3938 ConsumedParameters.reserve(FTI.NumParams); 3939 bool HasAnyConsumedParameters = false; 3940 3941 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 3942 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 3943 QualType ParamTy = Param->getType(); 3944 assert(!ParamTy.isNull() && "Couldn't parse type?"); 3945 3946 // Look for 'void'. void is allowed only as a single parameter to a 3947 // function with no other parameters (C99 6.7.5.3p10). We record 3948 // int(void) as a FunctionProtoType with an empty parameter list. 3949 if (ParamTy->isVoidType()) { 3950 // If this is something like 'float(int, void)', reject it. 'void' 3951 // is an incomplete type (C99 6.2.5p19) and function decls cannot 3952 // have parameters of incomplete type. 3953 if (FTI.NumParams != 1 || FTI.isVariadic) { 3954 S.Diag(DeclType.Loc, diag::err_void_only_param); 3955 ParamTy = Context.IntTy; 3956 Param->setType(ParamTy); 3957 } else if (FTI.Params[i].Ident) { 3958 // Reject, but continue to parse 'int(void abc)'. 3959 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); 3960 ParamTy = Context.IntTy; 3961 Param->setType(ParamTy); 3962 } else { 3963 // Reject, but continue to parse 'float(const void)'. 3964 if (ParamTy.hasQualifiers()) 3965 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 3966 3967 // Do not add 'void' to the list. 3968 break; 3969 } 3970 } else if (ParamTy->isHalfType()) { 3971 // Disallow half FP parameters. 3972 // FIXME: This really should be in BuildFunctionType. 3973 if (S.getLangOpts().OpenCL) { 3974 if (!S.getOpenCLOptions().cl_khr_fp16) { 3975 S.Diag(Param->getLocation(), 3976 diag::err_opencl_half_param) << ParamTy; 3977 D.setInvalidType(); 3978 Param->setInvalidDecl(); 3979 } 3980 } else if (!S.getLangOpts().HalfArgsAndReturns) { 3981 S.Diag(Param->getLocation(), 3982 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 3983 D.setInvalidType(); 3984 } 3985 } else if (!FTI.hasPrototype) { 3986 if (ParamTy->isPromotableIntegerType()) { 3987 ParamTy = Context.getPromotedIntegerType(ParamTy); 3988 Param->setKNRPromoted(true); 3989 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { 3990 if (BTy->getKind() == BuiltinType::Float) { 3991 ParamTy = Context.DoubleTy; 3992 Param->setKNRPromoted(true); 3993 } 3994 } 3995 } 3996 3997 if (LangOpts.ObjCAutoRefCount) { 3998 bool Consumed = Param->hasAttr<NSConsumedAttr>(); 3999 ConsumedParameters.push_back(Consumed); 4000 HasAnyConsumedParameters |= Consumed; 4001 } 4002 4003 ParamTys.push_back(ParamTy); 4004 } 4005 4006 if (HasAnyConsumedParameters) 4007 EPI.ConsumedParameters = ConsumedParameters.data(); 4008 4009 SmallVector<QualType, 4> Exceptions; 4010 SmallVector<ParsedType, 2> DynamicExceptions; 4011 SmallVector<SourceRange, 2> DynamicExceptionRanges; 4012 Expr *NoexceptExpr = nullptr; 4013 4014 if (FTI.getExceptionSpecType() == EST_Dynamic) { 4015 // FIXME: It's rather inefficient to have to split into two vectors 4016 // here. 4017 unsigned N = FTI.NumExceptions; 4018 DynamicExceptions.reserve(N); 4019 DynamicExceptionRanges.reserve(N); 4020 for (unsigned I = 0; I != N; ++I) { 4021 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 4022 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 4023 } 4024 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 4025 NoexceptExpr = FTI.NoexceptExpr; 4026 } 4027 4028 S.checkExceptionSpecification(D.isFunctionDeclarationContext(), 4029 FTI.getExceptionSpecType(), 4030 DynamicExceptions, 4031 DynamicExceptionRanges, 4032 NoexceptExpr, 4033 Exceptions, 4034 EPI.ExceptionSpec); 4035 4036 T = Context.getFunctionType(T, ParamTys, EPI); 4037 } 4038 4039 break; 4040 } 4041 case DeclaratorChunk::MemberPointer: 4042 // The scope spec must refer to a class, or be dependent. 4043 CXXScopeSpec &SS = DeclType.Mem.Scope(); 4044 QualType ClsType; 4045 4046 // Handle pointer nullability. 4047 inferPointerNullability(SimplePointerKind::MemberPointer, 4048 DeclType.Loc, DeclType.getAttrListRef()); 4049 4050 if (SS.isInvalid()) { 4051 // Avoid emitting extra errors if we already errored on the scope. 4052 D.setInvalidType(true); 4053 } else if (S.isDependentScopeSpecifier(SS) || 4054 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 4055 NestedNameSpecifier *NNS = SS.getScopeRep(); 4056 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 4057 switch (NNS->getKind()) { 4058 case NestedNameSpecifier::Identifier: 4059 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 4060 NNS->getAsIdentifier()); 4061 break; 4062 4063 case NestedNameSpecifier::Namespace: 4064 case NestedNameSpecifier::NamespaceAlias: 4065 case NestedNameSpecifier::Global: 4066 case NestedNameSpecifier::Super: 4067 llvm_unreachable("Nested-name-specifier must name a type"); 4068 4069 case NestedNameSpecifier::TypeSpec: 4070 case NestedNameSpecifier::TypeSpecWithTemplate: 4071 ClsType = QualType(NNS->getAsType(), 0); 4072 // Note: if the NNS has a prefix and ClsType is a nondependent 4073 // TemplateSpecializationType, then the NNS prefix is NOT included 4074 // in ClsType; hence we wrap ClsType into an ElaboratedType. 4075 // NOTE: in particular, no wrap occurs if ClsType already is an 4076 // Elaborated, DependentName, or DependentTemplateSpecialization. 4077 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 4078 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 4079 break; 4080 } 4081 } else { 4082 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 4083 diag::err_illegal_decl_mempointer_in_nonclass) 4084 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 4085 << DeclType.Mem.Scope().getRange(); 4086 D.setInvalidType(true); 4087 } 4088 4089 if (!ClsType.isNull()) 4090 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, 4091 D.getIdentifier()); 4092 if (T.isNull()) { 4093 T = Context.IntTy; 4094 D.setInvalidType(true); 4095 } else if (DeclType.Mem.TypeQuals) { 4096 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 4097 } 4098 break; 4099 } 4100 4101 if (T.isNull()) { 4102 D.setInvalidType(true); 4103 T = Context.IntTy; 4104 } 4105 4106 // See if there are any attributes on this declarator chunk. 4107 processTypeAttrs(state, T, TAL_DeclChunk, 4108 const_cast<AttributeList *>(DeclType.getAttrs())); 4109 } 4110 4111 assert(!T.isNull() && "T must not be null after this point"); 4112 4113 if (LangOpts.CPlusPlus && T->isFunctionType()) { 4114 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 4115 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 4116 4117 // C++ 8.3.5p4: 4118 // A cv-qualifier-seq shall only be part of the function type 4119 // for a nonstatic member function, the function type to which a pointer 4120 // to member refers, or the top-level function type of a function typedef 4121 // declaration. 4122 // 4123 // Core issue 547 also allows cv-qualifiers on function types that are 4124 // top-level template type arguments. 4125 bool FreeFunction; 4126 if (!D.getCXXScopeSpec().isSet()) { 4127 FreeFunction = ((D.getContext() != Declarator::MemberContext && 4128 D.getContext() != Declarator::LambdaExprContext) || 4129 D.getDeclSpec().isFriendSpecified()); 4130 } else { 4131 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 4132 FreeFunction = (DC && !DC->isRecord()); 4133 } 4134 4135 // C++11 [dcl.fct]p6 (w/DR1417): 4136 // An attempt to specify a function type with a cv-qualifier-seq or a 4137 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 4138 // - the function type for a non-static member function, 4139 // - the function type to which a pointer to member refers, 4140 // - the top-level function type of a function typedef declaration or 4141 // alias-declaration, 4142 // - the type-id in the default argument of a type-parameter, or 4143 // - the type-id of a template-argument for a type-parameter 4144 // 4145 // FIXME: Checking this here is insufficient. We accept-invalid on: 4146 // 4147 // template<typename T> struct S { void f(T); }; 4148 // S<int() const> s; 4149 // 4150 // ... for instance. 4151 if (IsQualifiedFunction && 4152 !(!FreeFunction && 4153 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 4154 !IsTypedefName && 4155 D.getContext() != Declarator::TemplateTypeArgContext) { 4156 SourceLocation Loc = D.getLocStart(); 4157 SourceRange RemovalRange; 4158 unsigned I; 4159 if (D.isFunctionDeclarator(I)) { 4160 SmallVector<SourceLocation, 4> RemovalLocs; 4161 const DeclaratorChunk &Chunk = D.getTypeObject(I); 4162 assert(Chunk.Kind == DeclaratorChunk::Function); 4163 if (Chunk.Fun.hasRefQualifier()) 4164 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 4165 if (Chunk.Fun.TypeQuals & Qualifiers::Const) 4166 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); 4167 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) 4168 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); 4169 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) 4170 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); 4171 if (!RemovalLocs.empty()) { 4172 std::sort(RemovalLocs.begin(), RemovalLocs.end(), 4173 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 4174 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 4175 Loc = RemovalLocs.front(); 4176 } 4177 } 4178 4179 S.Diag(Loc, diag::err_invalid_qualified_function_type) 4180 << FreeFunction << D.isFunctionDeclarator() << T 4181 << getFunctionQualifiersAsString(FnTy) 4182 << FixItHint::CreateRemoval(RemovalRange); 4183 4184 // Strip the cv-qualifiers and ref-qualifiers from the type. 4185 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 4186 EPI.TypeQuals = 0; 4187 EPI.RefQualifier = RQ_None; 4188 4189 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), 4190 EPI); 4191 // Rebuild any parens around the identifier in the function type. 4192 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4193 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 4194 break; 4195 T = S.BuildParenType(T); 4196 } 4197 } 4198 } 4199 4200 // Apply any undistributed attributes from the declarator. 4201 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); 4202 4203 // Diagnose any ignored type attributes. 4204 state.diagnoseIgnoredTypeAttrs(T); 4205 4206 // C++0x [dcl.constexpr]p9: 4207 // A constexpr specifier used in an object declaration declares the object 4208 // as const. 4209 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 4210 T.addConst(); 4211 } 4212 4213 // If there was an ellipsis in the declarator, the declaration declares a 4214 // parameter pack whose type may be a pack expansion type. 4215 if (D.hasEllipsis()) { 4216 // C++0x [dcl.fct]p13: 4217 // A declarator-id or abstract-declarator containing an ellipsis shall 4218 // only be used in a parameter-declaration. Such a parameter-declaration 4219 // is a parameter pack (14.5.3). [...] 4220 switch (D.getContext()) { 4221 case Declarator::PrototypeContext: 4222 case Declarator::LambdaExprParameterContext: 4223 // C++0x [dcl.fct]p13: 4224 // [...] When it is part of a parameter-declaration-clause, the 4225 // parameter pack is a function parameter pack (14.5.3). The type T 4226 // of the declarator-id of the function parameter pack shall contain 4227 // a template parameter pack; each template parameter pack in T is 4228 // expanded by the function parameter pack. 4229 // 4230 // We represent function parameter packs as function parameters whose 4231 // type is a pack expansion. 4232 if (!T->containsUnexpandedParameterPack()) { 4233 S.Diag(D.getEllipsisLoc(), 4234 diag::err_function_parameter_pack_without_parameter_packs) 4235 << T << D.getSourceRange(); 4236 D.setEllipsisLoc(SourceLocation()); 4237 } else { 4238 T = Context.getPackExpansionType(T, None); 4239 } 4240 break; 4241 case Declarator::TemplateParamContext: 4242 // C++0x [temp.param]p15: 4243 // If a template-parameter is a [...] is a parameter-declaration that 4244 // declares a parameter pack (8.3.5), then the template-parameter is a 4245 // template parameter pack (14.5.3). 4246 // 4247 // Note: core issue 778 clarifies that, if there are any unexpanded 4248 // parameter packs in the type of the non-type template parameter, then 4249 // it expands those parameter packs. 4250 if (T->containsUnexpandedParameterPack()) 4251 T = Context.getPackExpansionType(T, None); 4252 else 4253 S.Diag(D.getEllipsisLoc(), 4254 LangOpts.CPlusPlus11 4255 ? diag::warn_cxx98_compat_variadic_templates 4256 : diag::ext_variadic_templates); 4257 break; 4258 4259 case Declarator::FileContext: 4260 case Declarator::KNRTypeListContext: 4261 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here? 4262 case Declarator::ObjCResultContext: // FIXME: special diagnostic here? 4263 case Declarator::TypeNameContext: 4264 case Declarator::CXXNewContext: 4265 case Declarator::AliasDeclContext: 4266 case Declarator::AliasTemplateContext: 4267 case Declarator::MemberContext: 4268 case Declarator::BlockContext: 4269 case Declarator::ForContext: 4270 case Declarator::ConditionContext: 4271 case Declarator::CXXCatchContext: 4272 case Declarator::ObjCCatchContext: 4273 case Declarator::BlockLiteralContext: 4274 case Declarator::LambdaExprContext: 4275 case Declarator::ConversionIdContext: 4276 case Declarator::TrailingReturnContext: 4277 case Declarator::TemplateTypeArgContext: 4278 // FIXME: We may want to allow parameter packs in block-literal contexts 4279 // in the future. 4280 S.Diag(D.getEllipsisLoc(), 4281 diag::err_ellipsis_in_declarator_not_parameter); 4282 D.setEllipsisLoc(SourceLocation()); 4283 break; 4284 } 4285 } 4286 4287 assert(!T.isNull() && "T must not be null at the end of this function"); 4288 if (D.isInvalidType()) 4289 return Context.getTrivialTypeSourceInfo(T); 4290 4291 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); 4292 } 4293 4294 /// GetTypeForDeclarator - Convert the type for the specified 4295 /// declarator to Type instances. 4296 /// 4297 /// The result of this call will never be null, but the associated 4298 /// type may be a null type if there's an unrecoverable error. 4299 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 4300 // Determine the type of the declarator. Not all forms of declarator 4301 // have a type. 4302 4303 TypeProcessingState state(*this, D); 4304 4305 TypeSourceInfo *ReturnTypeInfo = nullptr; 4306 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 4307 4308 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 4309 inferARCWriteback(state, T); 4310 4311 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 4312 } 4313 4314 static void transferARCOwnershipToDeclSpec(Sema &S, 4315 QualType &declSpecTy, 4316 Qualifiers::ObjCLifetime ownership) { 4317 if (declSpecTy->isObjCRetainableType() && 4318 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 4319 Qualifiers qs; 4320 qs.addObjCLifetime(ownership); 4321 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 4322 } 4323 } 4324 4325 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 4326 Qualifiers::ObjCLifetime ownership, 4327 unsigned chunkIndex) { 4328 Sema &S = state.getSema(); 4329 Declarator &D = state.getDeclarator(); 4330 4331 // Look for an explicit lifetime attribute. 4332 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 4333 for (const AttributeList *attr = chunk.getAttrs(); attr; 4334 attr = attr->getNext()) 4335 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 4336 return; 4337 4338 const char *attrStr = nullptr; 4339 switch (ownership) { 4340 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 4341 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 4342 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 4343 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 4344 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 4345 } 4346 4347 IdentifierLoc *Arg = new (S.Context) IdentifierLoc; 4348 Arg->Ident = &S.Context.Idents.get(attrStr); 4349 Arg->Loc = SourceLocation(); 4350 4351 ArgsUnion Args(Arg); 4352 4353 // If there wasn't one, add one (with an invalid source location 4354 // so that we don't make an AttributedType for it). 4355 AttributeList *attr = D.getAttributePool() 4356 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), 4357 /*scope*/ nullptr, SourceLocation(), 4358 /*args*/ &Args, 1, AttributeList::AS_GNU); 4359 spliceAttrIntoList(*attr, chunk.getAttrListRef()); 4360 4361 // TODO: mark whether we did this inference? 4362 } 4363 4364 /// \brief Used for transferring ownership in casts resulting in l-values. 4365 static void transferARCOwnership(TypeProcessingState &state, 4366 QualType &declSpecTy, 4367 Qualifiers::ObjCLifetime ownership) { 4368 Sema &S = state.getSema(); 4369 Declarator &D = state.getDeclarator(); 4370 4371 int inner = -1; 4372 bool hasIndirection = false; 4373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4374 DeclaratorChunk &chunk = D.getTypeObject(i); 4375 switch (chunk.Kind) { 4376 case DeclaratorChunk::Paren: 4377 // Ignore parens. 4378 break; 4379 4380 case DeclaratorChunk::Array: 4381 case DeclaratorChunk::Reference: 4382 case DeclaratorChunk::Pointer: 4383 if (inner != -1) 4384 hasIndirection = true; 4385 inner = i; 4386 break; 4387 4388 case DeclaratorChunk::BlockPointer: 4389 if (inner != -1) 4390 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 4391 return; 4392 4393 case DeclaratorChunk::Function: 4394 case DeclaratorChunk::MemberPointer: 4395 return; 4396 } 4397 } 4398 4399 if (inner == -1) 4400 return; 4401 4402 DeclaratorChunk &chunk = D.getTypeObject(inner); 4403 if (chunk.Kind == DeclaratorChunk::Pointer) { 4404 if (declSpecTy->isObjCRetainableType()) 4405 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 4406 if (declSpecTy->isObjCObjectType() && hasIndirection) 4407 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 4408 } else { 4409 assert(chunk.Kind == DeclaratorChunk::Array || 4410 chunk.Kind == DeclaratorChunk::Reference); 4411 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 4412 } 4413 } 4414 4415 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 4416 TypeProcessingState state(*this, D); 4417 4418 TypeSourceInfo *ReturnTypeInfo = nullptr; 4419 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 4420 4421 if (getLangOpts().ObjC1) { 4422 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 4423 if (ownership != Qualifiers::OCL_None) 4424 transferARCOwnership(state, declSpecTy, ownership); 4425 } 4426 4427 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 4428 } 4429 4430 /// Map an AttributedType::Kind to an AttributeList::Kind. 4431 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 4432 switch (kind) { 4433 case AttributedType::attr_address_space: 4434 return AttributeList::AT_AddressSpace; 4435 case AttributedType::attr_regparm: 4436 return AttributeList::AT_Regparm; 4437 case AttributedType::attr_vector_size: 4438 return AttributeList::AT_VectorSize; 4439 case AttributedType::attr_neon_vector_type: 4440 return AttributeList::AT_NeonVectorType; 4441 case AttributedType::attr_neon_polyvector_type: 4442 return AttributeList::AT_NeonPolyVectorType; 4443 case AttributedType::attr_objc_gc: 4444 return AttributeList::AT_ObjCGC; 4445 case AttributedType::attr_objc_ownership: 4446 case AttributedType::attr_objc_inert_unsafe_unretained: 4447 return AttributeList::AT_ObjCOwnership; 4448 case AttributedType::attr_noreturn: 4449 return AttributeList::AT_NoReturn; 4450 case AttributedType::attr_cdecl: 4451 return AttributeList::AT_CDecl; 4452 case AttributedType::attr_fastcall: 4453 return AttributeList::AT_FastCall; 4454 case AttributedType::attr_stdcall: 4455 return AttributeList::AT_StdCall; 4456 case AttributedType::attr_thiscall: 4457 return AttributeList::AT_ThisCall; 4458 case AttributedType::attr_pascal: 4459 return AttributeList::AT_Pascal; 4460 case AttributedType::attr_vectorcall: 4461 return AttributeList::AT_VectorCall; 4462 case AttributedType::attr_pcs: 4463 case AttributedType::attr_pcs_vfp: 4464 return AttributeList::AT_Pcs; 4465 case AttributedType::attr_inteloclbicc: 4466 return AttributeList::AT_IntelOclBicc; 4467 case AttributedType::attr_ms_abi: 4468 return AttributeList::AT_MSABI; 4469 case AttributedType::attr_sysv_abi: 4470 return AttributeList::AT_SysVABI; 4471 case AttributedType::attr_ptr32: 4472 return AttributeList::AT_Ptr32; 4473 case AttributedType::attr_ptr64: 4474 return AttributeList::AT_Ptr64; 4475 case AttributedType::attr_sptr: 4476 return AttributeList::AT_SPtr; 4477 case AttributedType::attr_uptr: 4478 return AttributeList::AT_UPtr; 4479 case AttributedType::attr_nonnull: 4480 return AttributeList::AT_TypeNonNull; 4481 case AttributedType::attr_nullable: 4482 return AttributeList::AT_TypeNullable; 4483 case AttributedType::attr_null_unspecified: 4484 return AttributeList::AT_TypeNullUnspecified; 4485 case AttributedType::attr_objc_kindof: 4486 return AttributeList::AT_ObjCKindOf; 4487 } 4488 llvm_unreachable("unexpected attribute kind!"); 4489 } 4490 4491 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 4492 const AttributeList *attrs, 4493 const AttributeList *DeclAttrs = nullptr) { 4494 // DeclAttrs and attrs cannot be both empty. 4495 assert((attrs || DeclAttrs) && 4496 "no type attributes in the expected location!"); 4497 4498 AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind()); 4499 // Try to search for an attribute of matching kind in attrs list. 4500 while (attrs && attrs->getKind() != parsedKind) 4501 attrs = attrs->getNext(); 4502 if (!attrs) { 4503 // No matching type attribute in attrs list found. 4504 // Try searching through C++11 attributes in the declarator attribute list. 4505 while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() || 4506 DeclAttrs->getKind() != parsedKind)) 4507 DeclAttrs = DeclAttrs->getNext(); 4508 attrs = DeclAttrs; 4509 } 4510 4511 assert(attrs && "no matching type attribute in expected location!"); 4512 4513 TL.setAttrNameLoc(attrs->getLoc()); 4514 if (TL.hasAttrExprOperand()) { 4515 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind"); 4516 TL.setAttrExprOperand(attrs->getArgAsExpr(0)); 4517 } else if (TL.hasAttrEnumOperand()) { 4518 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) && 4519 "unexpected attribute operand kind"); 4520 if (attrs->isArgIdent(0)) 4521 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc); 4522 else 4523 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc()); 4524 } 4525 4526 // FIXME: preserve this information to here. 4527 if (TL.hasAttrOperand()) 4528 TL.setAttrOperandParensRange(SourceRange()); 4529 } 4530 4531 namespace { 4532 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 4533 ASTContext &Context; 4534 const DeclSpec &DS; 4535 4536 public: 4537 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 4538 : Context(Context), DS(DS) {} 4539 4540 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 4541 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 4542 Visit(TL.getModifiedLoc()); 4543 } 4544 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 4545 Visit(TL.getUnqualifiedLoc()); 4546 } 4547 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 4548 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 4549 } 4550 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 4551 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 4552 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 4553 // addition field. What we have is good enough for dispay of location 4554 // of 'fixit' on interface name. 4555 TL.setNameEndLoc(DS.getLocEnd()); 4556 } 4557 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 4558 TypeSourceInfo *RepTInfo = nullptr; 4559 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 4560 TL.copy(RepTInfo->getTypeLoc()); 4561 } 4562 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 4563 TypeSourceInfo *RepTInfo = nullptr; 4564 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); 4565 TL.copy(RepTInfo->getTypeLoc()); 4566 } 4567 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 4568 TypeSourceInfo *TInfo = nullptr; 4569 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4570 4571 // If we got no declarator info from previous Sema routines, 4572 // just fill with the typespec loc. 4573 if (!TInfo) { 4574 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 4575 return; 4576 } 4577 4578 TypeLoc OldTL = TInfo->getTypeLoc(); 4579 if (TInfo->getType()->getAs<ElaboratedType>()) { 4580 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 4581 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 4582 .castAs<TemplateSpecializationTypeLoc>(); 4583 TL.copy(NamedTL); 4584 } else { 4585 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 4586 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); 4587 } 4588 4589 } 4590 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 4591 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 4592 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 4593 TL.setParensRange(DS.getTypeofParensRange()); 4594 } 4595 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 4596 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 4597 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 4598 TL.setParensRange(DS.getTypeofParensRange()); 4599 assert(DS.getRepAsType()); 4600 TypeSourceInfo *TInfo = nullptr; 4601 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4602 TL.setUnderlyingTInfo(TInfo); 4603 } 4604 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 4605 // FIXME: This holds only because we only have one unary transform. 4606 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 4607 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 4608 TL.setParensRange(DS.getTypeofParensRange()); 4609 assert(DS.getRepAsType()); 4610 TypeSourceInfo *TInfo = nullptr; 4611 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4612 TL.setUnderlyingTInfo(TInfo); 4613 } 4614 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 4615 // By default, use the source location of the type specifier. 4616 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 4617 if (TL.needsExtraLocalData()) { 4618 // Set info for the written builtin specifiers. 4619 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 4620 // Try to have a meaningful source location. 4621 if (TL.getWrittenSignSpec() != TSS_unspecified) 4622 // Sign spec loc overrides the others (e.g., 'unsigned long'). 4623 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 4624 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 4625 // Width spec loc overrides type spec loc (e.g., 'short int'). 4626 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 4627 } 4628 } 4629 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 4630 ElaboratedTypeKeyword Keyword 4631 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 4632 if (DS.getTypeSpecType() == TST_typename) { 4633 TypeSourceInfo *TInfo = nullptr; 4634 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4635 if (TInfo) { 4636 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 4637 return; 4638 } 4639 } 4640 TL.setElaboratedKeywordLoc(Keyword != ETK_None 4641 ? DS.getTypeSpecTypeLoc() 4642 : SourceLocation()); 4643 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 4644 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4645 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 4646 } 4647 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 4648 assert(DS.getTypeSpecType() == TST_typename); 4649 TypeSourceInfo *TInfo = nullptr; 4650 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4651 assert(TInfo); 4652 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 4653 } 4654 void VisitDependentTemplateSpecializationTypeLoc( 4655 DependentTemplateSpecializationTypeLoc TL) { 4656 assert(DS.getTypeSpecType() == TST_typename); 4657 TypeSourceInfo *TInfo = nullptr; 4658 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4659 assert(TInfo); 4660 TL.copy( 4661 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 4662 } 4663 void VisitTagTypeLoc(TagTypeLoc TL) { 4664 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 4665 } 4666 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 4667 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 4668 // or an _Atomic qualifier. 4669 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 4670 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 4671 TL.setParensRange(DS.getTypeofParensRange()); 4672 4673 TypeSourceInfo *TInfo = nullptr; 4674 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 4675 assert(TInfo); 4676 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 4677 } else { 4678 TL.setKWLoc(DS.getAtomicSpecLoc()); 4679 // No parens, to indicate this was spelled as an _Atomic qualifier. 4680 TL.setParensRange(SourceRange()); 4681 Visit(TL.getValueLoc()); 4682 } 4683 } 4684 4685 void VisitTypeLoc(TypeLoc TL) { 4686 // FIXME: add other typespec types and change this to an assert. 4687 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 4688 } 4689 }; 4690 4691 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 4692 ASTContext &Context; 4693 const DeclaratorChunk &Chunk; 4694 4695 public: 4696 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 4697 : Context(Context), Chunk(Chunk) {} 4698 4699 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 4700 llvm_unreachable("qualified type locs not expected here!"); 4701 } 4702 void VisitDecayedTypeLoc(DecayedTypeLoc TL) { 4703 llvm_unreachable("decayed type locs not expected here!"); 4704 } 4705 4706 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 4707 fillAttributedTypeLoc(TL, Chunk.getAttrs()); 4708 } 4709 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 4710 // nothing 4711 } 4712 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 4713 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 4714 TL.setCaretLoc(Chunk.Loc); 4715 } 4716 void VisitPointerTypeLoc(PointerTypeLoc TL) { 4717 assert(Chunk.Kind == DeclaratorChunk::Pointer); 4718 TL.setStarLoc(Chunk.Loc); 4719 } 4720 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 4721 assert(Chunk.Kind == DeclaratorChunk::Pointer); 4722 TL.setStarLoc(Chunk.Loc); 4723 } 4724 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 4725 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 4726 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 4727 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 4728 4729 const Type* ClsTy = TL.getClass(); 4730 QualType ClsQT = QualType(ClsTy, 0); 4731 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 4732 // Now copy source location info into the type loc component. 4733 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 4734 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 4735 case NestedNameSpecifier::Identifier: 4736 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 4737 { 4738 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 4739 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 4740 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 4741 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 4742 } 4743 break; 4744 4745 case NestedNameSpecifier::TypeSpec: 4746 case NestedNameSpecifier::TypeSpecWithTemplate: 4747 if (isa<ElaboratedType>(ClsTy)) { 4748 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 4749 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 4750 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 4751 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 4752 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 4753 } else { 4754 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 4755 } 4756 break; 4757 4758 case NestedNameSpecifier::Namespace: 4759 case NestedNameSpecifier::NamespaceAlias: 4760 case NestedNameSpecifier::Global: 4761 case NestedNameSpecifier::Super: 4762 llvm_unreachable("Nested-name-specifier must name a type"); 4763 } 4764 4765 // Finally fill in MemberPointerLocInfo fields. 4766 TL.setStarLoc(Chunk.Loc); 4767 TL.setClassTInfo(ClsTInfo); 4768 } 4769 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 4770 assert(Chunk.Kind == DeclaratorChunk::Reference); 4771 // 'Amp' is misleading: this might have been originally 4772 /// spelled with AmpAmp. 4773 TL.setAmpLoc(Chunk.Loc); 4774 } 4775 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 4776 assert(Chunk.Kind == DeclaratorChunk::Reference); 4777 assert(!Chunk.Ref.LValueRef); 4778 TL.setAmpAmpLoc(Chunk.Loc); 4779 } 4780 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 4781 assert(Chunk.Kind == DeclaratorChunk::Array); 4782 TL.setLBracketLoc(Chunk.Loc); 4783 TL.setRBracketLoc(Chunk.EndLoc); 4784 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 4785 } 4786 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 4787 assert(Chunk.Kind == DeclaratorChunk::Function); 4788 TL.setLocalRangeBegin(Chunk.Loc); 4789 TL.setLocalRangeEnd(Chunk.EndLoc); 4790 4791 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 4792 TL.setLParenLoc(FTI.getLParenLoc()); 4793 TL.setRParenLoc(FTI.getRParenLoc()); 4794 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { 4795 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 4796 TL.setParam(tpi++, Param); 4797 } 4798 // FIXME: exception specs 4799 } 4800 void VisitParenTypeLoc(ParenTypeLoc TL) { 4801 assert(Chunk.Kind == DeclaratorChunk::Paren); 4802 TL.setLParenLoc(Chunk.Loc); 4803 TL.setRParenLoc(Chunk.EndLoc); 4804 } 4805 4806 void VisitTypeLoc(TypeLoc TL) { 4807 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 4808 } 4809 }; 4810 } 4811 4812 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 4813 SourceLocation Loc; 4814 switch (Chunk.Kind) { 4815 case DeclaratorChunk::Function: 4816 case DeclaratorChunk::Array: 4817 case DeclaratorChunk::Paren: 4818 llvm_unreachable("cannot be _Atomic qualified"); 4819 4820 case DeclaratorChunk::Pointer: 4821 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); 4822 break; 4823 4824 case DeclaratorChunk::BlockPointer: 4825 case DeclaratorChunk::Reference: 4826 case DeclaratorChunk::MemberPointer: 4827 // FIXME: Provide a source location for the _Atomic keyword. 4828 break; 4829 } 4830 4831 ATL.setKWLoc(Loc); 4832 ATL.setParensRange(SourceRange()); 4833 } 4834 4835 /// \brief Create and instantiate a TypeSourceInfo with type source information. 4836 /// 4837 /// \param T QualType referring to the type as written in source code. 4838 /// 4839 /// \param ReturnTypeInfo For declarators whose return type does not show 4840 /// up in the normal place in the declaration specifiers (such as a C++ 4841 /// conversion function), this pointer will refer to a type source information 4842 /// for that return type. 4843 TypeSourceInfo * 4844 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 4845 TypeSourceInfo *ReturnTypeInfo) { 4846 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 4847 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 4848 const AttributeList *DeclAttrs = D.getAttributes(); 4849 4850 // Handle parameter packs whose type is a pack expansion. 4851 if (isa<PackExpansionType>(T)) { 4852 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 4853 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 4854 } 4855 4856 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 4857 // An AtomicTypeLoc might be produced by an atomic qualifier in this 4858 // declarator chunk. 4859 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 4860 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 4861 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 4862 } 4863 4864 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 4865 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs); 4866 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 4867 } 4868 4869 // FIXME: Ordering here? 4870 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) 4871 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 4872 4873 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 4874 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 4875 } 4876 4877 // If we have different source information for the return type, use 4878 // that. This really only applies to C++ conversion functions. 4879 if (ReturnTypeInfo) { 4880 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 4881 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 4882 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 4883 } else { 4884 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 4885 } 4886 4887 return TInfo; 4888 } 4889 4890 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 4891 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 4892 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 4893 // and Sema during declaration parsing. Try deallocating/caching them when 4894 // it's appropriate, instead of allocating them and keeping them around. 4895 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 4896 TypeAlignment); 4897 new (LocT) LocInfoType(T, TInfo); 4898 assert(LocT->getTypeClass() != T->getTypeClass() && 4899 "LocInfoType's TypeClass conflicts with an existing Type class"); 4900 return ParsedType::make(QualType(LocT, 0)); 4901 } 4902 4903 void LocInfoType::getAsStringInternal(std::string &Str, 4904 const PrintingPolicy &Policy) const { 4905 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 4906 " was used directly instead of getting the QualType through" 4907 " GetTypeFromParser"); 4908 } 4909 4910 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 4911 // C99 6.7.6: Type names have no identifier. This is already validated by 4912 // the parser. 4913 assert(D.getIdentifier() == nullptr && 4914 "Type name should have no identifier!"); 4915 4916 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4917 QualType T = TInfo->getType(); 4918 if (D.isInvalidType()) 4919 return true; 4920 4921 // Make sure there are no unused decl attributes on the declarator. 4922 // We don't want to do this for ObjC parameters because we're going 4923 // to apply them to the actual parameter declaration. 4924 // Likewise, we don't want to do this for alias declarations, because 4925 // we are actually going to build a declaration from this eventually. 4926 if (D.getContext() != Declarator::ObjCParameterContext && 4927 D.getContext() != Declarator::AliasDeclContext && 4928 D.getContext() != Declarator::AliasTemplateContext) 4929 checkUnusedDeclAttributes(D); 4930 4931 if (getLangOpts().CPlusPlus) { 4932 // Check that there are no default arguments (C++ only). 4933 CheckExtraCXXDefaultArguments(D); 4934 } 4935 4936 return CreateParsedType(T, TInfo); 4937 } 4938 4939 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 4940 QualType T = Context.getObjCInstanceType(); 4941 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 4942 return CreateParsedType(T, TInfo); 4943 } 4944 4945 4946 //===----------------------------------------------------------------------===// 4947 // Type Attribute Processing 4948 //===----------------------------------------------------------------------===// 4949 4950 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 4951 /// specified type. The attribute contains 1 argument, the id of the address 4952 /// space for the type. 4953 static void HandleAddressSpaceTypeAttribute(QualType &Type, 4954 const AttributeList &Attr, Sema &S){ 4955 4956 // If this type is already address space qualified, reject it. 4957 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by 4958 // qualifiers for two or more different address spaces." 4959 if (Type.getAddressSpace()) { 4960 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 4961 Attr.setInvalid(); 4962 return; 4963 } 4964 4965 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 4966 // qualified by an address-space qualifier." 4967 if (Type->isFunctionType()) { 4968 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 4969 Attr.setInvalid(); 4970 return; 4971 } 4972 4973 unsigned ASIdx; 4974 if (Attr.getKind() == AttributeList::AT_AddressSpace) { 4975 // Check the attribute arguments. 4976 if (Attr.getNumArgs() != 1) { 4977 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 4978 << Attr.getName() << 1; 4979 Attr.setInvalid(); 4980 return; 4981 } 4982 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4983 llvm::APSInt addrSpace(32); 4984 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 4985 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 4986 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 4987 << Attr.getName() << AANT_ArgumentIntegerConstant 4988 << ASArgExpr->getSourceRange(); 4989 Attr.setInvalid(); 4990 return; 4991 } 4992 4993 // Bounds checking. 4994 if (addrSpace.isSigned()) { 4995 if (addrSpace.isNegative()) { 4996 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 4997 << ASArgExpr->getSourceRange(); 4998 Attr.setInvalid(); 4999 return; 5000 } 5001 addrSpace.setIsSigned(false); 5002 } 5003 llvm::APSInt max(addrSpace.getBitWidth()); 5004 max = Qualifiers::MaxAddressSpace; 5005 if (addrSpace > max) { 5006 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 5007 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange(); 5008 Attr.setInvalid(); 5009 return; 5010 } 5011 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 5012 } else { 5013 // The keyword-based type attributes imply which address space to use. 5014 switch (Attr.getKind()) { 5015 case AttributeList::AT_OpenCLGlobalAddressSpace: 5016 ASIdx = LangAS::opencl_global; break; 5017 case AttributeList::AT_OpenCLLocalAddressSpace: 5018 ASIdx = LangAS::opencl_local; break; 5019 case AttributeList::AT_OpenCLConstantAddressSpace: 5020 ASIdx = LangAS::opencl_constant; break; 5021 case AttributeList::AT_OpenCLGenericAddressSpace: 5022 ASIdx = LangAS::opencl_generic; break; 5023 default: 5024 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace); 5025 ASIdx = 0; break; 5026 } 5027 } 5028 5029 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 5030 } 5031 5032 /// Does this type have a "direct" ownership qualifier? That is, 5033 /// is it written like "__strong id", as opposed to something like 5034 /// "typeof(foo)", where that happens to be strong? 5035 static bool hasDirectOwnershipQualifier(QualType type) { 5036 // Fast path: no qualifier at all. 5037 assert(type.getQualifiers().hasObjCLifetime()); 5038 5039 while (true) { 5040 // __strong id 5041 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { 5042 if (attr->getAttrKind() == AttributedType::attr_objc_ownership) 5043 return true; 5044 5045 type = attr->getModifiedType(); 5046 5047 // X *__strong (...) 5048 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { 5049 type = paren->getInnerType(); 5050 5051 // That's it for things we want to complain about. In particular, 5052 // we do not want to look through typedefs, typeof(expr), 5053 // typeof(type), or any other way that the type is somehow 5054 // abstracted. 5055 } else { 5056 5057 return false; 5058 } 5059 } 5060 } 5061 5062 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 5063 /// attribute on the specified type. 5064 /// 5065 /// Returns 'true' if the attribute was handled. 5066 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 5067 AttributeList &attr, 5068 QualType &type) { 5069 bool NonObjCPointer = false; 5070 5071 if (!type->isDependentType() && !type->isUndeducedType()) { 5072 if (const PointerType *ptr = type->getAs<PointerType>()) { 5073 QualType pointee = ptr->getPointeeType(); 5074 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 5075 return false; 5076 // It is important not to lose the source info that there was an attribute 5077 // applied to non-objc pointer. We will create an attributed type but 5078 // its type will be the same as the original type. 5079 NonObjCPointer = true; 5080 } else if (!type->isObjCRetainableType()) { 5081 return false; 5082 } 5083 5084 // Don't accept an ownership attribute in the declspec if it would 5085 // just be the return type of a block pointer. 5086 if (state.isProcessingDeclSpec()) { 5087 Declarator &D = state.getDeclarator(); 5088 if (maybeMovePastReturnType(D, D.getNumTypeObjects(), 5089 /*onlyBlockPointers=*/true)) 5090 return false; 5091 } 5092 } 5093 5094 Sema &S = state.getSema(); 5095 SourceLocation AttrLoc = attr.getLoc(); 5096 if (AttrLoc.isMacroID()) 5097 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first; 5098 5099 if (!attr.isArgIdent(0)) { 5100 S.Diag(AttrLoc, diag::err_attribute_argument_type) 5101 << attr.getName() << AANT_ArgumentString; 5102 attr.setInvalid(); 5103 return true; 5104 } 5105 5106 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 5107 Qualifiers::ObjCLifetime lifetime; 5108 if (II->isStr("none")) 5109 lifetime = Qualifiers::OCL_ExplicitNone; 5110 else if (II->isStr("strong")) 5111 lifetime = Qualifiers::OCL_Strong; 5112 else if (II->isStr("weak")) 5113 lifetime = Qualifiers::OCL_Weak; 5114 else if (II->isStr("autoreleasing")) 5115 lifetime = Qualifiers::OCL_Autoreleasing; 5116 else { 5117 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 5118 << attr.getName() << II; 5119 attr.setInvalid(); 5120 return true; 5121 } 5122 5123 // Just ignore lifetime attributes other than __weak and __unsafe_unretained 5124 // outside of ARC mode. 5125 if (!S.getLangOpts().ObjCAutoRefCount && 5126 lifetime != Qualifiers::OCL_Weak && 5127 lifetime != Qualifiers::OCL_ExplicitNone) { 5128 return true; 5129 } 5130 5131 SplitQualType underlyingType = type.split(); 5132 5133 // Check for redundant/conflicting ownership qualifiers. 5134 if (Qualifiers::ObjCLifetime previousLifetime 5135 = type.getQualifiers().getObjCLifetime()) { 5136 // If it's written directly, that's an error. 5137 if (hasDirectOwnershipQualifier(type)) { 5138 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 5139 << type; 5140 return true; 5141 } 5142 5143 // Otherwise, if the qualifiers actually conflict, pull sugar off 5144 // until we reach a type that is directly qualified. 5145 if (previousLifetime != lifetime) { 5146 // This should always terminate: the canonical type is 5147 // qualified, so some bit of sugar must be hiding it. 5148 while (!underlyingType.Quals.hasObjCLifetime()) { 5149 underlyingType = underlyingType.getSingleStepDesugaredType(); 5150 } 5151 underlyingType.Quals.removeObjCLifetime(); 5152 } 5153 } 5154 5155 underlyingType.Quals.addObjCLifetime(lifetime); 5156 5157 if (NonObjCPointer) { 5158 StringRef name = attr.getName()->getName(); 5159 switch (lifetime) { 5160 case Qualifiers::OCL_None: 5161 case Qualifiers::OCL_ExplicitNone: 5162 break; 5163 case Qualifiers::OCL_Strong: name = "__strong"; break; 5164 case Qualifiers::OCL_Weak: name = "__weak"; break; 5165 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 5166 } 5167 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name 5168 << TDS_ObjCObjOrBlock << type; 5169 } 5170 5171 // Don't actually add the __unsafe_unretained qualifier in non-ARC files, 5172 // because having both 'T' and '__unsafe_unretained T' exist in the type 5173 // system causes unfortunate widespread consistency problems. (For example, 5174 // they're not considered compatible types, and we mangle them identicially 5175 // as template arguments.) These problems are all individually fixable, 5176 // but it's easier to just not add the qualifier and instead sniff it out 5177 // in specific places using isObjCInertUnsafeUnretainedType(). 5178 // 5179 // Doing this does means we miss some trivial consistency checks that 5180 // would've triggered in ARC, but that's better than trying to solve all 5181 // the coexistence problems with __unsafe_unretained. 5182 if (!S.getLangOpts().ObjCAutoRefCount && 5183 lifetime == Qualifiers::OCL_ExplicitNone) { 5184 type = S.Context.getAttributedType( 5185 AttributedType::attr_objc_inert_unsafe_unretained, 5186 type, type); 5187 return true; 5188 } 5189 5190 QualType origType = type; 5191 if (!NonObjCPointer) 5192 type = S.Context.getQualifiedType(underlyingType); 5193 5194 // If we have a valid source location for the attribute, use an 5195 // AttributedType instead. 5196 if (AttrLoc.isValid()) 5197 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, 5198 origType, type); 5199 5200 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, 5201 unsigned diagnostic, QualType type) { 5202 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 5203 S.DelayedDiagnostics.add( 5204 sema::DelayedDiagnostic::makeForbiddenType( 5205 S.getSourceManager().getExpansionLoc(loc), 5206 diagnostic, type, /*ignored*/ 0)); 5207 } else { 5208 S.Diag(loc, diagnostic); 5209 } 5210 }; 5211 5212 // Sometimes, __weak isn't allowed. 5213 if (lifetime == Qualifiers::OCL_Weak && 5214 !S.getLangOpts().ObjCWeak && !NonObjCPointer) { 5215 5216 // Use a specialized diagnostic if the runtime just doesn't support them. 5217 unsigned diagnostic = 5218 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled 5219 : diag::err_arc_weak_no_runtime); 5220 5221 // In any case, delay the diagnostic until we know what we're parsing. 5222 diagnoseOrDelay(S, AttrLoc, diagnostic, type); 5223 5224 attr.setInvalid(); 5225 return true; 5226 } 5227 5228 // Forbid __weak for class objects marked as 5229 // objc_arc_weak_reference_unavailable 5230 if (lifetime == Qualifiers::OCL_Weak) { 5231 if (const ObjCObjectPointerType *ObjT = 5232 type->getAs<ObjCObjectPointerType>()) { 5233 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 5234 if (Class->isArcWeakrefUnavailable()) { 5235 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 5236 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 5237 diag::note_class_declared); 5238 } 5239 } 5240 } 5241 } 5242 5243 return true; 5244 } 5245 5246 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 5247 /// attribute on the specified type. Returns true to indicate that 5248 /// the attribute was handled, false to indicate that the type does 5249 /// not permit the attribute. 5250 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 5251 AttributeList &attr, 5252 QualType &type) { 5253 Sema &S = state.getSema(); 5254 5255 // Delay if this isn't some kind of pointer. 5256 if (!type->isPointerType() && 5257 !type->isObjCObjectPointerType() && 5258 !type->isBlockPointerType()) 5259 return false; 5260 5261 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 5262 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 5263 attr.setInvalid(); 5264 return true; 5265 } 5266 5267 // Check the attribute arguments. 5268 if (!attr.isArgIdent(0)) { 5269 S.Diag(attr.getLoc(), diag::err_attribute_argument_type) 5270 << attr.getName() << AANT_ArgumentString; 5271 attr.setInvalid(); 5272 return true; 5273 } 5274 Qualifiers::GC GCAttr; 5275 if (attr.getNumArgs() > 1) { 5276 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) 5277 << attr.getName() << 1; 5278 attr.setInvalid(); 5279 return true; 5280 } 5281 5282 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; 5283 if (II->isStr("weak")) 5284 GCAttr = Qualifiers::Weak; 5285 else if (II->isStr("strong")) 5286 GCAttr = Qualifiers::Strong; 5287 else { 5288 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 5289 << attr.getName() << II; 5290 attr.setInvalid(); 5291 return true; 5292 } 5293 5294 QualType origType = type; 5295 type = S.Context.getObjCGCQualType(origType, GCAttr); 5296 5297 // Make an attributed type to preserve the source information. 5298 if (attr.getLoc().isValid()) 5299 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 5300 origType, type); 5301 5302 return true; 5303 } 5304 5305 namespace { 5306 /// A helper class to unwrap a type down to a function for the 5307 /// purposes of applying attributes there. 5308 /// 5309 /// Use: 5310 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 5311 /// if (unwrapped.isFunctionType()) { 5312 /// const FunctionType *fn = unwrapped.get(); 5313 /// // change fn somehow 5314 /// T = unwrapped.wrap(fn); 5315 /// } 5316 struct FunctionTypeUnwrapper { 5317 enum WrapKind { 5318 Desugar, 5319 Parens, 5320 Pointer, 5321 BlockPointer, 5322 Reference, 5323 MemberPointer 5324 }; 5325 5326 QualType Original; 5327 const FunctionType *Fn; 5328 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 5329 5330 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 5331 while (true) { 5332 const Type *Ty = T.getTypePtr(); 5333 if (isa<FunctionType>(Ty)) { 5334 Fn = cast<FunctionType>(Ty); 5335 return; 5336 } else if (isa<ParenType>(Ty)) { 5337 T = cast<ParenType>(Ty)->getInnerType(); 5338 Stack.push_back(Parens); 5339 } else if (isa<PointerType>(Ty)) { 5340 T = cast<PointerType>(Ty)->getPointeeType(); 5341 Stack.push_back(Pointer); 5342 } else if (isa<BlockPointerType>(Ty)) { 5343 T = cast<BlockPointerType>(Ty)->getPointeeType(); 5344 Stack.push_back(BlockPointer); 5345 } else if (isa<MemberPointerType>(Ty)) { 5346 T = cast<MemberPointerType>(Ty)->getPointeeType(); 5347 Stack.push_back(MemberPointer); 5348 } else if (isa<ReferenceType>(Ty)) { 5349 T = cast<ReferenceType>(Ty)->getPointeeType(); 5350 Stack.push_back(Reference); 5351 } else { 5352 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 5353 if (Ty == DTy) { 5354 Fn = nullptr; 5355 return; 5356 } 5357 5358 T = QualType(DTy, 0); 5359 Stack.push_back(Desugar); 5360 } 5361 } 5362 } 5363 5364 bool isFunctionType() const { return (Fn != nullptr); } 5365 const FunctionType *get() const { return Fn; } 5366 5367 QualType wrap(Sema &S, const FunctionType *New) { 5368 // If T wasn't modified from the unwrapped type, do nothing. 5369 if (New == get()) return Original; 5370 5371 Fn = New; 5372 return wrap(S.Context, Original, 0); 5373 } 5374 5375 private: 5376 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 5377 if (I == Stack.size()) 5378 return C.getQualifiedType(Fn, Old.getQualifiers()); 5379 5380 // Build up the inner type, applying the qualifiers from the old 5381 // type to the new type. 5382 SplitQualType SplitOld = Old.split(); 5383 5384 // As a special case, tail-recurse if there are no qualifiers. 5385 if (SplitOld.Quals.empty()) 5386 return wrap(C, SplitOld.Ty, I); 5387 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 5388 } 5389 5390 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 5391 if (I == Stack.size()) return QualType(Fn, 0); 5392 5393 switch (static_cast<WrapKind>(Stack[I++])) { 5394 case Desugar: 5395 // This is the point at which we potentially lose source 5396 // information. 5397 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 5398 5399 case Parens: { 5400 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 5401 return C.getParenType(New); 5402 } 5403 5404 case Pointer: { 5405 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 5406 return C.getPointerType(New); 5407 } 5408 5409 case BlockPointer: { 5410 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 5411 return C.getBlockPointerType(New); 5412 } 5413 5414 case MemberPointer: { 5415 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 5416 QualType New = wrap(C, OldMPT->getPointeeType(), I); 5417 return C.getMemberPointerType(New, OldMPT->getClass()); 5418 } 5419 5420 case Reference: { 5421 const ReferenceType *OldRef = cast<ReferenceType>(Old); 5422 QualType New = wrap(C, OldRef->getPointeeType(), I); 5423 if (isa<LValueReferenceType>(OldRef)) 5424 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 5425 else 5426 return C.getRValueReferenceType(New); 5427 } 5428 } 5429 5430 llvm_unreachable("unknown wrapping kind"); 5431 } 5432 }; 5433 } 5434 5435 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, 5436 AttributeList &Attr, 5437 QualType &Type) { 5438 Sema &S = State.getSema(); 5439 5440 AttributeList::Kind Kind = Attr.getKind(); 5441 QualType Desugared = Type; 5442 const AttributedType *AT = dyn_cast<AttributedType>(Type); 5443 while (AT) { 5444 AttributedType::Kind CurAttrKind = AT->getAttrKind(); 5445 5446 // You cannot specify duplicate type attributes, so if the attribute has 5447 // already been applied, flag it. 5448 if (getAttrListKind(CurAttrKind) == Kind) { 5449 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact) 5450 << Attr.getName(); 5451 return true; 5452 } 5453 5454 // You cannot have both __sptr and __uptr on the same type, nor can you 5455 // have __ptr32 and __ptr64. 5456 if ((CurAttrKind == AttributedType::attr_ptr32 && 5457 Kind == AttributeList::AT_Ptr64) || 5458 (CurAttrKind == AttributedType::attr_ptr64 && 5459 Kind == AttributeList::AT_Ptr32)) { 5460 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 5461 << "'__ptr32'" << "'__ptr64'"; 5462 return true; 5463 } else if ((CurAttrKind == AttributedType::attr_sptr && 5464 Kind == AttributeList::AT_UPtr) || 5465 (CurAttrKind == AttributedType::attr_uptr && 5466 Kind == AttributeList::AT_SPtr)) { 5467 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 5468 << "'__sptr'" << "'__uptr'"; 5469 return true; 5470 } 5471 5472 Desugared = AT->getEquivalentType(); 5473 AT = dyn_cast<AttributedType>(Desugared); 5474 } 5475 5476 // Pointer type qualifiers can only operate on pointer types, but not 5477 // pointer-to-member types. 5478 if (!isa<PointerType>(Desugared)) { 5479 if (Type->isMemberPointerType()) 5480 S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers) 5481 << Attr.getName(); 5482 else 5483 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only) 5484 << Attr.getName() << 0; 5485 return true; 5486 } 5487 5488 AttributedType::Kind TAK; 5489 switch (Kind) { 5490 default: llvm_unreachable("Unknown attribute kind"); 5491 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break; 5492 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break; 5493 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break; 5494 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break; 5495 } 5496 5497 Type = S.Context.getAttributedType(TAK, Type, Type); 5498 return false; 5499 } 5500 5501 bool Sema::checkNullabilityTypeSpecifier(QualType &type, 5502 NullabilityKind nullability, 5503 SourceLocation nullabilityLoc, 5504 bool isContextSensitive) { 5505 // We saw a nullability type specifier. If this is the first one for 5506 // this file, note that. 5507 FileID file = getNullabilityCompletenessCheckFileID(*this, nullabilityLoc); 5508 if (!file.isInvalid()) { 5509 FileNullability &fileNullability = NullabilityMap[file]; 5510 if (!fileNullability.SawTypeNullability) { 5511 // If we have already seen a pointer declarator without a nullability 5512 // annotation, complain about it. 5513 if (fileNullability.PointerLoc.isValid()) { 5514 Diag(fileNullability.PointerLoc, diag::warn_nullability_missing) 5515 << static_cast<unsigned>(fileNullability.PointerKind); 5516 } 5517 5518 fileNullability.SawTypeNullability = true; 5519 } 5520 } 5521 5522 // Check for existing nullability attributes on the type. 5523 QualType desugared = type; 5524 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { 5525 // Check whether there is already a null 5526 if (auto existingNullability = attributed->getImmediateNullability()) { 5527 // Duplicated nullability. 5528 if (nullability == *existingNullability) { 5529 Diag(nullabilityLoc, diag::warn_nullability_duplicate) 5530 << DiagNullabilityKind(nullability, isContextSensitive) 5531 << FixItHint::CreateRemoval(nullabilityLoc); 5532 5533 break; 5534 } 5535 5536 // Conflicting nullability. 5537 Diag(nullabilityLoc, diag::err_nullability_conflicting) 5538 << DiagNullabilityKind(nullability, isContextSensitive) 5539 << DiagNullabilityKind(*existingNullability, false); 5540 return true; 5541 } 5542 5543 desugared = attributed->getModifiedType(); 5544 } 5545 5546 // If there is already a different nullability specifier, complain. 5547 // This (unlike the code above) looks through typedefs that might 5548 // have nullability specifiers on them, which means we cannot 5549 // provide a useful Fix-It. 5550 if (auto existingNullability = desugared->getNullability(Context)) { 5551 if (nullability != *existingNullability) { 5552 Diag(nullabilityLoc, diag::err_nullability_conflicting) 5553 << DiagNullabilityKind(nullability, isContextSensitive) 5554 << DiagNullabilityKind(*existingNullability, false); 5555 5556 // Try to find the typedef with the existing nullability specifier. 5557 if (auto typedefType = desugared->getAs<TypedefType>()) { 5558 TypedefNameDecl *typedefDecl = typedefType->getDecl(); 5559 QualType underlyingType = typedefDecl->getUnderlyingType(); 5560 if (auto typedefNullability 5561 = AttributedType::stripOuterNullability(underlyingType)) { 5562 if (*typedefNullability == *existingNullability) { 5563 Diag(typedefDecl->getLocation(), diag::note_nullability_here) 5564 << DiagNullabilityKind(*existingNullability, false); 5565 } 5566 } 5567 } 5568 5569 return true; 5570 } 5571 } 5572 5573 // If this definitely isn't a pointer type, reject the specifier. 5574 if (!desugared->canHaveNullability()) { 5575 Diag(nullabilityLoc, diag::err_nullability_nonpointer) 5576 << DiagNullabilityKind(nullability, isContextSensitive) << type; 5577 return true; 5578 } 5579 5580 // For the context-sensitive keywords/Objective-C property 5581 // attributes, require that the type be a single-level pointer. 5582 if (isContextSensitive) { 5583 // Make sure that the pointee isn't itself a pointer type. 5584 QualType pointeeType = desugared->getPointeeType(); 5585 if (pointeeType->isAnyPointerType() || 5586 pointeeType->isObjCObjectPointerType() || 5587 pointeeType->isMemberPointerType()) { 5588 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) 5589 << DiagNullabilityKind(nullability, true) 5590 << type; 5591 Diag(nullabilityLoc, diag::note_nullability_type_specifier) 5592 << DiagNullabilityKind(nullability, false) 5593 << type 5594 << FixItHint::CreateReplacement(nullabilityLoc, 5595 getNullabilitySpelling(nullability)); 5596 return true; 5597 } 5598 } 5599 5600 // Form the attributed type. 5601 type = Context.getAttributedType( 5602 AttributedType::getNullabilityAttrKind(nullability), type, type); 5603 return false; 5604 } 5605 5606 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) { 5607 // Find out if it's an Objective-C object or object pointer type; 5608 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); 5609 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() 5610 : type->getAs<ObjCObjectType>(); 5611 5612 // If not, we can't apply __kindof. 5613 if (!objType) { 5614 // FIXME: Handle dependent types that aren't yet object types. 5615 Diag(loc, diag::err_objc_kindof_nonobject) 5616 << type; 5617 return true; 5618 } 5619 5620 // Rebuild the "equivalent" type, which pushes __kindof down into 5621 // the object type. 5622 QualType equivType = Context.getObjCObjectType(objType->getBaseType(), 5623 objType->getTypeArgsAsWritten(), 5624 objType->getProtocols(), 5625 /*isKindOf=*/true); 5626 5627 // If we started with an object pointer type, rebuild it. 5628 if (ptrType) { 5629 equivType = Context.getObjCObjectPointerType(equivType); 5630 if (auto nullability = type->getNullability(Context)) { 5631 auto attrKind = AttributedType::getNullabilityAttrKind(*nullability); 5632 equivType = Context.getAttributedType(attrKind, equivType, equivType); 5633 } 5634 } 5635 5636 // Build the attributed type to record where __kindof occurred. 5637 type = Context.getAttributedType(AttributedType::attr_objc_kindof, 5638 type, 5639 equivType); 5640 5641 return false; 5642 } 5643 5644 /// Map a nullability attribute kind to a nullability kind. 5645 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) { 5646 switch (kind) { 5647 case AttributeList::AT_TypeNonNull: 5648 return NullabilityKind::NonNull; 5649 5650 case AttributeList::AT_TypeNullable: 5651 return NullabilityKind::Nullable; 5652 5653 case AttributeList::AT_TypeNullUnspecified: 5654 return NullabilityKind::Unspecified; 5655 5656 default: 5657 llvm_unreachable("not a nullability attribute kind"); 5658 } 5659 } 5660 5661 /// Distribute a nullability type attribute that cannot be applied to 5662 /// the type specifier to a pointer, block pointer, or member pointer 5663 /// declarator, complaining if necessary. 5664 /// 5665 /// \returns true if the nullability annotation was distributed, false 5666 /// otherwise. 5667 static bool distributeNullabilityTypeAttr(TypeProcessingState &state, 5668 QualType type, 5669 AttributeList &attr) { 5670 Declarator &declarator = state.getDeclarator(); 5671 5672 /// Attempt to move the attribute to the specified chunk. 5673 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { 5674 // If there is already a nullability attribute there, don't add 5675 // one. 5676 if (hasNullabilityAttr(chunk.getAttrListRef())) 5677 return false; 5678 5679 // Complain about the nullability qualifier being in the wrong 5680 // place. 5681 enum { 5682 PK_Pointer, 5683 PK_BlockPointer, 5684 PK_MemberPointer, 5685 PK_FunctionPointer, 5686 PK_MemberFunctionPointer, 5687 } pointerKind 5688 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer 5689 : PK_Pointer) 5690 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer 5691 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; 5692 5693 auto diag = state.getSema().Diag(attr.getLoc(), 5694 diag::warn_nullability_declspec) 5695 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), 5696 attr.isContextSensitiveKeywordAttribute()) 5697 << type 5698 << static_cast<unsigned>(pointerKind); 5699 5700 // FIXME: MemberPointer chunks don't carry the location of the *. 5701 if (chunk.Kind != DeclaratorChunk::MemberPointer) { 5702 diag << FixItHint::CreateRemoval(attr.getLoc()) 5703 << FixItHint::CreateInsertion( 5704 state.getSema().getPreprocessor() 5705 .getLocForEndOfToken(chunk.Loc), 5706 " " + attr.getName()->getName().str() + " "); 5707 } 5708 5709 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 5710 chunk.getAttrListRef()); 5711 return true; 5712 }; 5713 5714 // Move it to the outermost pointer, member pointer, or block 5715 // pointer declarator. 5716 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 5717 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 5718 switch (chunk.Kind) { 5719 case DeclaratorChunk::Pointer: 5720 case DeclaratorChunk::BlockPointer: 5721 case DeclaratorChunk::MemberPointer: 5722 return moveToChunk(chunk, false); 5723 5724 case DeclaratorChunk::Paren: 5725 case DeclaratorChunk::Array: 5726 continue; 5727 5728 case DeclaratorChunk::Function: 5729 // Try to move past the return type to a function/block/member 5730 // function pointer. 5731 if (DeclaratorChunk *dest = maybeMovePastReturnType( 5732 declarator, i, 5733 /*onlyBlockPointers=*/false)) { 5734 return moveToChunk(*dest, true); 5735 } 5736 5737 return false; 5738 5739 // Don't walk through these. 5740 case DeclaratorChunk::Reference: 5741 return false; 5742 } 5743 } 5744 5745 return false; 5746 } 5747 5748 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) { 5749 assert(!Attr.isInvalid()); 5750 switch (Attr.getKind()) { 5751 default: 5752 llvm_unreachable("not a calling convention attribute"); 5753 case AttributeList::AT_CDecl: 5754 return AttributedType::attr_cdecl; 5755 case AttributeList::AT_FastCall: 5756 return AttributedType::attr_fastcall; 5757 case AttributeList::AT_StdCall: 5758 return AttributedType::attr_stdcall; 5759 case AttributeList::AT_ThisCall: 5760 return AttributedType::attr_thiscall; 5761 case AttributeList::AT_Pascal: 5762 return AttributedType::attr_pascal; 5763 case AttributeList::AT_VectorCall: 5764 return AttributedType::attr_vectorcall; 5765 case AttributeList::AT_Pcs: { 5766 // The attribute may have had a fixit applied where we treated an 5767 // identifier as a string literal. The contents of the string are valid, 5768 // but the form may not be. 5769 StringRef Str; 5770 if (Attr.isArgExpr(0)) 5771 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); 5772 else 5773 Str = Attr.getArgAsIdent(0)->Ident->getName(); 5774 return llvm::StringSwitch<AttributedType::Kind>(Str) 5775 .Case("aapcs", AttributedType::attr_pcs) 5776 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp); 5777 } 5778 case AttributeList::AT_IntelOclBicc: 5779 return AttributedType::attr_inteloclbicc; 5780 case AttributeList::AT_MSABI: 5781 return AttributedType::attr_ms_abi; 5782 case AttributeList::AT_SysVABI: 5783 return AttributedType::attr_sysv_abi; 5784 } 5785 llvm_unreachable("unexpected attribute kind!"); 5786 } 5787 5788 /// Process an individual function attribute. Returns true to 5789 /// indicate that the attribute was handled, false if it wasn't. 5790 static bool handleFunctionTypeAttr(TypeProcessingState &state, 5791 AttributeList &attr, 5792 QualType &type) { 5793 Sema &S = state.getSema(); 5794 5795 FunctionTypeUnwrapper unwrapped(S, type); 5796 5797 if (attr.getKind() == AttributeList::AT_NoReturn) { 5798 if (S.CheckNoReturnAttr(attr)) 5799 return true; 5800 5801 // Delay if this is not a function type. 5802 if (!unwrapped.isFunctionType()) 5803 return false; 5804 5805 // Otherwise we can process right away. 5806 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 5807 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 5808 return true; 5809 } 5810 5811 // ns_returns_retained is not always a type attribute, but if we got 5812 // here, we're treating it as one right now. 5813 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) { 5814 assert(S.getLangOpts().ObjCAutoRefCount && 5815 "ns_returns_retained treated as type attribute in non-ARC"); 5816 if (attr.getNumArgs()) return true; 5817 5818 // Delay if this is not a function type. 5819 if (!unwrapped.isFunctionType()) 5820 return false; 5821 5822 FunctionType::ExtInfo EI 5823 = unwrapped.get()->getExtInfo().withProducesResult(true); 5824 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 5825 return true; 5826 } 5827 5828 if (attr.getKind() == AttributeList::AT_Regparm) { 5829 unsigned value; 5830 if (S.CheckRegparmAttr(attr, value)) 5831 return true; 5832 5833 // Delay if this is not a function type. 5834 if (!unwrapped.isFunctionType()) 5835 return false; 5836 5837 // Diagnose regparm with fastcall. 5838 const FunctionType *fn = unwrapped.get(); 5839 CallingConv CC = fn->getCallConv(); 5840 if (CC == CC_X86FastCall) { 5841 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 5842 << FunctionType::getNameForCallConv(CC) 5843 << "regparm"; 5844 attr.setInvalid(); 5845 return true; 5846 } 5847 5848 FunctionType::ExtInfo EI = 5849 unwrapped.get()->getExtInfo().withRegParm(value); 5850 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 5851 return true; 5852 } 5853 5854 // Delay if the type didn't work out to a function. 5855 if (!unwrapped.isFunctionType()) return false; 5856 5857 // Otherwise, a calling convention. 5858 CallingConv CC; 5859 if (S.CheckCallingConvAttr(attr, CC)) 5860 return true; 5861 5862 const FunctionType *fn = unwrapped.get(); 5863 CallingConv CCOld = fn->getCallConv(); 5864 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr); 5865 5866 if (CCOld != CC) { 5867 // Error out on when there's already an attribute on the type 5868 // and the CCs don't match. 5869 const AttributedType *AT = S.getCallingConvAttributedType(type); 5870 if (AT && AT->getAttrKind() != CCAttrKind) { 5871 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 5872 << FunctionType::getNameForCallConv(CC) 5873 << FunctionType::getNameForCallConv(CCOld); 5874 attr.setInvalid(); 5875 return true; 5876 } 5877 } 5878 5879 // Diagnose use of callee-cleanup calling convention on variadic functions. 5880 if (!supportsVariadicCall(CC)) { 5881 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); 5882 if (FnP && FnP->isVariadic()) { 5883 unsigned DiagID = diag::err_cconv_varargs; 5884 // stdcall and fastcall are ignored with a warning for GCC and MS 5885 // compatibility. 5886 if (CC == CC_X86StdCall || CC == CC_X86FastCall) 5887 DiagID = diag::warn_cconv_varargs; 5888 5889 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC); 5890 attr.setInvalid(); 5891 return true; 5892 } 5893 } 5894 5895 // Also diagnose fastcall with regparm. 5896 if (CC == CC_X86FastCall && fn->getHasRegParm()) { 5897 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 5898 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); 5899 attr.setInvalid(); 5900 return true; 5901 } 5902 5903 // Modify the CC from the wrapped function type, wrap it all back, and then 5904 // wrap the whole thing in an AttributedType as written. The modified type 5905 // might have a different CC if we ignored the attribute. 5906 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 5907 QualType Equivalent = 5908 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 5909 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent); 5910 return true; 5911 } 5912 5913 bool Sema::hasExplicitCallingConv(QualType &T) { 5914 QualType R = T.IgnoreParens(); 5915 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) { 5916 if (AT->isCallingConv()) 5917 return true; 5918 R = AT->getModifiedType().IgnoreParens(); 5919 } 5920 return false; 5921 } 5922 5923 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, 5924 SourceLocation Loc) { 5925 FunctionTypeUnwrapper Unwrapped(*this, T); 5926 const FunctionType *FT = Unwrapped.get(); 5927 bool IsVariadic = (isa<FunctionProtoType>(FT) && 5928 cast<FunctionProtoType>(FT)->isVariadic()); 5929 CallingConv CurCC = FT->getCallConv(); 5930 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); 5931 5932 if (CurCC == ToCC) 5933 return; 5934 5935 // MS compiler ignores explicit calling convention attributes on structors. We 5936 // should do the same. 5937 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { 5938 // Issue a warning on ignored calling convention -- except of __stdcall. 5939 // Again, this is what MS compiler does. 5940 if (CurCC != CC_X86StdCall) 5941 Diag(Loc, diag::warn_cconv_structors) 5942 << FunctionType::getNameForCallConv(CurCC); 5943 // Default adjustment. 5944 } else { 5945 // Only adjust types with the default convention. For example, on Windows 5946 // we should adjust a __cdecl type to __thiscall for instance methods, and a 5947 // __thiscall type to __cdecl for static methods. 5948 CallingConv DefaultCC = 5949 Context.getDefaultCallingConvention(IsVariadic, IsStatic); 5950 5951 if (CurCC != DefaultCC || DefaultCC == ToCC) 5952 return; 5953 5954 if (hasExplicitCallingConv(T)) 5955 return; 5956 } 5957 5958 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); 5959 QualType Wrapped = Unwrapped.wrap(*this, FT); 5960 T = Context.getAdjustedType(T, Wrapped); 5961 } 5962 5963 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 5964 /// and float scalars, although arrays, pointers, and function return values are 5965 /// allowed in conjunction with this construct. Aggregates with this attribute 5966 /// are invalid, even if they are of the same size as a corresponding scalar. 5967 /// The raw attribute should contain precisely 1 argument, the vector size for 5968 /// the variable, measured in bytes. If curType and rawAttr are well formed, 5969 /// this routine will return a new vector type. 5970 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 5971 Sema &S) { 5972 // Check the attribute arguments. 5973 if (Attr.getNumArgs() != 1) { 5974 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 5975 << Attr.getName() << 1; 5976 Attr.setInvalid(); 5977 return; 5978 } 5979 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 5980 llvm::APSInt vecSize(32); 5981 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 5982 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 5983 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 5984 << Attr.getName() << AANT_ArgumentIntegerConstant 5985 << sizeExpr->getSourceRange(); 5986 Attr.setInvalid(); 5987 return; 5988 } 5989 // The base type must be integer (not Boolean or enumeration) or float, and 5990 // can't already be a vector. 5991 if (!CurType->isBuiltinType() || CurType->isBooleanType() || 5992 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) { 5993 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 5994 Attr.setInvalid(); 5995 return; 5996 } 5997 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 5998 // vecSize is specified in bytes - convert to bits. 5999 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 6000 6001 // the vector size needs to be an integral multiple of the type size. 6002 if (vectorSize % typeSize) { 6003 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 6004 << sizeExpr->getSourceRange(); 6005 Attr.setInvalid(); 6006 return; 6007 } 6008 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) { 6009 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large) 6010 << sizeExpr->getSourceRange(); 6011 Attr.setInvalid(); 6012 return; 6013 } 6014 if (vectorSize == 0) { 6015 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 6016 << sizeExpr->getSourceRange(); 6017 Attr.setInvalid(); 6018 return; 6019 } 6020 6021 // Success! Instantiate the vector type, the number of elements is > 0, and 6022 // not required to be a power of 2, unlike GCC. 6023 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 6024 VectorType::GenericVector); 6025 } 6026 6027 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on 6028 /// a type. 6029 static void HandleExtVectorTypeAttr(QualType &CurType, 6030 const AttributeList &Attr, 6031 Sema &S) { 6032 // check the attribute arguments. 6033 if (Attr.getNumArgs() != 1) { 6034 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6035 << Attr.getName() << 1; 6036 return; 6037 } 6038 6039 Expr *sizeExpr; 6040 6041 // Special case where the argument is a template id. 6042 if (Attr.isArgIdent(0)) { 6043 CXXScopeSpec SS; 6044 SourceLocation TemplateKWLoc; 6045 UnqualifiedId id; 6046 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc()); 6047 6048 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 6049 id, false, false); 6050 if (Size.isInvalid()) 6051 return; 6052 6053 sizeExpr = Size.get(); 6054 } else { 6055 sizeExpr = Attr.getArgAsExpr(0); 6056 } 6057 6058 // Create the vector type. 6059 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 6060 if (!T.isNull()) 6061 CurType = T; 6062 } 6063 6064 static bool isPermittedNeonBaseType(QualType &Ty, 6065 VectorType::VectorKind VecKind, Sema &S) { 6066 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 6067 if (!BTy) 6068 return false; 6069 6070 llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); 6071 6072 // Signed poly is mathematically wrong, but has been baked into some ABIs by 6073 // now. 6074 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || 6075 Triple.getArch() == llvm::Triple::aarch64_be; 6076 if (VecKind == VectorType::NeonPolyVector) { 6077 if (IsPolyUnsigned) { 6078 // AArch64 polynomial vectors are unsigned and support poly64. 6079 return BTy->getKind() == BuiltinType::UChar || 6080 BTy->getKind() == BuiltinType::UShort || 6081 BTy->getKind() == BuiltinType::ULong || 6082 BTy->getKind() == BuiltinType::ULongLong; 6083 } else { 6084 // AArch32 polynomial vector are signed. 6085 return BTy->getKind() == BuiltinType::SChar || 6086 BTy->getKind() == BuiltinType::Short; 6087 } 6088 } 6089 6090 // Non-polynomial vector types: the usual suspects are allowed, as well as 6091 // float64_t on AArch64. 6092 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 || 6093 Triple.getArch() == llvm::Triple::aarch64_be; 6094 6095 if (Is64Bit && BTy->getKind() == BuiltinType::Double) 6096 return true; 6097 6098 return BTy->getKind() == BuiltinType::SChar || 6099 BTy->getKind() == BuiltinType::UChar || 6100 BTy->getKind() == BuiltinType::Short || 6101 BTy->getKind() == BuiltinType::UShort || 6102 BTy->getKind() == BuiltinType::Int || 6103 BTy->getKind() == BuiltinType::UInt || 6104 BTy->getKind() == BuiltinType::Long || 6105 BTy->getKind() == BuiltinType::ULong || 6106 BTy->getKind() == BuiltinType::LongLong || 6107 BTy->getKind() == BuiltinType::ULongLong || 6108 BTy->getKind() == BuiltinType::Float || 6109 BTy->getKind() == BuiltinType::Half; 6110 } 6111 6112 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 6113 /// "neon_polyvector_type" attributes are used to create vector types that 6114 /// are mangled according to ARM's ABI. Otherwise, these types are identical 6115 /// to those created with the "vector_size" attribute. Unlike "vector_size" 6116 /// the argument to these Neon attributes is the number of vector elements, 6117 /// not the vector size in bytes. The vector width and element type must 6118 /// match one of the standard Neon vector types. 6119 static void HandleNeonVectorTypeAttr(QualType& CurType, 6120 const AttributeList &Attr, Sema &S, 6121 VectorType::VectorKind VecKind) { 6122 // Target must have NEON 6123 if (!S.Context.getTargetInfo().hasFeature("neon")) { 6124 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName(); 6125 Attr.setInvalid(); 6126 return; 6127 } 6128 // Check the attribute arguments. 6129 if (Attr.getNumArgs() != 1) { 6130 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 6131 << Attr.getName() << 1; 6132 Attr.setInvalid(); 6133 return; 6134 } 6135 // The number of elements must be an ICE. 6136 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 6137 llvm::APSInt numEltsInt(32); 6138 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 6139 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 6140 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 6141 << Attr.getName() << AANT_ArgumentIntegerConstant 6142 << numEltsExpr->getSourceRange(); 6143 Attr.setInvalid(); 6144 return; 6145 } 6146 // Only certain element types are supported for Neon vectors. 6147 if (!isPermittedNeonBaseType(CurType, VecKind, S)) { 6148 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 6149 Attr.setInvalid(); 6150 return; 6151 } 6152 6153 // The total size of the vector must be 64 or 128 bits. 6154 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 6155 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 6156 unsigned vecSize = typeSize * numElts; 6157 if (vecSize != 64 && vecSize != 128) { 6158 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 6159 Attr.setInvalid(); 6160 return; 6161 } 6162 6163 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 6164 } 6165 6166 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 6167 TypeAttrLocation TAL, AttributeList *attrs) { 6168 // Scan through and apply attributes to this type where it makes sense. Some 6169 // attributes (such as __address_space__, __vector_size__, etc) apply to the 6170 // type, but others can be present in the type specifiers even though they 6171 // apply to the decl. Here we apply type attributes and ignore the rest. 6172 6173 bool hasOpenCLAddressSpace = false; 6174 while (attrs) { 6175 AttributeList &attr = *attrs; 6176 attrs = attr.getNext(); // reset to the next here due to early loop continue 6177 // stmts 6178 6179 // Skip attributes that were marked to be invalid. 6180 if (attr.isInvalid()) 6181 continue; 6182 6183 if (attr.isCXX11Attribute()) { 6184 // [[gnu::...]] attributes are treated as declaration attributes, so may 6185 // not appertain to a DeclaratorChunk, even if we handle them as type 6186 // attributes. 6187 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) { 6188 if (TAL == TAL_DeclChunk) { 6189 state.getSema().Diag(attr.getLoc(), 6190 diag::warn_cxx11_gnu_attribute_on_type) 6191 << attr.getName(); 6192 continue; 6193 } 6194 } else if (TAL != TAL_DeclChunk) { 6195 // Otherwise, only consider type processing for a C++11 attribute if 6196 // it's actually been applied to a type. 6197 continue; 6198 } 6199 } 6200 6201 // If this is an attribute we can handle, do so now, 6202 // otherwise, add it to the FnAttrs list for rechaining. 6203 switch (attr.getKind()) { 6204 default: 6205 // A C++11 attribute on a declarator chunk must appertain to a type. 6206 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { 6207 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 6208 << attr.getName(); 6209 attr.setUsedAsTypeAttr(); 6210 } 6211 break; 6212 6213 case AttributeList::UnknownAttribute: 6214 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) 6215 state.getSema().Diag(attr.getLoc(), 6216 diag::warn_unknown_attribute_ignored) 6217 << attr.getName(); 6218 break; 6219 6220 case AttributeList::IgnoredAttribute: 6221 break; 6222 6223 case AttributeList::AT_MayAlias: 6224 // FIXME: This attribute needs to actually be handled, but if we ignore 6225 // it it breaks large amounts of Linux software. 6226 attr.setUsedAsTypeAttr(); 6227 break; 6228 case AttributeList::AT_OpenCLPrivateAddressSpace: 6229 case AttributeList::AT_OpenCLGlobalAddressSpace: 6230 case AttributeList::AT_OpenCLLocalAddressSpace: 6231 case AttributeList::AT_OpenCLConstantAddressSpace: 6232 case AttributeList::AT_OpenCLGenericAddressSpace: 6233 case AttributeList::AT_AddressSpace: 6234 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 6235 attr.setUsedAsTypeAttr(); 6236 hasOpenCLAddressSpace = true; 6237 break; 6238 OBJC_POINTER_TYPE_ATTRS_CASELIST: 6239 if (!handleObjCPointerTypeAttr(state, attr, type)) 6240 distributeObjCPointerTypeAttr(state, attr, type); 6241 attr.setUsedAsTypeAttr(); 6242 break; 6243 case AttributeList::AT_VectorSize: 6244 HandleVectorSizeAttr(type, attr, state.getSema()); 6245 attr.setUsedAsTypeAttr(); 6246 break; 6247 case AttributeList::AT_ExtVectorType: 6248 HandleExtVectorTypeAttr(type, attr, state.getSema()); 6249 attr.setUsedAsTypeAttr(); 6250 break; 6251 case AttributeList::AT_NeonVectorType: 6252 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 6253 VectorType::NeonVector); 6254 attr.setUsedAsTypeAttr(); 6255 break; 6256 case AttributeList::AT_NeonPolyVectorType: 6257 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 6258 VectorType::NeonPolyVector); 6259 attr.setUsedAsTypeAttr(); 6260 break; 6261 case AttributeList::AT_OpenCLImageAccess: 6262 // FIXME: there should be some type checking happening here, I would 6263 // imagine, but the original handler's checking was entirely superfluous. 6264 attr.setUsedAsTypeAttr(); 6265 break; 6266 6267 MS_TYPE_ATTRS_CASELIST: 6268 if (!handleMSPointerTypeQualifierAttr(state, attr, type)) 6269 attr.setUsedAsTypeAttr(); 6270 break; 6271 6272 6273 NULLABILITY_TYPE_ATTRS_CASELIST: 6274 // Either add nullability here or try to distribute it. We 6275 // don't want to distribute the nullability specifier past any 6276 // dependent type, because that complicates the user model. 6277 if (type->canHaveNullability() || type->isDependentType() || 6278 !distributeNullabilityTypeAttr(state, type, attr)) { 6279 if (state.getSema().checkNullabilityTypeSpecifier( 6280 type, 6281 mapNullabilityAttrKind(attr.getKind()), 6282 attr.getLoc(), 6283 attr.isContextSensitiveKeywordAttribute())) { 6284 attr.setInvalid(); 6285 } 6286 6287 attr.setUsedAsTypeAttr(); 6288 } 6289 break; 6290 6291 case AttributeList::AT_ObjCKindOf: 6292 // '__kindof' must be part of the decl-specifiers. 6293 switch (TAL) { 6294 case TAL_DeclSpec: 6295 break; 6296 6297 case TAL_DeclChunk: 6298 case TAL_DeclName: 6299 state.getSema().Diag(attr.getLoc(), 6300 diag::err_objc_kindof_wrong_position) 6301 << FixItHint::CreateRemoval(attr.getLoc()) 6302 << FixItHint::CreateInsertion( 6303 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof "); 6304 break; 6305 } 6306 6307 // Apply it regardless. 6308 if (state.getSema().checkObjCKindOfType(type, attr.getLoc())) 6309 attr.setInvalid(); 6310 attr.setUsedAsTypeAttr(); 6311 break; 6312 6313 case AttributeList::AT_NSReturnsRetained: 6314 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 6315 break; 6316 // fallthrough into the function attrs 6317 6318 FUNCTION_TYPE_ATTRS_CASELIST: 6319 attr.setUsedAsTypeAttr(); 6320 6321 // Never process function type attributes as part of the 6322 // declaration-specifiers. 6323 if (TAL == TAL_DeclSpec) 6324 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 6325 6326 // Otherwise, handle the possible delays. 6327 else if (!handleFunctionTypeAttr(state, attr, type)) 6328 distributeFunctionTypeAttr(state, attr, type); 6329 break; 6330 } 6331 } 6332 6333 // If address space is not set, OpenCL 2.0 defines non private default 6334 // address spaces for some cases: 6335 // OpenCL 2.0, section 6.5: 6336 // The address space for a variable at program scope or a static variable 6337 // inside a function can either be __global or __constant, but defaults to 6338 // __global if not specified. 6339 // (...) 6340 // Pointers that are declared without pointing to a named address space point 6341 // to the generic address space. 6342 if (state.getSema().getLangOpts().OpenCLVersion >= 200 && 6343 !hasOpenCLAddressSpace && type.getAddressSpace() == 0 && 6344 (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) { 6345 Declarator &D = state.getDeclarator(); 6346 if (state.getCurrentChunkIndex() > 0 && 6347 D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind == 6348 DeclaratorChunk::Pointer) { 6349 type = state.getSema().Context.getAddrSpaceQualType( 6350 type, LangAS::opencl_generic); 6351 } else if (state.getCurrentChunkIndex() == 0 && 6352 D.getContext() == Declarator::FileContext && 6353 !D.isFunctionDeclarator() && !D.isFunctionDefinition() && 6354 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6355 !type->isSamplerT()) 6356 type = state.getSema().Context.getAddrSpaceQualType( 6357 type, LangAS::opencl_global); 6358 else if (state.getCurrentChunkIndex() == 0 && 6359 D.getContext() == Declarator::BlockContext && 6360 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) 6361 type = state.getSema().Context.getAddrSpaceQualType( 6362 type, LangAS::opencl_global); 6363 } 6364 } 6365 6366 void Sema::completeExprArrayBound(Expr *E) { 6367 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 6368 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 6369 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { 6370 SourceLocation PointOfInstantiation = E->getExprLoc(); 6371 6372 if (MemberSpecializationInfo *MSInfo = 6373 Var->getMemberSpecializationInfo()) { 6374 // If we don't already have a point of instantiation, this is it. 6375 if (MSInfo->getPointOfInstantiation().isInvalid()) { 6376 MSInfo->setPointOfInstantiation(PointOfInstantiation); 6377 6378 // This is a modification of an existing AST node. Notify 6379 // listeners. 6380 if (ASTMutationListener *L = getASTMutationListener()) 6381 L->StaticDataMemberInstantiated(Var); 6382 } 6383 } else { 6384 VarTemplateSpecializationDecl *VarSpec = 6385 cast<VarTemplateSpecializationDecl>(Var); 6386 if (VarSpec->getPointOfInstantiation().isInvalid()) 6387 VarSpec->setPointOfInstantiation(PointOfInstantiation); 6388 } 6389 6390 InstantiateVariableDefinition(PointOfInstantiation, Var); 6391 6392 // Update the type to the newly instantiated definition's type both 6393 // here and within the expression. 6394 if (VarDecl *Def = Var->getDefinition()) { 6395 DRE->setDecl(Def); 6396 QualType T = Def->getType(); 6397 DRE->setType(T); 6398 // FIXME: Update the type on all intervening expressions. 6399 E->setType(T); 6400 } 6401 6402 // We still go on to try to complete the type independently, as it 6403 // may also require instantiations or diagnostics if it remains 6404 // incomplete. 6405 } 6406 } 6407 } 6408 } 6409 6410 /// \brief Ensure that the type of the given expression is complete. 6411 /// 6412 /// This routine checks whether the expression \p E has a complete type. If the 6413 /// expression refers to an instantiable construct, that instantiation is 6414 /// performed as needed to complete its type. Furthermore 6415 /// Sema::RequireCompleteType is called for the expression's type (or in the 6416 /// case of a reference type, the referred-to type). 6417 /// 6418 /// \param E The expression whose type is required to be complete. 6419 /// \param Diagnoser The object that will emit a diagnostic if the type is 6420 /// incomplete. 6421 /// 6422 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 6423 /// otherwise. 6424 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) { 6425 QualType T = E->getType(); 6426 6427 // Incomplete array types may be completed by the initializer attached to 6428 // their definitions. For static data members of class templates and for 6429 // variable templates, we need to instantiate the definition to get this 6430 // initializer and complete the type. 6431 if (T->isIncompleteArrayType()) { 6432 completeExprArrayBound(E); 6433 T = E->getType(); 6434 } 6435 6436 // FIXME: Are there other cases which require instantiating something other 6437 // than the type to complete the type of an expression? 6438 6439 return RequireCompleteType(E->getExprLoc(), T, Diagnoser); 6440 } 6441 6442 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 6443 BoundTypeDiagnoser<> Diagnoser(DiagID); 6444 return RequireCompleteExprType(E, Diagnoser); 6445 } 6446 6447 /// @brief Ensure that the type T is a complete type. 6448 /// 6449 /// This routine checks whether the type @p T is complete in any 6450 /// context where a complete type is required. If @p T is a complete 6451 /// type, returns false. If @p T is a class template specialization, 6452 /// this routine then attempts to perform class template 6453 /// instantiation. If instantiation fails, or if @p T is incomplete 6454 /// and cannot be completed, issues the diagnostic @p diag (giving it 6455 /// the type @p T) and returns true. 6456 /// 6457 /// @param Loc The location in the source that the incomplete type 6458 /// diagnostic should refer to. 6459 /// 6460 /// @param T The type that this routine is examining for completeness. 6461 /// 6462 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 6463 /// @c false otherwise. 6464 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 6465 TypeDiagnoser &Diagnoser) { 6466 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser)) 6467 return true; 6468 if (const TagType *Tag = T->getAs<TagType>()) { 6469 if (!Tag->getDecl()->isCompleteDefinitionRequired()) { 6470 Tag->getDecl()->setCompleteDefinitionRequired(); 6471 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); 6472 } 6473 } 6474 return false; 6475 } 6476 6477 /// \brief Determine whether there is any declaration of \p D that was ever a 6478 /// definition (perhaps before module merging) and is currently visible. 6479 /// \param D The definition of the entity. 6480 /// \param Suggested Filled in with the declaration that should be made visible 6481 /// in order to provide a definition of this entity. 6482 /// \param OnlyNeedComplete If \c true, we only need the type to be complete, 6483 /// not defined. This only matters for enums with a fixed underlying 6484 /// type, since in all other cases, a type is complete if and only if it 6485 /// is defined. 6486 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 6487 bool OnlyNeedComplete) { 6488 // Easy case: if we don't have modules, all declarations are visible. 6489 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) 6490 return true; 6491 6492 // If this definition was instantiated from a template, map back to the 6493 // pattern from which it was instantiated. 6494 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { 6495 // We're in the middle of defining it; this definition should be treated 6496 // as visible. 6497 return true; 6498 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 6499 if (auto *Pattern = RD->getTemplateInstantiationPattern()) 6500 RD = Pattern; 6501 D = RD->getDefinition(); 6502 } else if (auto *ED = dyn_cast<EnumDecl>(D)) { 6503 while (auto *NewED = ED->getInstantiatedFromMemberEnum()) 6504 ED = NewED; 6505 if (OnlyNeedComplete && ED->isFixed()) { 6506 // If the enum has a fixed underlying type, and we're only looking for a 6507 // complete type (not a definition), any visible declaration of it will 6508 // do. 6509 *Suggested = nullptr; 6510 for (auto *Redecl : ED->redecls()) { 6511 if (isVisible(Redecl)) 6512 return true; 6513 if (Redecl->isThisDeclarationADefinition() || 6514 (Redecl->isCanonicalDecl() && !*Suggested)) 6515 *Suggested = Redecl; 6516 } 6517 return false; 6518 } 6519 D = ED->getDefinition(); 6520 } 6521 assert(D && "missing definition for pattern of instantiated definition"); 6522 6523 *Suggested = D; 6524 if (isVisible(D)) 6525 return true; 6526 6527 // The external source may have additional definitions of this type that are 6528 // visible, so complete the redeclaration chain now and ask again. 6529 if (auto *Source = Context.getExternalSource()) { 6530 Source->CompleteRedeclChain(D); 6531 return isVisible(D); 6532 } 6533 6534 return false; 6535 } 6536 6537 /// Locks in the inheritance model for the given class and all of its bases. 6538 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { 6539 RD = RD->getMostRecentDecl(); 6540 if (!RD->hasAttr<MSInheritanceAttr>()) { 6541 MSInheritanceAttr::Spelling IM; 6542 6543 switch (S.MSPointerToMemberRepresentationMethod) { 6544 case LangOptions::PPTMK_BestCase: 6545 IM = RD->calculateInheritanceModel(); 6546 break; 6547 case LangOptions::PPTMK_FullGeneralitySingleInheritance: 6548 IM = MSInheritanceAttr::Keyword_single_inheritance; 6549 break; 6550 case LangOptions::PPTMK_FullGeneralityMultipleInheritance: 6551 IM = MSInheritanceAttr::Keyword_multiple_inheritance; 6552 break; 6553 case LangOptions::PPTMK_FullGeneralityVirtualInheritance: 6554 IM = MSInheritanceAttr::Keyword_unspecified_inheritance; 6555 break; 6556 } 6557 6558 RD->addAttr(MSInheritanceAttr::CreateImplicit( 6559 S.getASTContext(), IM, 6560 /*BestCase=*/S.MSPointerToMemberRepresentationMethod == 6561 LangOptions::PPTMK_BestCase, 6562 S.ImplicitMSInheritanceAttrLoc.isValid() 6563 ? S.ImplicitMSInheritanceAttrLoc 6564 : RD->getSourceRange())); 6565 } 6566 } 6567 6568 /// \brief The implementation of RequireCompleteType 6569 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 6570 TypeDiagnoser *Diagnoser) { 6571 // FIXME: Add this assertion to make sure we always get instantiation points. 6572 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 6573 // FIXME: Add this assertion to help us flush out problems with 6574 // checking for dependent types and type-dependent expressions. 6575 // 6576 // assert(!T->isDependentType() && 6577 // "Can't ask whether a dependent type is complete"); 6578 6579 // We lock in the inheritance model once somebody has asked us to ensure 6580 // that a pointer-to-member type is complete. 6581 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 6582 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { 6583 if (!MPTy->getClass()->isDependentType()) { 6584 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); 6585 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); 6586 } 6587 } 6588 } 6589 6590 // If we have a complete type, we're done. 6591 NamedDecl *Def = nullptr; 6592 if (!T->isIncompleteType(&Def)) { 6593 // If we know about the definition but it is not visible, complain. 6594 NamedDecl *SuggestedDef = nullptr; 6595 if (Def && 6596 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { 6597 // If the user is going to see an error here, recover by making the 6598 // definition visible. 6599 bool TreatAsComplete = Diagnoser && !isSFINAEContext(); 6600 if (Diagnoser) 6601 diagnoseMissingImport(Loc, SuggestedDef, /*NeedDefinition*/true, 6602 /*Recover*/TreatAsComplete); 6603 return !TreatAsComplete; 6604 } 6605 6606 return false; 6607 } 6608 6609 const TagType *Tag = T->getAs<TagType>(); 6610 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>(); 6611 6612 // If there's an unimported definition of this type in a module (for 6613 // instance, because we forward declared it, then imported the definition), 6614 // import that definition now. 6615 // 6616 // FIXME: What about other cases where an import extends a redeclaration 6617 // chain for a declaration that can be accessed through a mechanism other 6618 // than name lookup (eg, referenced in a template, or a variable whose type 6619 // could be completed by the module)? 6620 // 6621 // FIXME: Should we map through to the base array element type before 6622 // checking for a tag type? 6623 if (Tag || IFace) { 6624 NamedDecl *D = 6625 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl(); 6626 6627 // Avoid diagnosing invalid decls as incomplete. 6628 if (D->isInvalidDecl()) 6629 return true; 6630 6631 // Give the external AST source a chance to complete the type. 6632 if (auto *Source = Context.getExternalSource()) { 6633 if (Tag) 6634 Source->CompleteType(Tag->getDecl()); 6635 else 6636 Source->CompleteType(IFace->getDecl()); 6637 6638 // If the external source completed the type, go through the motions 6639 // again to ensure we're allowed to use the completed type. 6640 if (!T->isIncompleteType()) 6641 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 6642 } 6643 } 6644 6645 // If we have a class template specialization or a class member of a 6646 // class template specialization, or an array with known size of such, 6647 // try to instantiate it. 6648 QualType MaybeTemplate = T; 6649 while (const ConstantArrayType *Array 6650 = Context.getAsConstantArrayType(MaybeTemplate)) 6651 MaybeTemplate = Array->getElementType(); 6652 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 6653 bool Instantiated = false; 6654 bool Diagnosed = false; 6655 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 6656 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 6657 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 6658 Diagnosed = InstantiateClassTemplateSpecialization( 6659 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, 6660 /*Complain=*/Diagnoser); 6661 Instantiated = true; 6662 } 6663 } else if (CXXRecordDecl *Rec 6664 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 6665 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass(); 6666 if (!Rec->isBeingDefined() && Pattern) { 6667 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo(); 6668 assert(MSI && "Missing member specialization information?"); 6669 // This record was instantiated from a class within a template. 6670 if (MSI->getTemplateSpecializationKind() != 6671 TSK_ExplicitSpecialization) { 6672 Diagnosed = InstantiateClass(Loc, Rec, Pattern, 6673 getTemplateInstantiationArgs(Rec), 6674 TSK_ImplicitInstantiation, 6675 /*Complain=*/Diagnoser); 6676 Instantiated = true; 6677 } 6678 } 6679 } 6680 6681 if (Instantiated) { 6682 // Instantiate* might have already complained that the template is not 6683 // defined, if we asked it to. 6684 if (Diagnoser && Diagnosed) 6685 return true; 6686 // If we instantiated a definition, check that it's usable, even if 6687 // instantiation produced an error, so that repeated calls to this 6688 // function give consistent answers. 6689 if (!T->isIncompleteType()) 6690 return RequireCompleteTypeImpl(Loc, T, Diagnoser); 6691 } 6692 } 6693 6694 if (!Diagnoser) 6695 return true; 6696 6697 // We have an incomplete type. Produce a diagnostic. 6698 if (Ident___float128 && 6699 T == Context.getTypeDeclType(Context.getFloat128StubType())) { 6700 Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128); 6701 return true; 6702 } 6703 6704 Diagnoser->diagnose(*this, Loc, T); 6705 6706 // If the type was a forward declaration of a class/struct/union 6707 // type, produce a note. 6708 if (Tag && !Tag->getDecl()->isInvalidDecl()) 6709 Diag(Tag->getDecl()->getLocation(), 6710 Tag->isBeingDefined() ? diag::note_type_being_defined 6711 : diag::note_forward_declaration) 6712 << QualType(Tag, 0); 6713 6714 // If the Objective-C class was a forward declaration, produce a note. 6715 if (IFace && !IFace->getDecl()->isInvalidDecl()) 6716 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class); 6717 6718 // If we have external information that we can use to suggest a fix, 6719 // produce a note. 6720 if (ExternalSource) 6721 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); 6722 6723 return true; 6724 } 6725 6726 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 6727 unsigned DiagID) { 6728 BoundTypeDiagnoser<> Diagnoser(DiagID); 6729 return RequireCompleteType(Loc, T, Diagnoser); 6730 } 6731 6732 /// \brief Get diagnostic %select index for tag kind for 6733 /// literal type diagnostic message. 6734 /// WARNING: Indexes apply to particular diagnostics only! 6735 /// 6736 /// \returns diagnostic %select index. 6737 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 6738 switch (Tag) { 6739 case TTK_Struct: return 0; 6740 case TTK_Interface: return 1; 6741 case TTK_Class: return 2; 6742 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 6743 } 6744 } 6745 6746 /// @brief Ensure that the type T is a literal type. 6747 /// 6748 /// This routine checks whether the type @p T is a literal type. If @p T is an 6749 /// incomplete type, an attempt is made to complete it. If @p T is a literal 6750 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 6751 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 6752 /// it the type @p T), along with notes explaining why the type is not a 6753 /// literal type, and returns true. 6754 /// 6755 /// @param Loc The location in the source that the non-literal type 6756 /// diagnostic should refer to. 6757 /// 6758 /// @param T The type that this routine is examining for literalness. 6759 /// 6760 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 6761 /// 6762 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 6763 /// @c false otherwise. 6764 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 6765 TypeDiagnoser &Diagnoser) { 6766 assert(!T->isDependentType() && "type should not be dependent"); 6767 6768 QualType ElemType = Context.getBaseElementType(T); 6769 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && 6770 T->isLiteralType(Context)) 6771 return false; 6772 6773 Diagnoser.diagnose(*this, Loc, T); 6774 6775 if (T->isVariableArrayType()) 6776 return true; 6777 6778 const RecordType *RT = ElemType->getAs<RecordType>(); 6779 if (!RT) 6780 return true; 6781 6782 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 6783 6784 // A partially-defined class type can't be a literal type, because a literal 6785 // class type must have a trivial destructor (which can't be checked until 6786 // the class definition is complete). 6787 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) 6788 return true; 6789 6790 // If the class has virtual base classes, then it's not an aggregate, and 6791 // cannot have any constexpr constructors or a trivial default constructor, 6792 // so is non-literal. This is better to diagnose than the resulting absence 6793 // of constexpr constructors. 6794 if (RD->getNumVBases()) { 6795 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 6796 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 6797 for (const auto &I : RD->vbases()) 6798 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here) 6799 << I.getSourceRange(); 6800 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 6801 !RD->hasTrivialDefaultConstructor()) { 6802 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 6803 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 6804 for (const auto &I : RD->bases()) { 6805 if (!I.getType()->isLiteralType(Context)) { 6806 Diag(I.getLocStart(), 6807 diag::note_non_literal_base_class) 6808 << RD << I.getType() << I.getSourceRange(); 6809 return true; 6810 } 6811 } 6812 for (const auto *I : RD->fields()) { 6813 if (!I->getType()->isLiteralType(Context) || 6814 I->getType().isVolatileQualified()) { 6815 Diag(I->getLocation(), diag::note_non_literal_field) 6816 << RD << I << I->getType() 6817 << I->getType().isVolatileQualified(); 6818 return true; 6819 } 6820 } 6821 } else if (!RD->hasTrivialDestructor()) { 6822 // All fields and bases are of literal types, so have trivial destructors. 6823 // If this class's destructor is non-trivial it must be user-declared. 6824 CXXDestructorDecl *Dtor = RD->getDestructor(); 6825 assert(Dtor && "class has literal fields and bases but no dtor?"); 6826 if (!Dtor) 6827 return true; 6828 6829 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 6830 diag::note_non_literal_user_provided_dtor : 6831 diag::note_non_literal_nontrivial_dtor) << RD; 6832 if (!Dtor->isUserProvided()) 6833 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true); 6834 } 6835 6836 return true; 6837 } 6838 6839 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 6840 BoundTypeDiagnoser<> Diagnoser(DiagID); 6841 return RequireLiteralType(Loc, T, Diagnoser); 6842 } 6843 6844 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 6845 /// and qualified by the nested-name-specifier contained in SS. 6846 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 6847 const CXXScopeSpec &SS, QualType T) { 6848 if (T.isNull()) 6849 return T; 6850 NestedNameSpecifier *NNS; 6851 if (SS.isValid()) 6852 NNS = SS.getScopeRep(); 6853 else { 6854 if (Keyword == ETK_None) 6855 return T; 6856 NNS = nullptr; 6857 } 6858 return Context.getElaboratedType(Keyword, NNS, T); 6859 } 6860 6861 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 6862 ExprResult ER = CheckPlaceholderExpr(E); 6863 if (ER.isInvalid()) return QualType(); 6864 E = ER.get(); 6865 6866 if (!getLangOpts().CPlusPlus && E->refersToBitField()) 6867 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; 6868 6869 if (!E->isTypeDependent()) { 6870 QualType T = E->getType(); 6871 if (const TagType *TT = T->getAs<TagType>()) 6872 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 6873 } 6874 return Context.getTypeOfExprType(E); 6875 } 6876 6877 /// getDecltypeForExpr - Given an expr, will return the decltype for 6878 /// that expression, according to the rules in C++11 6879 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 6880 static QualType getDecltypeForExpr(Sema &S, Expr *E) { 6881 if (E->isTypeDependent()) 6882 return S.Context.DependentTy; 6883 6884 // C++11 [dcl.type.simple]p4: 6885 // The type denoted by decltype(e) is defined as follows: 6886 // 6887 // - if e is an unparenthesized id-expression or an unparenthesized class 6888 // member access (5.2.5), decltype(e) is the type of the entity named 6889 // by e. If there is no such entity, or if e names a set of overloaded 6890 // functions, the program is ill-formed; 6891 // 6892 // We apply the same rules for Objective-C ivar and property references. 6893 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 6894 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 6895 return VD->getType(); 6896 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 6897 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 6898 return FD->getType(); 6899 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { 6900 return IR->getDecl()->getType(); 6901 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { 6902 if (PR->isExplicitProperty()) 6903 return PR->getExplicitProperty()->getType(); 6904 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) { 6905 return PE->getType(); 6906 } 6907 6908 // C++11 [expr.lambda.prim]p18: 6909 // Every occurrence of decltype((x)) where x is a possibly 6910 // parenthesized id-expression that names an entity of automatic 6911 // storage duration is treated as if x were transformed into an 6912 // access to a corresponding data member of the closure type that 6913 // would have been declared if x were an odr-use of the denoted 6914 // entity. 6915 using namespace sema; 6916 if (S.getCurLambda()) { 6917 if (isa<ParenExpr>(E)) { 6918 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 6919 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 6920 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); 6921 if (!T.isNull()) 6922 return S.Context.getLValueReferenceType(T); 6923 } 6924 } 6925 } 6926 } 6927 6928 6929 // C++11 [dcl.type.simple]p4: 6930 // [...] 6931 QualType T = E->getType(); 6932 switch (E->getValueKind()) { 6933 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 6934 // type of e; 6935 case VK_XValue: T = S.Context.getRValueReferenceType(T); break; 6936 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 6937 // type of e; 6938 case VK_LValue: T = S.Context.getLValueReferenceType(T); break; 6939 // - otherwise, decltype(e) is the type of e. 6940 case VK_RValue: break; 6941 } 6942 6943 return T; 6944 } 6945 6946 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc, 6947 bool AsUnevaluated) { 6948 ExprResult ER = CheckPlaceholderExpr(E); 6949 if (ER.isInvalid()) return QualType(); 6950 E = ER.get(); 6951 6952 if (AsUnevaluated && ActiveTemplateInstantiations.empty() && 6953 E->HasSideEffects(Context, false)) { 6954 // The expression operand for decltype is in an unevaluated expression 6955 // context, so side effects could result in unintended consequences. 6956 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 6957 } 6958 6959 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); 6960 } 6961 6962 QualType Sema::BuildUnaryTransformType(QualType BaseType, 6963 UnaryTransformType::UTTKind UKind, 6964 SourceLocation Loc) { 6965 switch (UKind) { 6966 case UnaryTransformType::EnumUnderlyingType: 6967 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 6968 Diag(Loc, diag::err_only_enums_have_underlying_types); 6969 return QualType(); 6970 } else { 6971 QualType Underlying = BaseType; 6972 if (!BaseType->isDependentType()) { 6973 // The enum could be incomplete if we're parsing its definition or 6974 // recovering from an error. 6975 NamedDecl *FwdDecl = nullptr; 6976 if (BaseType->isIncompleteType(&FwdDecl)) { 6977 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; 6978 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; 6979 return QualType(); 6980 } 6981 6982 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 6983 assert(ED && "EnumType has no EnumDecl"); 6984 6985 DiagnoseUseOfDecl(ED, Loc); 6986 6987 Underlying = ED->getIntegerType(); 6988 assert(!Underlying.isNull()); 6989 } 6990 return Context.getUnaryTransformType(BaseType, Underlying, 6991 UnaryTransformType::EnumUnderlyingType); 6992 } 6993 } 6994 llvm_unreachable("unknown unary transform type"); 6995 } 6996 6997 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 6998 if (!T->isDependentType()) { 6999 // FIXME: It isn't entirely clear whether incomplete atomic types 7000 // are allowed or not; for simplicity, ban them for the moment. 7001 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 7002 return QualType(); 7003 7004 int DisallowedKind = -1; 7005 if (T->isArrayType()) 7006 DisallowedKind = 1; 7007 else if (T->isFunctionType()) 7008 DisallowedKind = 2; 7009 else if (T->isReferenceType()) 7010 DisallowedKind = 3; 7011 else if (T->isAtomicType()) 7012 DisallowedKind = 4; 7013 else if (T.hasQualifiers()) 7014 DisallowedKind = 5; 7015 else if (!T.isTriviallyCopyableType(Context)) 7016 // Some other non-trivially-copyable type (probably a C++ class) 7017 DisallowedKind = 6; 7018 7019 if (DisallowedKind != -1) { 7020 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 7021 return QualType(); 7022 } 7023 7024 // FIXME: Do we need any handling for ARC here? 7025 } 7026 7027 // Build the pointer type. 7028 return Context.getAtomicType(T); 7029 } 7030