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