1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements type-related semantic analysis. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/DeclTemplate.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/TypeLoc.h" 22 #include "clang/AST/TypeLocVisitor.h" 23 #include "clang/Basic/OpenCL.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Lex/Preprocessor.h" 27 #include "clang/Parse/ParseDiagnostic.h" 28 #include "clang/Sema/DeclSpec.h" 29 #include "clang/Sema/DelayedDiagnostic.h" 30 #include "clang/Sema/Lookup.h" 31 #include "clang/Sema/ScopeInfo.h" 32 #include "clang/Sema/Template.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include "llvm/Support/ErrorHandling.h" 36 using namespace clang; 37 38 /// isOmittedBlockReturnType - Return true if this declarator is missing a 39 /// return type because this is a omitted return type on a block literal. 40 static bool isOmittedBlockReturnType(const Declarator &D) { 41 if (D.getContext() != Declarator::BlockLiteralContext || 42 D.getDeclSpec().hasTypeSpecifier()) 43 return false; 44 45 if (D.getNumTypeObjects() == 0) 46 return true; // ^{ ... } 47 48 if (D.getNumTypeObjects() == 1 && 49 D.getTypeObject(0).Kind == DeclaratorChunk::Function) 50 return true; // ^(int X, float Y) { ... } 51 52 return false; 53 } 54 55 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which 56 /// doesn't apply to the given type. 57 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr, 58 QualType type) { 59 bool useExpansionLoc = false; 60 61 unsigned diagID = 0; 62 switch (attr.getKind()) { 63 case AttributeList::AT_ObjCGC: 64 diagID = diag::warn_pointer_attribute_wrong_type; 65 useExpansionLoc = true; 66 break; 67 68 case AttributeList::AT_ObjCOwnership: 69 diagID = diag::warn_objc_object_attribute_wrong_type; 70 useExpansionLoc = true; 71 break; 72 73 default: 74 // Assume everything else was a function attribute. 75 diagID = diag::warn_function_attribute_wrong_type; 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 if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) { 84 if (attr.getParameterName()->isStr("strong")) { 85 if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; 86 } else if (attr.getParameterName()->isStr("weak")) { 87 if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; 88 } 89 } 90 91 S.Diag(loc, diagID) << name << type; 92 } 93 94 // objc_gc applies to Objective-C pointers or, otherwise, to the 95 // smallest available pointer type (i.e. 'void*' in 'void**'). 96 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \ 97 case AttributeList::AT_ObjCGC: \ 98 case AttributeList::AT_ObjCOwnership 99 100 // Function type attributes. 101 #define FUNCTION_TYPE_ATTRS_CASELIST \ 102 case AttributeList::AT_NoReturn: \ 103 case AttributeList::AT_CDecl: \ 104 case AttributeList::AT_FastCall: \ 105 case AttributeList::AT_StdCall: \ 106 case AttributeList::AT_ThisCall: \ 107 case AttributeList::AT_Pascal: \ 108 case AttributeList::AT_Regparm: \ 109 case AttributeList::AT_Pcs: \ 110 case AttributeList::AT_PnaclCall: \ 111 case AttributeList::AT_IntelOclBicc \ 112 113 namespace { 114 /// An object which stores processing state for the entire 115 /// GetTypeForDeclarator process. 116 class TypeProcessingState { 117 Sema &sema; 118 119 /// The declarator being processed. 120 Declarator &declarator; 121 122 /// The index of the declarator chunk we're currently processing. 123 /// May be the total number of valid chunks, indicating the 124 /// DeclSpec. 125 unsigned chunkIndex; 126 127 /// Whether there are non-trivial modifications to the decl spec. 128 bool trivial; 129 130 /// Whether we saved the attributes in the decl spec. 131 bool hasSavedAttrs; 132 133 /// The original set of attributes on the DeclSpec. 134 SmallVector<AttributeList*, 2> savedAttrs; 135 136 /// A list of attributes to diagnose the uselessness of when the 137 /// processing is complete. 138 SmallVector<AttributeList*, 2> ignoredTypeAttrs; 139 140 public: 141 TypeProcessingState(Sema &sema, Declarator &declarator) 142 : sema(sema), declarator(declarator), 143 chunkIndex(declarator.getNumTypeObjects()), 144 trivial(true), hasSavedAttrs(false) {} 145 146 Sema &getSema() const { 147 return sema; 148 } 149 150 Declarator &getDeclarator() const { 151 return declarator; 152 } 153 154 bool isProcessingDeclSpec() const { 155 return chunkIndex == declarator.getNumTypeObjects(); 156 } 157 158 unsigned getCurrentChunkIndex() const { 159 return chunkIndex; 160 } 161 162 void setCurrentChunkIndex(unsigned idx) { 163 assert(idx <= declarator.getNumTypeObjects()); 164 chunkIndex = idx; 165 } 166 167 AttributeList *&getCurrentAttrListRef() const { 168 if (isProcessingDeclSpec()) 169 return getMutableDeclSpec().getAttributes().getListRef(); 170 return declarator.getTypeObject(chunkIndex).getAttrListRef(); 171 } 172 173 /// Save the current set of attributes on the DeclSpec. 174 void saveDeclSpecAttrs() { 175 // Don't try to save them multiple times. 176 if (hasSavedAttrs) return; 177 178 DeclSpec &spec = getMutableDeclSpec(); 179 for (AttributeList *attr = spec.getAttributes().getList(); attr; 180 attr = attr->getNext()) 181 savedAttrs.push_back(attr); 182 trivial &= savedAttrs.empty(); 183 hasSavedAttrs = true; 184 } 185 186 /// Record that we had nowhere to put the given type attribute. 187 /// We will diagnose such attributes later. 188 void addIgnoredTypeAttr(AttributeList &attr) { 189 ignoredTypeAttrs.push_back(&attr); 190 } 191 192 /// Diagnose all the ignored type attributes, given that the 193 /// declarator worked out to the given type. 194 void diagnoseIgnoredTypeAttrs(QualType type) const { 195 for (SmallVectorImpl<AttributeList*>::const_iterator 196 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end(); 197 i != e; ++i) 198 diagnoseBadTypeAttribute(getSema(), **i, type); 199 } 200 201 ~TypeProcessingState() { 202 if (trivial) return; 203 204 restoreDeclSpecAttrs(); 205 } 206 207 private: 208 DeclSpec &getMutableDeclSpec() const { 209 return const_cast<DeclSpec&>(declarator.getDeclSpec()); 210 } 211 212 void restoreDeclSpecAttrs() { 213 assert(hasSavedAttrs); 214 215 if (savedAttrs.empty()) { 216 getMutableDeclSpec().getAttributes().set(0); 217 return; 218 } 219 220 getMutableDeclSpec().getAttributes().set(savedAttrs[0]); 221 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i) 222 savedAttrs[i]->setNext(savedAttrs[i+1]); 223 savedAttrs.back()->setNext(0); 224 } 225 }; 226 227 /// Basically std::pair except that we really want to avoid an 228 /// implicit operator= for safety concerns. It's also a minor 229 /// link-time optimization for this to be a private type. 230 struct AttrAndList { 231 /// The attribute. 232 AttributeList &first; 233 234 /// The head of the list the attribute is currently in. 235 AttributeList *&second; 236 237 AttrAndList(AttributeList &attr, AttributeList *&head) 238 : first(attr), second(head) {} 239 }; 240 } 241 242 namespace llvm { 243 template <> struct isPodLike<AttrAndList> { 244 static const bool value = true; 245 }; 246 } 247 248 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) { 249 attr.setNext(head); 250 head = &attr; 251 } 252 253 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) { 254 if (head == &attr) { 255 head = attr.getNext(); 256 return; 257 } 258 259 AttributeList *cur = head; 260 while (true) { 261 assert(cur && cur->getNext() && "ran out of attrs?"); 262 if (cur->getNext() == &attr) { 263 cur->setNext(attr.getNext()); 264 return; 265 } 266 cur = cur->getNext(); 267 } 268 } 269 270 static void moveAttrFromListToList(AttributeList &attr, 271 AttributeList *&fromList, 272 AttributeList *&toList) { 273 spliceAttrOutOfList(attr, fromList); 274 spliceAttrIntoList(attr, toList); 275 } 276 277 /// The location of a type attribute. 278 enum TypeAttrLocation { 279 /// The attribute is in the decl-specifier-seq. 280 TAL_DeclSpec, 281 /// The attribute is part of a DeclaratorChunk. 282 TAL_DeclChunk, 283 /// The attribute is immediately after the declaration's name. 284 TAL_DeclName 285 }; 286 287 static void processTypeAttrs(TypeProcessingState &state, 288 QualType &type, TypeAttrLocation TAL, 289 AttributeList *attrs); 290 291 static bool handleFunctionTypeAttr(TypeProcessingState &state, 292 AttributeList &attr, 293 QualType &type); 294 295 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 296 AttributeList &attr, QualType &type); 297 298 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 299 AttributeList &attr, QualType &type); 300 301 static bool handleObjCPointerTypeAttr(TypeProcessingState &state, 302 AttributeList &attr, QualType &type) { 303 if (attr.getKind() == AttributeList::AT_ObjCGC) 304 return handleObjCGCTypeAttr(state, attr, type); 305 assert(attr.getKind() == AttributeList::AT_ObjCOwnership); 306 return handleObjCOwnershipTypeAttr(state, attr, type); 307 } 308 309 /// Given the index of a declarator chunk, check whether that chunk 310 /// directly specifies the return type of a function and, if so, find 311 /// an appropriate place for it. 312 /// 313 /// \param i - a notional index which the search will start 314 /// immediately inside 315 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, 316 unsigned i) { 317 assert(i <= declarator.getNumTypeObjects()); 318 319 DeclaratorChunk *result = 0; 320 321 // First, look inwards past parens for a function declarator. 322 for (; i != 0; --i) { 323 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); 324 switch (fnChunk.Kind) { 325 case DeclaratorChunk::Paren: 326 continue; 327 328 // If we find anything except a function, bail out. 329 case DeclaratorChunk::Pointer: 330 case DeclaratorChunk::BlockPointer: 331 case DeclaratorChunk::Array: 332 case DeclaratorChunk::Reference: 333 case DeclaratorChunk::MemberPointer: 334 return result; 335 336 // If we do find a function declarator, scan inwards from that, 337 // looking for a block-pointer declarator. 338 case DeclaratorChunk::Function: 339 for (--i; i != 0; --i) { 340 DeclaratorChunk &blockChunk = declarator.getTypeObject(i-1); 341 switch (blockChunk.Kind) { 342 case DeclaratorChunk::Paren: 343 case DeclaratorChunk::Pointer: 344 case DeclaratorChunk::Array: 345 case DeclaratorChunk::Function: 346 case DeclaratorChunk::Reference: 347 case DeclaratorChunk::MemberPointer: 348 continue; 349 case DeclaratorChunk::BlockPointer: 350 result = &blockChunk; 351 goto continue_outer; 352 } 353 llvm_unreachable("bad declarator chunk kind"); 354 } 355 356 // If we run out of declarators doing that, we're done. 357 return result; 358 } 359 llvm_unreachable("bad declarator chunk kind"); 360 361 // Okay, reconsider from our new point. 362 continue_outer: ; 363 } 364 365 // Ran out of chunks, bail out. 366 return result; 367 } 368 369 /// Given that an objc_gc attribute was written somewhere on a 370 /// declaration *other* than on the declarator itself (for which, use 371 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it 372 /// didn't apply in whatever position it was written in, try to move 373 /// it to a more appropriate position. 374 static void distributeObjCPointerTypeAttr(TypeProcessingState &state, 375 AttributeList &attr, 376 QualType type) { 377 Declarator &declarator = state.getDeclarator(); 378 379 // Move it to the outermost normal or block pointer declarator. 380 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 381 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 382 switch (chunk.Kind) { 383 case DeclaratorChunk::Pointer: 384 case DeclaratorChunk::BlockPointer: { 385 // But don't move an ARC ownership attribute to the return type 386 // of a block. 387 DeclaratorChunk *destChunk = 0; 388 if (state.isProcessingDeclSpec() && 389 attr.getKind() == AttributeList::AT_ObjCOwnership) 390 destChunk = maybeMovePastReturnType(declarator, i - 1); 391 if (!destChunk) destChunk = &chunk; 392 393 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 394 destChunk->getAttrListRef()); 395 return; 396 } 397 398 case DeclaratorChunk::Paren: 399 case DeclaratorChunk::Array: 400 continue; 401 402 // We may be starting at the return type of a block. 403 case DeclaratorChunk::Function: 404 if (state.isProcessingDeclSpec() && 405 attr.getKind() == AttributeList::AT_ObjCOwnership) { 406 if (DeclaratorChunk *dest = maybeMovePastReturnType(declarator, i)) { 407 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 408 dest->getAttrListRef()); 409 return; 410 } 411 } 412 goto error; 413 414 // Don't walk through these. 415 case DeclaratorChunk::Reference: 416 case DeclaratorChunk::MemberPointer: 417 goto error; 418 } 419 } 420 error: 421 422 diagnoseBadTypeAttribute(state.getSema(), attr, type); 423 } 424 425 /// Distribute an objc_gc type attribute that was written on the 426 /// declarator. 427 static void 428 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, 429 AttributeList &attr, 430 QualType &declSpecType) { 431 Declarator &declarator = state.getDeclarator(); 432 433 // objc_gc goes on the innermost pointer to something that's not a 434 // pointer. 435 unsigned innermost = -1U; 436 bool considerDeclSpec = true; 437 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 438 DeclaratorChunk &chunk = declarator.getTypeObject(i); 439 switch (chunk.Kind) { 440 case DeclaratorChunk::Pointer: 441 case DeclaratorChunk::BlockPointer: 442 innermost = i; 443 continue; 444 445 case DeclaratorChunk::Reference: 446 case DeclaratorChunk::MemberPointer: 447 case DeclaratorChunk::Paren: 448 case DeclaratorChunk::Array: 449 continue; 450 451 case DeclaratorChunk::Function: 452 considerDeclSpec = false; 453 goto done; 454 } 455 } 456 done: 457 458 // That might actually be the decl spec if we weren't blocked by 459 // anything in the declarator. 460 if (considerDeclSpec) { 461 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { 462 // Splice the attribute into the decl spec. Prevents the 463 // attribute from being applied multiple times and gives 464 // the source-location-filler something to work with. 465 state.saveDeclSpecAttrs(); 466 moveAttrFromListToList(attr, declarator.getAttrListRef(), 467 declarator.getMutableDeclSpec().getAttributes().getListRef()); 468 return; 469 } 470 } 471 472 // Otherwise, if we found an appropriate chunk, splice the attribute 473 // into it. 474 if (innermost != -1U) { 475 moveAttrFromListToList(attr, declarator.getAttrListRef(), 476 declarator.getTypeObject(innermost).getAttrListRef()); 477 return; 478 } 479 480 // Otherwise, diagnose when we're done building the type. 481 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 482 state.addIgnoredTypeAttr(attr); 483 } 484 485 /// A function type attribute was written somewhere in a declaration 486 /// *other* than on the declarator itself or in the decl spec. Given 487 /// that it didn't apply in whatever position it was written in, try 488 /// to move it to a more appropriate position. 489 static void distributeFunctionTypeAttr(TypeProcessingState &state, 490 AttributeList &attr, 491 QualType type) { 492 Declarator &declarator = state.getDeclarator(); 493 494 // Try to push the attribute from the return type of a function to 495 // the function itself. 496 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 497 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 498 switch (chunk.Kind) { 499 case DeclaratorChunk::Function: 500 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 501 chunk.getAttrListRef()); 502 return; 503 504 case DeclaratorChunk::Paren: 505 case DeclaratorChunk::Pointer: 506 case DeclaratorChunk::BlockPointer: 507 case DeclaratorChunk::Array: 508 case DeclaratorChunk::Reference: 509 case DeclaratorChunk::MemberPointer: 510 continue; 511 } 512 } 513 514 diagnoseBadTypeAttribute(state.getSema(), attr, type); 515 } 516 517 /// Try to distribute a function type attribute to the innermost 518 /// function chunk or type. Returns true if the attribute was 519 /// distributed, false if no location was found. 520 static bool 521 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, 522 AttributeList &attr, 523 AttributeList *&attrList, 524 QualType &declSpecType) { 525 Declarator &declarator = state.getDeclarator(); 526 527 // Put it on the innermost function chunk, if there is one. 528 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 529 DeclaratorChunk &chunk = declarator.getTypeObject(i); 530 if (chunk.Kind != DeclaratorChunk::Function) continue; 531 532 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef()); 533 return true; 534 } 535 536 if (handleFunctionTypeAttr(state, attr, declSpecType)) { 537 spliceAttrOutOfList(attr, attrList); 538 return true; 539 } 540 541 return false; 542 } 543 544 /// A function type attribute was written in the decl spec. Try to 545 /// apply it somewhere. 546 static void 547 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, 548 AttributeList &attr, 549 QualType &declSpecType) { 550 state.saveDeclSpecAttrs(); 551 552 // C++11 attributes before the decl specifiers actually appertain to 553 // the declarators. Move them straight there. We don't support the 554 // 'put them wherever you like' semantics we allow for GNU attributes. 555 if (attr.isCXX11Attribute()) { 556 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 557 state.getDeclarator().getAttrListRef()); 558 return; 559 } 560 561 // Try to distribute to the innermost. 562 if (distributeFunctionTypeAttrToInnermost(state, attr, 563 state.getCurrentAttrListRef(), 564 declSpecType)) 565 return; 566 567 // If that failed, diagnose the bad attribute when the declarator is 568 // fully built. 569 state.addIgnoredTypeAttr(attr); 570 } 571 572 /// A function type attribute was written on the declarator. Try to 573 /// apply it somewhere. 574 static void 575 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, 576 AttributeList &attr, 577 QualType &declSpecType) { 578 Declarator &declarator = state.getDeclarator(); 579 580 // Try to distribute to the innermost. 581 if (distributeFunctionTypeAttrToInnermost(state, attr, 582 declarator.getAttrListRef(), 583 declSpecType)) 584 return; 585 586 // If that failed, diagnose the bad attribute when the declarator is 587 // fully built. 588 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 589 state.addIgnoredTypeAttr(attr); 590 } 591 592 /// \brief Given that there are attributes written on the declarator 593 /// itself, try to distribute any type attributes to the appropriate 594 /// declarator chunk. 595 /// 596 /// These are attributes like the following: 597 /// int f ATTR; 598 /// int (f ATTR)(); 599 /// but not necessarily this: 600 /// int f() ATTR; 601 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, 602 QualType &declSpecType) { 603 // Collect all the type attributes from the declarator itself. 604 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!"); 605 AttributeList *attr = state.getDeclarator().getAttributes(); 606 AttributeList *next; 607 do { 608 next = attr->getNext(); 609 610 // Do not distribute C++11 attributes. They have strict rules for what 611 // they appertain to. 612 if (attr->isCXX11Attribute()) 613 continue; 614 615 switch (attr->getKind()) { 616 OBJC_POINTER_TYPE_ATTRS_CASELIST: 617 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType); 618 break; 619 620 case AttributeList::AT_NSReturnsRetained: 621 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 622 break; 623 // fallthrough 624 625 FUNCTION_TYPE_ATTRS_CASELIST: 626 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType); 627 break; 628 629 default: 630 break; 631 } 632 } while ((attr = next)); 633 } 634 635 /// Add a synthetic '()' to a block-literal declarator if it is 636 /// required, given the return type. 637 static void maybeSynthesizeBlockSignature(TypeProcessingState &state, 638 QualType declSpecType) { 639 Declarator &declarator = state.getDeclarator(); 640 641 // First, check whether the declarator would produce a function, 642 // i.e. whether the innermost semantic chunk is a function. 643 if (declarator.isFunctionDeclarator()) { 644 // If so, make that declarator a prototyped declarator. 645 declarator.getFunctionTypeInfo().hasPrototype = true; 646 return; 647 } 648 649 // If there are any type objects, the type as written won't name a 650 // function, regardless of the decl spec type. This is because a 651 // block signature declarator is always an abstract-declarator, and 652 // abstract-declarators can't just be parentheses chunks. Therefore 653 // we need to build a function chunk unless there are no type 654 // objects and the decl spec type is a function. 655 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) 656 return; 657 658 // Note that there *are* cases with invalid declarators where 659 // declarators consist solely of parentheses. In general, these 660 // occur only in failed efforts to make function declarators, so 661 // faking up the function chunk is still the right thing to do. 662 663 // Otherwise, we need to fake up a function declarator. 664 SourceLocation loc = declarator.getLocStart(); 665 666 // ...and *prepend* it to the declarator. 667 SourceLocation NoLoc; 668 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( 669 /*HasProto=*/true, 670 /*IsAmbiguous=*/false, 671 /*LParenLoc=*/NoLoc, 672 /*ArgInfo=*/0, 673 /*NumArgs=*/0, 674 /*EllipsisLoc=*/NoLoc, 675 /*RParenLoc=*/NoLoc, 676 /*TypeQuals=*/0, 677 /*RefQualifierIsLvalueRef=*/true, 678 /*RefQualifierLoc=*/NoLoc, 679 /*ConstQualifierLoc=*/NoLoc, 680 /*VolatileQualifierLoc=*/NoLoc, 681 /*MutableLoc=*/NoLoc, 682 EST_None, 683 /*ESpecLoc=*/NoLoc, 684 /*Exceptions=*/0, 685 /*ExceptionRanges=*/0, 686 /*NumExceptions=*/0, 687 /*NoexceptExpr=*/0, 688 loc, loc, declarator)); 689 690 // For consistency, make sure the state still has us as processing 691 // the decl spec. 692 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1); 693 state.setCurrentChunkIndex(declarator.getNumTypeObjects()); 694 } 695 696 /// \brief Convert the specified declspec to the appropriate type 697 /// object. 698 /// \param state Specifies the declarator containing the declaration specifier 699 /// to be converted, along with other associated processing state. 700 /// \returns The type described by the declaration specifiers. This function 701 /// never returns null. 702 static QualType ConvertDeclSpecToType(TypeProcessingState &state) { 703 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 704 // checking. 705 706 Sema &S = state.getSema(); 707 Declarator &declarator = state.getDeclarator(); 708 const DeclSpec &DS = declarator.getDeclSpec(); 709 SourceLocation DeclLoc = declarator.getIdentifierLoc(); 710 if (DeclLoc.isInvalid()) 711 DeclLoc = DS.getLocStart(); 712 713 ASTContext &Context = S.Context; 714 715 QualType Result; 716 switch (DS.getTypeSpecType()) { 717 case DeclSpec::TST_void: 718 Result = Context.VoidTy; 719 break; 720 case DeclSpec::TST_char: 721 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 722 Result = Context.CharTy; 723 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 724 Result = Context.SignedCharTy; 725 else { 726 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 727 "Unknown TSS value"); 728 Result = Context.UnsignedCharTy; 729 } 730 break; 731 case DeclSpec::TST_wchar: 732 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 733 Result = Context.WCharTy; 734 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 735 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 736 << DS.getSpecifierName(DS.getTypeSpecType()); 737 Result = Context.getSignedWCharType(); 738 } else { 739 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 740 "Unknown TSS value"); 741 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 742 << DS.getSpecifierName(DS.getTypeSpecType()); 743 Result = Context.getUnsignedWCharType(); 744 } 745 break; 746 case DeclSpec::TST_char16: 747 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 748 "Unknown TSS value"); 749 Result = Context.Char16Ty; 750 break; 751 case DeclSpec::TST_char32: 752 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 753 "Unknown TSS value"); 754 Result = Context.Char32Ty; 755 break; 756 case DeclSpec::TST_unspecified: 757 // "<proto1,proto2>" is an objc qualified ID with a missing id. 758 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 759 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 760 (ObjCProtocolDecl*const*)PQ, 761 DS.getNumProtocolQualifiers()); 762 Result = Context.getObjCObjectPointerType(Result); 763 break; 764 } 765 766 // If this is a missing declspec in a block literal return context, then it 767 // is inferred from the return statements inside the block. 768 // The declspec is always missing in a lambda expr context; it is either 769 // specified with a trailing return type or inferred. 770 if (declarator.getContext() == Declarator::LambdaExprContext || 771 isOmittedBlockReturnType(declarator)) { 772 Result = Context.DependentTy; 773 break; 774 } 775 776 // Unspecified typespec defaults to int in C90. However, the C90 grammar 777 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 778 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 779 // Note that the one exception to this is function definitions, which are 780 // allowed to be completely missing a declspec. This is handled in the 781 // parser already though by it pretending to have seen an 'int' in this 782 // case. 783 if (S.getLangOpts().ImplicitInt) { 784 // In C89 mode, we only warn if there is a completely missing declspec 785 // when one is not allowed. 786 if (DS.isEmpty()) { 787 S.Diag(DeclLoc, diag::ext_missing_declspec) 788 << DS.getSourceRange() 789 << FixItHint::CreateInsertion(DS.getLocStart(), "int"); 790 } 791 } else if (!DS.hasTypeSpecifier()) { 792 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 793 // "At least one type specifier shall be given in the declaration 794 // specifiers in each declaration, and in the specifier-qualifier list in 795 // each struct declaration and type name." 796 if (S.getLangOpts().CPlusPlus) { 797 S.Diag(DeclLoc, diag::err_missing_type_specifier) 798 << DS.getSourceRange(); 799 800 // When this occurs in C++ code, often something is very broken with the 801 // value being declared, poison it as invalid so we don't get chains of 802 // errors. 803 declarator.setInvalidType(true); 804 } else { 805 S.Diag(DeclLoc, diag::ext_missing_type_specifier) 806 << DS.getSourceRange(); 807 } 808 } 809 810 // FALL THROUGH. 811 case DeclSpec::TST_int: { 812 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 813 switch (DS.getTypeSpecWidth()) { 814 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 815 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 816 case DeclSpec::TSW_long: Result = Context.LongTy; break; 817 case DeclSpec::TSW_longlong: 818 Result = Context.LongLongTy; 819 820 // 'long long' is a C99 or C++11 feature. 821 if (!S.getLangOpts().C99) { 822 if (S.getLangOpts().CPlusPlus) 823 S.Diag(DS.getTypeSpecWidthLoc(), 824 S.getLangOpts().CPlusPlus11 ? 825 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 826 else 827 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 828 } 829 break; 830 } 831 } else { 832 switch (DS.getTypeSpecWidth()) { 833 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 834 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 835 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 836 case DeclSpec::TSW_longlong: 837 Result = Context.UnsignedLongLongTy; 838 839 // 'long long' is a C99 or C++11 feature. 840 if (!S.getLangOpts().C99) { 841 if (S.getLangOpts().CPlusPlus) 842 S.Diag(DS.getTypeSpecWidthLoc(), 843 S.getLangOpts().CPlusPlus11 ? 844 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 845 else 846 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); 847 } 848 break; 849 } 850 } 851 break; 852 } 853 case DeclSpec::TST_int128: 854 if (!S.PP.getTargetInfo().hasInt128Type()) 855 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported); 856 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) 857 Result = Context.UnsignedInt128Ty; 858 else 859 Result = Context.Int128Ty; 860 break; 861 case DeclSpec::TST_half: Result = Context.HalfTy; break; 862 case DeclSpec::TST_float: Result = Context.FloatTy; break; 863 case DeclSpec::TST_double: 864 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 865 Result = Context.LongDoubleTy; 866 else 867 Result = Context.DoubleTy; 868 869 if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) { 870 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64); 871 declarator.setInvalidType(true); 872 } 873 break; 874 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 875 case DeclSpec::TST_decimal32: // _Decimal32 876 case DeclSpec::TST_decimal64: // _Decimal64 877 case DeclSpec::TST_decimal128: // _Decimal128 878 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 879 Result = Context.IntTy; 880 declarator.setInvalidType(true); 881 break; 882 case DeclSpec::TST_class: 883 case DeclSpec::TST_enum: 884 case DeclSpec::TST_union: 885 case DeclSpec::TST_struct: 886 case DeclSpec::TST_interface: { 887 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl()); 888 if (!D) { 889 // This can happen in C++ with ambiguous lookups. 890 Result = Context.IntTy; 891 declarator.setInvalidType(true); 892 break; 893 } 894 895 // If the type is deprecated or unavailable, diagnose it. 896 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); 897 898 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 899 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!"); 900 901 // TypeQuals handled by caller. 902 Result = Context.getTypeDeclType(D); 903 904 // In both C and C++, make an ElaboratedType. 905 ElaboratedTypeKeyword Keyword 906 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); 907 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result); 908 break; 909 } 910 case DeclSpec::TST_typename: { 911 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 912 DS.getTypeSpecSign() == 0 && 913 "Can't handle qualifiers on typedef names yet!"); 914 Result = S.GetTypeFromParser(DS.getRepAsType()); 915 if (Result.isNull()) 916 declarator.setInvalidType(true); 917 else if (DeclSpec::ProtocolQualifierListTy PQ 918 = DS.getProtocolQualifiers()) { 919 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) { 920 // Silently drop any existing protocol qualifiers. 921 // TODO: determine whether that's the right thing to do. 922 if (ObjT->getNumProtocols()) 923 Result = ObjT->getBaseType(); 924 925 if (DS.getNumProtocolQualifiers()) 926 Result = Context.getObjCObjectType(Result, 927 (ObjCProtocolDecl*const*) PQ, 928 DS.getNumProtocolQualifiers()); 929 } else if (Result->isObjCIdType()) { 930 // id<protocol-list> 931 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 932 (ObjCProtocolDecl*const*) PQ, 933 DS.getNumProtocolQualifiers()); 934 Result = Context.getObjCObjectPointerType(Result); 935 } else if (Result->isObjCClassType()) { 936 // Class<protocol-list> 937 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 938 (ObjCProtocolDecl*const*) PQ, 939 DS.getNumProtocolQualifiers()); 940 Result = Context.getObjCObjectPointerType(Result); 941 } else { 942 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers) 943 << DS.getSourceRange(); 944 declarator.setInvalidType(true); 945 } 946 } 947 948 // TypeQuals handled by caller. 949 break; 950 } 951 case DeclSpec::TST_typeofType: 952 // FIXME: Preserve type source info. 953 Result = S.GetTypeFromParser(DS.getRepAsType()); 954 assert(!Result.isNull() && "Didn't get a type for typeof?"); 955 if (!Result->isDependentType()) 956 if (const TagType *TT = Result->getAs<TagType>()) 957 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); 958 // TypeQuals handled by caller. 959 Result = Context.getTypeOfType(Result); 960 break; 961 case DeclSpec::TST_typeofExpr: { 962 Expr *E = DS.getRepAsExpr(); 963 assert(E && "Didn't get an expression for typeof?"); 964 // TypeQuals handled by caller. 965 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); 966 if (Result.isNull()) { 967 Result = Context.IntTy; 968 declarator.setInvalidType(true); 969 } 970 break; 971 } 972 case DeclSpec::TST_decltype: { 973 Expr *E = DS.getRepAsExpr(); 974 assert(E && "Didn't get an expression for decltype?"); 975 // TypeQuals handled by caller. 976 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); 977 if (Result.isNull()) { 978 Result = Context.IntTy; 979 declarator.setInvalidType(true); 980 } 981 break; 982 } 983 case DeclSpec::TST_underlyingType: 984 Result = S.GetTypeFromParser(DS.getRepAsType()); 985 assert(!Result.isNull() && "Didn't get a type for __underlying_type?"); 986 Result = S.BuildUnaryTransformType(Result, 987 UnaryTransformType::EnumUnderlyingType, 988 DS.getTypeSpecTypeLoc()); 989 if (Result.isNull()) { 990 Result = Context.IntTy; 991 declarator.setInvalidType(true); 992 } 993 break; 994 995 case DeclSpec::TST_auto: 996 // TypeQuals handled by caller. 997 Result = Context.getAutoType(QualType(), /*decltype(auto)*/false); 998 break; 999 1000 case DeclSpec::TST_decltype_auto: 1001 Result = Context.getAutoType(QualType(), /*decltype(auto)*/true); 1002 break; 1003 1004 case DeclSpec::TST_unknown_anytype: 1005 Result = Context.UnknownAnyTy; 1006 break; 1007 1008 case DeclSpec::TST_atomic: 1009 Result = S.GetTypeFromParser(DS.getRepAsType()); 1010 assert(!Result.isNull() && "Didn't get a type for _Atomic?"); 1011 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); 1012 if (Result.isNull()) { 1013 Result = Context.IntTy; 1014 declarator.setInvalidType(true); 1015 } 1016 break; 1017 1018 case DeclSpec::TST_image1d_t: 1019 Result = Context.OCLImage1dTy; 1020 break; 1021 1022 case DeclSpec::TST_image1d_array_t: 1023 Result = Context.OCLImage1dArrayTy; 1024 break; 1025 1026 case DeclSpec::TST_image1d_buffer_t: 1027 Result = Context.OCLImage1dBufferTy; 1028 break; 1029 1030 case DeclSpec::TST_image2d_t: 1031 Result = Context.OCLImage2dTy; 1032 break; 1033 1034 case DeclSpec::TST_image2d_array_t: 1035 Result = Context.OCLImage2dArrayTy; 1036 break; 1037 1038 case DeclSpec::TST_image3d_t: 1039 Result = Context.OCLImage3dTy; 1040 break; 1041 1042 case DeclSpec::TST_sampler_t: 1043 Result = Context.OCLSamplerTy; 1044 break; 1045 1046 case DeclSpec::TST_event_t: 1047 Result = Context.OCLEventTy; 1048 break; 1049 1050 case DeclSpec::TST_error: 1051 Result = Context.IntTy; 1052 declarator.setInvalidType(true); 1053 break; 1054 } 1055 1056 // Handle complex types. 1057 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 1058 if (S.getLangOpts().Freestanding) 1059 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 1060 Result = Context.getComplexType(Result); 1061 } else if (DS.isTypeAltiVecVector()) { 1062 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); 1063 assert(typeSize > 0 && "type size for vector must be greater than 0 bits"); 1064 VectorType::VectorKind VecKind = VectorType::AltiVecVector; 1065 if (DS.isTypeAltiVecPixel()) 1066 VecKind = VectorType::AltiVecPixel; 1067 else if (DS.isTypeAltiVecBool()) 1068 VecKind = VectorType::AltiVecBool; 1069 Result = Context.getVectorType(Result, 128/typeSize, VecKind); 1070 } 1071 1072 // FIXME: Imaginary. 1073 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) 1074 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); 1075 1076 // Before we process any type attributes, synthesize a block literal 1077 // function declarator if necessary. 1078 if (declarator.getContext() == Declarator::BlockLiteralContext) 1079 maybeSynthesizeBlockSignature(state, Result); 1080 1081 // Apply any type attributes from the decl spec. This may cause the 1082 // list of type attributes to be temporarily saved while the type 1083 // attributes are pushed around. 1084 if (AttributeList *attrs = DS.getAttributes().getList()) 1085 processTypeAttrs(state, Result, TAL_DeclSpec, attrs); 1086 1087 // Apply const/volatile/restrict qualifiers to T. 1088 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 1089 1090 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification 1091 // of a function type includes any type qualifiers, the behavior is 1092 // undefined." 1093 if (Result->isFunctionType() && TypeQuals) { 1094 if (TypeQuals & DeclSpec::TQ_const) 1095 S.Diag(DS.getConstSpecLoc(), diag::warn_typecheck_function_qualifiers) 1096 << Result << DS.getSourceRange(); 1097 else if (TypeQuals & DeclSpec::TQ_volatile) 1098 S.Diag(DS.getVolatileSpecLoc(), diag::warn_typecheck_function_qualifiers) 1099 << Result << DS.getSourceRange(); 1100 else { 1101 assert((TypeQuals & (DeclSpec::TQ_restrict | DeclSpec::TQ_atomic)) && 1102 "Has CVRA quals but not C, V, R, or A?"); 1103 // No diagnostic; we'll diagnose 'restrict' or '_Atomic' applied to a 1104 // function type later, in BuildQualifiedType. 1105 } 1106 } 1107 1108 // C++ [dcl.ref]p1: 1109 // Cv-qualified references are ill-formed except when the 1110 // cv-qualifiers are introduced through the use of a typedef 1111 // (7.1.3) or of a template type argument (14.3), in which 1112 // case the cv-qualifiers are ignored. 1113 // FIXME: Shouldn't we be checking SCS_typedef here? 1114 if (DS.getTypeSpecType() == DeclSpec::TST_typename && 1115 TypeQuals && Result->isReferenceType()) { 1116 TypeQuals &= ~DeclSpec::TQ_const; 1117 TypeQuals &= ~DeclSpec::TQ_volatile; 1118 TypeQuals &= ~DeclSpec::TQ_atomic; 1119 } 1120 1121 // C90 6.5.3 constraints: "The same type qualifier shall not appear more 1122 // than once in the same specifier-list or qualifier-list, either directly 1123 // or via one or more typedefs." 1124 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus 1125 && TypeQuals & Result.getCVRQualifiers()) { 1126 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { 1127 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) 1128 << "const"; 1129 } 1130 1131 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { 1132 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) 1133 << "volatile"; 1134 } 1135 1136 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to 1137 // produce a warning in this case. 1138 } 1139 1140 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS); 1141 1142 // If adding qualifiers fails, just use the unqualified type. 1143 if (Qualified.isNull()) 1144 declarator.setInvalidType(true); 1145 else 1146 Result = Qualified; 1147 } 1148 1149 return Result; 1150 } 1151 1152 static std::string getPrintableNameForEntity(DeclarationName Entity) { 1153 if (Entity) 1154 return Entity.getAsString(); 1155 1156 return "type name"; 1157 } 1158 1159 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 1160 Qualifiers Qs, const DeclSpec *DS) { 1161 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 1162 // object or incomplete types shall not be restrict-qualified." 1163 if (Qs.hasRestrict()) { 1164 unsigned DiagID = 0; 1165 QualType ProblemTy; 1166 1167 if (T->isAnyPointerType() || T->isReferenceType() || 1168 T->isMemberPointerType()) { 1169 QualType EltTy; 1170 if (T->isObjCObjectPointerType()) 1171 EltTy = T; 1172 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) 1173 EltTy = PTy->getPointeeType(); 1174 else 1175 EltTy = T->getPointeeType(); 1176 1177 // If we have a pointer or reference, the pointee must have an object 1178 // incomplete type. 1179 if (!EltTy->isIncompleteOrObjectType()) { 1180 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 1181 ProblemTy = EltTy; 1182 } 1183 } else if (!T->isDependentType()) { 1184 DiagID = diag::err_typecheck_invalid_restrict_not_pointer; 1185 ProblemTy = T; 1186 } 1187 1188 if (DiagID) { 1189 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; 1190 Qs.removeRestrict(); 1191 } 1192 } 1193 1194 return Context.getQualifiedType(T, Qs); 1195 } 1196 1197 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 1198 unsigned CVRA, const DeclSpec *DS) { 1199 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic. 1200 unsigned CVR = CVRA & ~DeclSpec::TQ_atomic; 1201 1202 // C11 6.7.3/5: 1203 // If the same qualifier appears more than once in the same 1204 // specifier-qualifier-list, either directly or via one or more typedefs, 1205 // the behavior is the same as if it appeared only once. 1206 // 1207 // It's not specified what happens when the _Atomic qualifier is applied to 1208 // a type specified with the _Atomic specifier, but we assume that this 1209 // should be treated as if the _Atomic qualifier appeared multiple times. 1210 if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) { 1211 // C11 6.7.3/5: 1212 // If other qualifiers appear along with the _Atomic qualifier in a 1213 // specifier-qualifier-list, the resulting type is the so-qualified 1214 // atomic type. 1215 // 1216 // Don't need to worry about array types here, since _Atomic can't be 1217 // applied to such types. 1218 SplitQualType Split = T.getSplitUnqualifiedType(); 1219 T = BuildAtomicType(QualType(Split.Ty, 0), 1220 DS ? DS->getAtomicSpecLoc() : Loc); 1221 if (T.isNull()) 1222 return T; 1223 Split.Quals.addCVRQualifiers(CVR); 1224 return BuildQualifiedType(T, Loc, Split.Quals); 1225 } 1226 1227 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS); 1228 } 1229 1230 /// \brief Build a paren type including \p T. 1231 QualType Sema::BuildParenType(QualType T) { 1232 return Context.getParenType(T); 1233 } 1234 1235 /// Given that we're building a pointer or reference to the given 1236 static QualType inferARCLifetimeForPointee(Sema &S, QualType type, 1237 SourceLocation loc, 1238 bool isReference) { 1239 // Bail out if retention is unrequired or already specified. 1240 if (!type->isObjCLifetimeType() || 1241 type.getObjCLifetime() != Qualifiers::OCL_None) 1242 return type; 1243 1244 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; 1245 1246 // If the object type is const-qualified, we can safely use 1247 // __unsafe_unretained. This is safe (because there are no read 1248 // barriers), and it'll be safe to coerce anything but __weak* to 1249 // the resulting type. 1250 if (type.isConstQualified()) { 1251 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1252 1253 // Otherwise, check whether the static type does not require 1254 // retaining. This currently only triggers for Class (possibly 1255 // protocol-qualifed, and arrays thereof). 1256 } else if (type->isObjCARCImplicitlyUnretainedType()) { 1257 implicitLifetime = Qualifiers::OCL_ExplicitNone; 1258 1259 // If we are in an unevaluated context, like sizeof, skip adding a 1260 // qualification. 1261 } else if (S.isUnevaluatedContext()) { 1262 return type; 1263 1264 // If that failed, give an error and recover using __strong. __strong 1265 // is the option most likely to prevent spurious second-order diagnostics, 1266 // like when binding a reference to a field. 1267 } else { 1268 // These types can show up in private ivars in system headers, so 1269 // we need this to not be an error in those cases. Instead we 1270 // want to delay. 1271 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 1272 S.DelayedDiagnostics.add( 1273 sema::DelayedDiagnostic::makeForbiddenType(loc, 1274 diag::err_arc_indirect_no_ownership, type, isReference)); 1275 } else { 1276 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; 1277 } 1278 implicitLifetime = Qualifiers::OCL_Strong; 1279 } 1280 assert(implicitLifetime && "didn't infer any lifetime!"); 1281 1282 Qualifiers qs; 1283 qs.addObjCLifetime(implicitLifetime); 1284 return S.Context.getQualifiedType(type, qs); 1285 } 1286 1287 /// \brief Build a pointer type. 1288 /// 1289 /// \param T The type to which we'll be building a pointer. 1290 /// 1291 /// \param Loc The location of the entity whose type involves this 1292 /// pointer type or, if there is no such entity, the location of the 1293 /// type that will have pointer type. 1294 /// 1295 /// \param Entity The name of the entity that involves the pointer 1296 /// type, if known. 1297 /// 1298 /// \returns A suitable pointer type, if there are no 1299 /// errors. Otherwise, returns a NULL type. 1300 QualType Sema::BuildPointerType(QualType T, 1301 SourceLocation Loc, DeclarationName Entity) { 1302 if (T->isReferenceType()) { 1303 // C++ 8.3.2p4: There shall be no ... pointers to references ... 1304 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 1305 << getPrintableNameForEntity(Entity) << T; 1306 return QualType(); 1307 } 1308 1309 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType"); 1310 1311 // In ARC, it is forbidden to build pointers to unqualified pointers. 1312 if (getLangOpts().ObjCAutoRefCount) 1313 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); 1314 1315 // Build the pointer type. 1316 return Context.getPointerType(T); 1317 } 1318 1319 /// \brief Build a reference type. 1320 /// 1321 /// \param T The type to which we'll be building a reference. 1322 /// 1323 /// \param Loc The location of the entity whose type involves this 1324 /// reference type or, if there is no such entity, the location of the 1325 /// type that will have reference type. 1326 /// 1327 /// \param Entity The name of the entity that involves the reference 1328 /// type, if known. 1329 /// 1330 /// \returns A suitable reference type, if there are no 1331 /// errors. Otherwise, returns a NULL type. 1332 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, 1333 SourceLocation Loc, 1334 DeclarationName Entity) { 1335 assert(Context.getCanonicalType(T) != Context.OverloadTy && 1336 "Unresolved overloaded function type"); 1337 1338 // C++0x [dcl.ref]p6: 1339 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a 1340 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a 1341 // type T, an attempt to create the type "lvalue reference to cv TR" creates 1342 // the type "lvalue reference to T", while an attempt to create the type 1343 // "rvalue reference to cv TR" creates the type TR. 1344 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); 1345 1346 // C++ [dcl.ref]p4: There shall be no references to references. 1347 // 1348 // According to C++ DR 106, references to references are only 1349 // diagnosed when they are written directly (e.g., "int & &"), 1350 // but not when they happen via a typedef: 1351 // 1352 // typedef int& intref; 1353 // typedef intref& intref2; 1354 // 1355 // Parser::ParseDeclaratorInternal diagnoses the case where 1356 // references are written directly; here, we handle the 1357 // collapsing of references-to-references as described in C++0x. 1358 // DR 106 and 540 introduce reference-collapsing into C++98/03. 1359 1360 // C++ [dcl.ref]p1: 1361 // A declarator that specifies the type "reference to cv void" 1362 // is ill-formed. 1363 if (T->isVoidType()) { 1364 Diag(Loc, diag::err_reference_to_void); 1365 return QualType(); 1366 } 1367 1368 // In ARC, it is forbidden to build references to unqualified pointers. 1369 if (getLangOpts().ObjCAutoRefCount) 1370 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); 1371 1372 // Handle restrict on references. 1373 if (LValueRef) 1374 return Context.getLValueReferenceType(T, SpelledAsLValue); 1375 return Context.getRValueReferenceType(T); 1376 } 1377 1378 /// Check whether the specified array size makes the array type a VLA. If so, 1379 /// return true, if not, return the size of the array in SizeVal. 1380 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) { 1381 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode 1382 // (like gnu99, but not c99) accept any evaluatable value as an extension. 1383 class VLADiagnoser : public Sema::VerifyICEDiagnoser { 1384 public: 1385 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {} 1386 1387 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1388 } 1389 1390 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) { 1391 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR; 1392 } 1393 } Diagnoser; 1394 1395 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser, 1396 S.LangOpts.GNUMode).isInvalid(); 1397 } 1398 1399 1400 /// \brief Build an array type. 1401 /// 1402 /// \param T The type of each element in the array. 1403 /// 1404 /// \param ASM C99 array size modifier (e.g., '*', 'static'). 1405 /// 1406 /// \param ArraySize Expression describing the size of the array. 1407 /// 1408 /// \param Brackets The range from the opening '[' to the closing ']'. 1409 /// 1410 /// \param Entity The name of the entity that involves the array 1411 /// type, if known. 1412 /// 1413 /// \returns A suitable array type, if there are no errors. Otherwise, 1414 /// returns a NULL type. 1415 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 1416 Expr *ArraySize, unsigned Quals, 1417 SourceRange Brackets, DeclarationName Entity) { 1418 1419 SourceLocation Loc = Brackets.getBegin(); 1420 if (getLangOpts().CPlusPlus) { 1421 // C++ [dcl.array]p1: 1422 // T is called the array element type; this type shall not be a reference 1423 // type, the (possibly cv-qualified) type void, a function type or an 1424 // abstract class type. 1425 // 1426 // C++ [dcl.array]p3: 1427 // When several "array of" specifications are adjacent, [...] only the 1428 // first of the constant expressions that specify the bounds of the arrays 1429 // may be omitted. 1430 // 1431 // Note: function types are handled in the common path with C. 1432 if (T->isReferenceType()) { 1433 Diag(Loc, diag::err_illegal_decl_array_of_references) 1434 << getPrintableNameForEntity(Entity) << T; 1435 return QualType(); 1436 } 1437 1438 if (T->isVoidType() || T->isIncompleteArrayType()) { 1439 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; 1440 return QualType(); 1441 } 1442 1443 if (RequireNonAbstractType(Brackets.getBegin(), T, 1444 diag::err_array_of_abstract_type)) 1445 return QualType(); 1446 1447 } else { 1448 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 1449 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 1450 if (RequireCompleteType(Loc, T, 1451 diag::err_illegal_decl_array_incomplete_type)) 1452 return QualType(); 1453 } 1454 1455 if (T->isFunctionType()) { 1456 Diag(Loc, diag::err_illegal_decl_array_of_functions) 1457 << getPrintableNameForEntity(Entity) << T; 1458 return QualType(); 1459 } 1460 1461 if (const RecordType *EltTy = T->getAs<RecordType>()) { 1462 // If the element type is a struct or union that contains a variadic 1463 // array, accept it as a GNU extension: C99 6.7.2.1p2. 1464 if (EltTy->getDecl()->hasFlexibleArrayMember()) 1465 Diag(Loc, diag::ext_flexible_array_in_array) << T; 1466 } else if (T->isObjCObjectType()) { 1467 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 1468 return QualType(); 1469 } 1470 1471 // Do placeholder conversions on the array size expression. 1472 if (ArraySize && ArraySize->hasPlaceholderType()) { 1473 ExprResult Result = CheckPlaceholderExpr(ArraySize); 1474 if (Result.isInvalid()) return QualType(); 1475 ArraySize = Result.take(); 1476 } 1477 1478 // Do lvalue-to-rvalue conversions on the array size expression. 1479 if (ArraySize && !ArraySize->isRValue()) { 1480 ExprResult Result = DefaultLvalueConversion(ArraySize); 1481 if (Result.isInvalid()) 1482 return QualType(); 1483 1484 ArraySize = Result.take(); 1485 } 1486 1487 // C99 6.7.5.2p1: The size expression shall have integer type. 1488 // C++11 allows contextual conversions to such types. 1489 if (!getLangOpts().CPlusPlus11 && 1490 ArraySize && !ArraySize->isTypeDependent() && 1491 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 1492 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 1493 << ArraySize->getType() << ArraySize->getSourceRange(); 1494 return QualType(); 1495 } 1496 1497 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); 1498 if (!ArraySize) { 1499 if (ASM == ArrayType::Star) 1500 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets); 1501 else 1502 T = Context.getIncompleteArrayType(T, ASM, Quals); 1503 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { 1504 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 1505 } else if ((!T->isDependentType() && !T->isIncompleteType() && 1506 !T->isConstantSizeType()) || 1507 isArraySizeVLA(*this, ArraySize, ConstVal)) { 1508 // Even in C++11, don't allow contextual conversions in the array bound 1509 // of a VLA. 1510 if (getLangOpts().CPlusPlus11 && 1511 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 1512 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 1513 << ArraySize->getType() << ArraySize->getSourceRange(); 1514 return QualType(); 1515 } 1516 1517 // C99: an array with an element type that has a non-constant-size is a VLA. 1518 // C99: an array with a non-ICE size is a VLA. We accept any expression 1519 // that we can fold to a non-zero positive value as an extension. 1520 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 1521 } else { 1522 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 1523 // have a value greater than zero. 1524 if (ConstVal.isSigned() && ConstVal.isNegative()) { 1525 if (Entity) 1526 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size) 1527 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange(); 1528 else 1529 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size) 1530 << ArraySize->getSourceRange(); 1531 return QualType(); 1532 } 1533 if (ConstVal == 0) { 1534 // GCC accepts zero sized static arrays. We allow them when 1535 // we're not in a SFINAE context. 1536 Diag(ArraySize->getLocStart(), 1537 isSFINAEContext()? diag::err_typecheck_zero_array_size 1538 : diag::ext_typecheck_zero_array_size) 1539 << ArraySize->getSourceRange(); 1540 1541 if (ASM == ArrayType::Static) { 1542 Diag(ArraySize->getLocStart(), 1543 diag::warn_typecheck_zero_static_array_size) 1544 << ArraySize->getSourceRange(); 1545 ASM = ArrayType::Normal; 1546 } 1547 } else if (!T->isDependentType() && !T->isVariablyModifiedType() && 1548 !T->isIncompleteType()) { 1549 // Is the array too large? 1550 unsigned ActiveSizeBits 1551 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal); 1552 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) 1553 Diag(ArraySize->getLocStart(), diag::err_array_too_large) 1554 << ConstVal.toString(10) 1555 << ArraySize->getSourceRange(); 1556 } 1557 1558 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); 1559 } 1560 1561 // OpenCL v1.2 s6.9.d: variable length arrays are not supported. 1562 if (getLangOpts().OpenCL && T->isVariableArrayType()) { 1563 Diag(Loc, diag::err_opencl_vla); 1564 return QualType(); 1565 } 1566 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 1567 if (!getLangOpts().C99) { 1568 if (T->isVariableArrayType()) { 1569 // Prohibit the use of non-POD types in VLAs. 1570 // FIXME: C++1y allows this. 1571 QualType BaseT = Context.getBaseElementType(T); 1572 if (!T->isDependentType() && 1573 !BaseT.isPODType(Context) && 1574 !BaseT->isObjCLifetimeType()) { 1575 Diag(Loc, diag::err_vla_non_pod) 1576 << BaseT; 1577 return QualType(); 1578 } 1579 // Prohibit the use of VLAs during template argument deduction. 1580 else if (isSFINAEContext()) { 1581 Diag(Loc, diag::err_vla_in_sfinae); 1582 return QualType(); 1583 } 1584 // Just extwarn about VLAs. 1585 else 1586 Diag(Loc, getLangOpts().CPlusPlus1y 1587 ? diag::warn_cxx11_compat_array_of_runtime_bound 1588 : diag::ext_vla); 1589 } else if (ASM != ArrayType::Normal || Quals != 0) 1590 Diag(Loc, 1591 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx 1592 : diag::ext_c99_array_usage) << ASM; 1593 } 1594 1595 if (T->isVariableArrayType()) { 1596 // Warn about VLAs for -Wvla. 1597 Diag(Loc, diag::warn_vla_used); 1598 } 1599 1600 return T; 1601 } 1602 1603 /// \brief Build an ext-vector type. 1604 /// 1605 /// Run the required checks for the extended vector type. 1606 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, 1607 SourceLocation AttrLoc) { 1608 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 1609 // in conjunction with complex types (pointers, arrays, functions, etc.). 1610 if (!T->isDependentType() && 1611 !T->isIntegerType() && !T->isRealFloatingType()) { 1612 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 1613 return QualType(); 1614 } 1615 1616 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { 1617 llvm::APSInt vecSize(32); 1618 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { 1619 Diag(AttrLoc, diag::err_attribute_argument_not_int) 1620 << "ext_vector_type" << ArraySize->getSourceRange(); 1621 return QualType(); 1622 } 1623 1624 // unlike gcc's vector_size attribute, the size is specified as the 1625 // number of elements, not the number of bytes. 1626 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 1627 1628 if (vectorSize == 0) { 1629 Diag(AttrLoc, diag::err_attribute_zero_size) 1630 << ArraySize->getSourceRange(); 1631 return QualType(); 1632 } 1633 1634 return Context.getExtVectorType(T, vectorSize); 1635 } 1636 1637 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); 1638 } 1639 1640 QualType Sema::BuildFunctionType(QualType T, 1641 llvm::MutableArrayRef<QualType> ParamTypes, 1642 SourceLocation Loc, DeclarationName Entity, 1643 const FunctionProtoType::ExtProtoInfo &EPI) { 1644 if (T->isArrayType() || T->isFunctionType()) { 1645 Diag(Loc, diag::err_func_returning_array_function) 1646 << T->isFunctionType() << T; 1647 return QualType(); 1648 } 1649 1650 // Functions cannot return half FP. 1651 if (T->isHalfType()) { 1652 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << 1653 FixItHint::CreateInsertion(Loc, "*"); 1654 return QualType(); 1655 } 1656 1657 bool Invalid = false; 1658 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { 1659 // FIXME: Loc is too inprecise here, should use proper locations for args. 1660 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); 1661 if (ParamType->isVoidType()) { 1662 Diag(Loc, diag::err_param_with_void_type); 1663 Invalid = true; 1664 } else if (ParamType->isHalfType()) { 1665 // Disallow half FP arguments. 1666 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << 1667 FixItHint::CreateInsertion(Loc, "*"); 1668 Invalid = true; 1669 } 1670 1671 ParamTypes[Idx] = ParamType; 1672 } 1673 1674 if (Invalid) 1675 return QualType(); 1676 1677 return Context.getFunctionType(T, ParamTypes, EPI); 1678 } 1679 1680 /// \brief Build a member pointer type \c T Class::*. 1681 /// 1682 /// \param T the type to which the member pointer refers. 1683 /// \param Class the class type into which the member pointer points. 1684 /// \param Loc the location where this type begins 1685 /// \param Entity the name of the entity that will have this member pointer type 1686 /// 1687 /// \returns a member pointer type, if successful, or a NULL type if there was 1688 /// an error. 1689 QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 1690 SourceLocation Loc, 1691 DeclarationName Entity) { 1692 // Verify that we're not building a pointer to pointer to function with 1693 // exception specification. 1694 if (CheckDistantExceptionSpec(T)) { 1695 Diag(Loc, diag::err_distant_exception_spec); 1696 1697 // FIXME: If we're doing this as part of template instantiation, 1698 // we should return immediately. 1699 1700 // Build the type anyway, but use the canonical type so that the 1701 // exception specifiers are stripped off. 1702 T = Context.getCanonicalType(T); 1703 } 1704 1705 // C++ 8.3.3p3: A pointer to member shall not point to ... a member 1706 // with reference type, or "cv void." 1707 if (T->isReferenceType()) { 1708 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 1709 << (Entity? Entity.getAsString() : "type name") << T; 1710 return QualType(); 1711 } 1712 1713 if (T->isVoidType()) { 1714 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 1715 << (Entity? Entity.getAsString() : "type name"); 1716 return QualType(); 1717 } 1718 1719 if (!Class->isDependentType() && !Class->isRecordType()) { 1720 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 1721 return QualType(); 1722 } 1723 1724 // C++ allows the class type in a member pointer to be an incomplete type. 1725 // In the Microsoft ABI, the size of the member pointer can vary 1726 // according to the class type, which means that we really need a 1727 // complete type if possible, which means we need to instantiate templates. 1728 // 1729 // If template instantiation fails or the type is just incomplete, we have to 1730 // add an extra slot to the member pointer. Yes, this does cause problems 1731 // when passing pointers between TUs that disagree about the size. 1732 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1733 CXXRecordDecl *RD = Class->getAsCXXRecordDecl(); 1734 if (RD && !RD->hasAttr<MSInheritanceAttr>()) { 1735 // Lock in the inheritance model on the first use of a member pointer. 1736 // Otherwise we may disagree about the size at different points in the TU. 1737 // FIXME: MSVC picks a model on the first use that needs to know the size, 1738 // rather than on the first mention of the type, e.g. typedefs. 1739 if (RequireCompleteType(Loc, Class, 0) && !RD->isBeingDefined()) { 1740 // We know it doesn't have an attribute and it's incomplete, so use the 1741 // unspecified inheritance model. If we're in the record body, we can 1742 // figure out the inheritance model. 1743 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(), 1744 E = RD->redecls_end(); I != E; ++I) { 1745 I->addAttr(::new (Context) UnspecifiedInheritanceAttr( 1746 RD->getSourceRange(), Context)); 1747 } 1748 } 1749 } 1750 } 1751 1752 return Context.getMemberPointerType(T, Class.getTypePtr()); 1753 } 1754 1755 /// \brief Build a block pointer type. 1756 /// 1757 /// \param T The type to which we'll be building a block pointer. 1758 /// 1759 /// \param Loc The source location, used for diagnostics. 1760 /// 1761 /// \param Entity The name of the entity that involves the block pointer 1762 /// type, if known. 1763 /// 1764 /// \returns A suitable block pointer type, if there are no 1765 /// errors. Otherwise, returns a NULL type. 1766 QualType Sema::BuildBlockPointerType(QualType T, 1767 SourceLocation Loc, 1768 DeclarationName Entity) { 1769 if (!T->isFunctionType()) { 1770 Diag(Loc, diag::err_nonfunction_block_type); 1771 return QualType(); 1772 } 1773 1774 return Context.getBlockPointerType(T); 1775 } 1776 1777 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { 1778 QualType QT = Ty.get(); 1779 if (QT.isNull()) { 1780 if (TInfo) *TInfo = 0; 1781 return QualType(); 1782 } 1783 1784 TypeSourceInfo *DI = 0; 1785 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 1786 QT = LIT->getType(); 1787 DI = LIT->getTypeSourceInfo(); 1788 } 1789 1790 if (TInfo) *TInfo = DI; 1791 return QT; 1792 } 1793 1794 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 1795 Qualifiers::ObjCLifetime ownership, 1796 unsigned chunkIndex); 1797 1798 /// Given that this is the declaration of a parameter under ARC, 1799 /// attempt to infer attributes and such for pointer-to-whatever 1800 /// types. 1801 static void inferARCWriteback(TypeProcessingState &state, 1802 QualType &declSpecType) { 1803 Sema &S = state.getSema(); 1804 Declarator &declarator = state.getDeclarator(); 1805 1806 // TODO: should we care about decl qualifiers? 1807 1808 // Check whether the declarator has the expected form. We walk 1809 // from the inside out in order to make the block logic work. 1810 unsigned outermostPointerIndex = 0; 1811 bool isBlockPointer = false; 1812 unsigned numPointers = 0; 1813 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 1814 unsigned chunkIndex = i; 1815 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); 1816 switch (chunk.Kind) { 1817 case DeclaratorChunk::Paren: 1818 // Ignore parens. 1819 break; 1820 1821 case DeclaratorChunk::Reference: 1822 case DeclaratorChunk::Pointer: 1823 // Count the number of pointers. Treat references 1824 // interchangeably as pointers; if they're mis-ordered, normal 1825 // type building will discover that. 1826 outermostPointerIndex = chunkIndex; 1827 numPointers++; 1828 break; 1829 1830 case DeclaratorChunk::BlockPointer: 1831 // If we have a pointer to block pointer, that's an acceptable 1832 // indirect reference; anything else is not an application of 1833 // the rules. 1834 if (numPointers != 1) return; 1835 numPointers++; 1836 outermostPointerIndex = chunkIndex; 1837 isBlockPointer = true; 1838 1839 // We don't care about pointer structure in return values here. 1840 goto done; 1841 1842 case DeclaratorChunk::Array: // suppress if written (id[])? 1843 case DeclaratorChunk::Function: 1844 case DeclaratorChunk::MemberPointer: 1845 return; 1846 } 1847 } 1848 done: 1849 1850 // If we have *one* pointer, then we want to throw the qualifier on 1851 // the declaration-specifiers, which means that it needs to be a 1852 // retainable object type. 1853 if (numPointers == 1) { 1854 // If it's not a retainable object type, the rule doesn't apply. 1855 if (!declSpecType->isObjCRetainableType()) return; 1856 1857 // If it already has lifetime, don't do anything. 1858 if (declSpecType.getObjCLifetime()) return; 1859 1860 // Otherwise, modify the type in-place. 1861 Qualifiers qs; 1862 1863 if (declSpecType->isObjCARCImplicitlyUnretainedType()) 1864 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); 1865 else 1866 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); 1867 declSpecType = S.Context.getQualifiedType(declSpecType, qs); 1868 1869 // If we have *two* pointers, then we want to throw the qualifier on 1870 // the outermost pointer. 1871 } else if (numPointers == 2) { 1872 // If we don't have a block pointer, we need to check whether the 1873 // declaration-specifiers gave us something that will turn into a 1874 // retainable object pointer after we slap the first pointer on it. 1875 if (!isBlockPointer && !declSpecType->isObjCObjectType()) 1876 return; 1877 1878 // Look for an explicit lifetime attribute there. 1879 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); 1880 if (chunk.Kind != DeclaratorChunk::Pointer && 1881 chunk.Kind != DeclaratorChunk::BlockPointer) 1882 return; 1883 for (const AttributeList *attr = chunk.getAttrs(); attr; 1884 attr = attr->getNext()) 1885 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 1886 return; 1887 1888 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, 1889 outermostPointerIndex); 1890 1891 // Any other number of pointers/references does not trigger the rule. 1892 } else return; 1893 1894 // TODO: mark whether we did this inference? 1895 } 1896 1897 static void diagnoseIgnoredQualifiers( 1898 Sema &S, unsigned Quals, 1899 SourceLocation FallbackLoc, 1900 SourceLocation ConstQualLoc = SourceLocation(), 1901 SourceLocation VolatileQualLoc = SourceLocation(), 1902 SourceLocation RestrictQualLoc = SourceLocation(), 1903 SourceLocation AtomicQualLoc = SourceLocation()) { 1904 if (!Quals) 1905 return; 1906 1907 const SourceManager &SM = S.getSourceManager(); 1908 1909 struct Qual { 1910 unsigned Mask; 1911 const char *Name; 1912 SourceLocation Loc; 1913 } const QualKinds[4] = { 1914 { DeclSpec::TQ_const, "const", ConstQualLoc }, 1915 { DeclSpec::TQ_volatile, "volatile", VolatileQualLoc }, 1916 { DeclSpec::TQ_restrict, "restrict", RestrictQualLoc }, 1917 { DeclSpec::TQ_atomic, "_Atomic", AtomicQualLoc } 1918 }; 1919 1920 llvm::SmallString<32> QualStr; 1921 unsigned NumQuals = 0; 1922 SourceLocation Loc; 1923 FixItHint FixIts[4]; 1924 1925 // Build a string naming the redundant qualifiers. 1926 for (unsigned I = 0; I != 4; ++I) { 1927 if (Quals & QualKinds[I].Mask) { 1928 if (!QualStr.empty()) QualStr += ' '; 1929 QualStr += QualKinds[I].Name; 1930 1931 // If we have a location for the qualifier, offer a fixit. 1932 SourceLocation QualLoc = QualKinds[I].Loc; 1933 if (!QualLoc.isInvalid()) { 1934 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); 1935 if (Loc.isInvalid() || SM.isBeforeInTranslationUnit(QualLoc, Loc)) 1936 Loc = QualLoc; 1937 } 1938 1939 ++NumQuals; 1940 } 1941 } 1942 1943 S.Diag(Loc.isInvalid() ? FallbackLoc : Loc, diag::warn_qual_return_type) 1944 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; 1945 } 1946 1947 // Diagnose pointless type qualifiers on the return type of a function. 1948 static void diagnoseIgnoredFunctionQualifiers(Sema &S, QualType RetTy, 1949 Declarator &D, 1950 unsigned FunctionChunkIndex) { 1951 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) { 1952 // FIXME: TypeSourceInfo doesn't preserve location information for 1953 // qualifiers. 1954 diagnoseIgnoredQualifiers(S, RetTy.getLocalCVRQualifiers(), 1955 D.getIdentifierLoc()); 1956 return; 1957 } 1958 1959 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, 1960 End = D.getNumTypeObjects(); 1961 OuterChunkIndex != End; ++OuterChunkIndex) { 1962 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); 1963 switch (OuterChunk.Kind) { 1964 case DeclaratorChunk::Paren: 1965 continue; 1966 1967 case DeclaratorChunk::Pointer: { 1968 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; 1969 diagnoseIgnoredQualifiers( 1970 S, PTI.TypeQuals, 1971 SourceLocation(), 1972 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), 1973 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), 1974 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), 1975 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc)); 1976 return; 1977 } 1978 1979 case DeclaratorChunk::Function: 1980 case DeclaratorChunk::BlockPointer: 1981 case DeclaratorChunk::Reference: 1982 case DeclaratorChunk::Array: 1983 case DeclaratorChunk::MemberPointer: 1984 // FIXME: We can't currently provide an accurate source location and a 1985 // fix-it hint for these. 1986 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; 1987 diagnoseIgnoredQualifiers(S, RetTy.getCVRQualifiers() | AtomicQual, 1988 D.getIdentifierLoc()); 1989 return; 1990 } 1991 1992 llvm_unreachable("unknown declarator chunk kind"); 1993 } 1994 1995 // If the qualifiers come from a conversion function type, don't diagnose 1996 // them -- they're not necessarily redundant, since such a conversion 1997 // operator can be explicitly called as "x.operator const int()". 1998 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 1999 return; 2000 2001 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers 2002 // which are present there. 2003 diagnoseIgnoredQualifiers(S, D.getDeclSpec().getTypeQualifiers(), 2004 D.getIdentifierLoc(), 2005 D.getDeclSpec().getConstSpecLoc(), 2006 D.getDeclSpec().getVolatileSpecLoc(), 2007 D.getDeclSpec().getRestrictSpecLoc(), 2008 D.getDeclSpec().getAtomicSpecLoc()); 2009 } 2010 2011 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, 2012 TypeSourceInfo *&ReturnTypeInfo) { 2013 Sema &SemaRef = state.getSema(); 2014 Declarator &D = state.getDeclarator(); 2015 QualType T; 2016 ReturnTypeInfo = 0; 2017 2018 // The TagDecl owned by the DeclSpec. 2019 TagDecl *OwnedTagDecl = 0; 2020 2021 bool ContainsPlaceholderType = false; 2022 2023 switch (D.getName().getKind()) { 2024 case UnqualifiedId::IK_ImplicitSelfParam: 2025 case UnqualifiedId::IK_OperatorFunctionId: 2026 case UnqualifiedId::IK_Identifier: 2027 case UnqualifiedId::IK_LiteralOperatorId: 2028 case UnqualifiedId::IK_TemplateId: 2029 T = ConvertDeclSpecToType(state); 2030 ContainsPlaceholderType = D.getDeclSpec().containsPlaceholderType(); 2031 2032 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 2033 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 2034 // Owned declaration is embedded in declarator. 2035 OwnedTagDecl->setEmbeddedInDeclarator(true); 2036 } 2037 break; 2038 2039 case UnqualifiedId::IK_ConstructorName: 2040 case UnqualifiedId::IK_ConstructorTemplateId: 2041 case UnqualifiedId::IK_DestructorName: 2042 // Constructors and destructors don't have return types. Use 2043 // "void" instead. 2044 T = SemaRef.Context.VoidTy; 2045 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList()) 2046 processTypeAttrs(state, T, TAL_DeclSpec, attrs); 2047 break; 2048 2049 case UnqualifiedId::IK_ConversionFunctionId: 2050 // The result type of a conversion function is the type that it 2051 // converts to. 2052 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, 2053 &ReturnTypeInfo); 2054 ContainsPlaceholderType = T->getContainedAutoType(); 2055 break; 2056 } 2057 2058 if (D.getAttributes()) 2059 distributeTypeAttrsFromDeclarator(state, T); 2060 2061 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. 2062 // In C++11, a function declarator using 'auto' must have a trailing return 2063 // type (this is checked later) and we can skip this. In other languages 2064 // using auto, we need to check regardless. 2065 if (ContainsPlaceholderType && 2066 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) { 2067 int Error = -1; 2068 2069 switch (D.getContext()) { 2070 case Declarator::KNRTypeListContext: 2071 llvm_unreachable("K&R type lists aren't allowed in C++"); 2072 case Declarator::LambdaExprContext: 2073 llvm_unreachable("Can't specify a type specifier in lambda grammar"); 2074 case Declarator::ObjCParameterContext: 2075 case Declarator::ObjCResultContext: 2076 case Declarator::PrototypeContext: 2077 Error = 0; // Function prototype 2078 break; 2079 case Declarator::MemberContext: 2080 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) 2081 break; 2082 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { 2083 case TTK_Enum: llvm_unreachable("unhandled tag kind"); 2084 case TTK_Struct: Error = 1; /* Struct member */ break; 2085 case TTK_Union: Error = 2; /* Union member */ break; 2086 case TTK_Class: Error = 3; /* Class member */ break; 2087 case TTK_Interface: Error = 4; /* Interface member */ break; 2088 } 2089 break; 2090 case Declarator::CXXCatchContext: 2091 case Declarator::ObjCCatchContext: 2092 Error = 5; // Exception declaration 2093 break; 2094 case Declarator::TemplateParamContext: 2095 Error = 6; // Template parameter 2096 break; 2097 case Declarator::BlockLiteralContext: 2098 Error = 7; // Block literal 2099 break; 2100 case Declarator::TemplateTypeArgContext: 2101 Error = 8; // Template type argument 2102 break; 2103 case Declarator::AliasDeclContext: 2104 case Declarator::AliasTemplateContext: 2105 Error = 10; // Type alias 2106 break; 2107 case Declarator::TrailingReturnContext: 2108 if (!SemaRef.getLangOpts().CPlusPlus1y) 2109 Error = 11; // Function return type 2110 break; 2111 case Declarator::ConversionIdContext: 2112 if (!SemaRef.getLangOpts().CPlusPlus1y) 2113 Error = 12; // conversion-type-id 2114 break; 2115 case Declarator::TypeNameContext: 2116 Error = 13; // Generic 2117 break; 2118 case Declarator::FileContext: 2119 case Declarator::BlockContext: 2120 case Declarator::ForContext: 2121 case Declarator::ConditionContext: 2122 case Declarator::CXXNewContext: 2123 break; 2124 } 2125 2126 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 2127 Error = 9; 2128 2129 // In Objective-C it is an error to use 'auto' on a function declarator. 2130 if (D.isFunctionDeclarator()) 2131 Error = 11; 2132 2133 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator 2134 // contains a trailing return type. That is only legal at the outermost 2135 // level. Check all declarator chunks (outermost first) anyway, to give 2136 // better diagnostics. 2137 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) { 2138 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2139 unsigned chunkIndex = e - i - 1; 2140 state.setCurrentChunkIndex(chunkIndex); 2141 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 2142 if (DeclType.Kind == DeclaratorChunk::Function) { 2143 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2144 if (FTI.hasTrailingReturnType()) { 2145 Error = -1; 2146 break; 2147 } 2148 } 2149 } 2150 } 2151 2152 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); 2153 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) 2154 AutoRange = D.getName().getSourceRange(); 2155 2156 if (Error != -1) { 2157 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) 2158 << Error << AutoRange; 2159 T = SemaRef.Context.IntTy; 2160 D.setInvalidType(true); 2161 } else 2162 SemaRef.Diag(AutoRange.getBegin(), 2163 diag::warn_cxx98_compat_auto_type_specifier) 2164 << AutoRange; 2165 } 2166 2167 if (SemaRef.getLangOpts().CPlusPlus && 2168 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { 2169 // Check the contexts where C++ forbids the declaration of a new class 2170 // or enumeration in a type-specifier-seq. 2171 switch (D.getContext()) { 2172 case Declarator::TrailingReturnContext: 2173 // Class and enumeration definitions are syntactically not allowed in 2174 // trailing return types. 2175 llvm_unreachable("parser should not have allowed this"); 2176 break; 2177 case Declarator::FileContext: 2178 case Declarator::MemberContext: 2179 case Declarator::BlockContext: 2180 case Declarator::ForContext: 2181 case Declarator::BlockLiteralContext: 2182 case Declarator::LambdaExprContext: 2183 // C++11 [dcl.type]p3: 2184 // A type-specifier-seq shall not define a class or enumeration unless 2185 // it appears in the type-id of an alias-declaration (7.1.3) that is not 2186 // the declaration of a template-declaration. 2187 case Declarator::AliasDeclContext: 2188 break; 2189 case Declarator::AliasTemplateContext: 2190 SemaRef.Diag(OwnedTagDecl->getLocation(), 2191 diag::err_type_defined_in_alias_template) 2192 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2193 D.setInvalidType(true); 2194 break; 2195 case Declarator::TypeNameContext: 2196 case Declarator::ConversionIdContext: 2197 case Declarator::TemplateParamContext: 2198 case Declarator::CXXNewContext: 2199 case Declarator::CXXCatchContext: 2200 case Declarator::ObjCCatchContext: 2201 case Declarator::TemplateTypeArgContext: 2202 SemaRef.Diag(OwnedTagDecl->getLocation(), 2203 diag::err_type_defined_in_type_specifier) 2204 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2205 D.setInvalidType(true); 2206 break; 2207 case Declarator::PrototypeContext: 2208 case Declarator::ObjCParameterContext: 2209 case Declarator::ObjCResultContext: 2210 case Declarator::KNRTypeListContext: 2211 // C++ [dcl.fct]p6: 2212 // Types shall not be defined in return or parameter types. 2213 SemaRef.Diag(OwnedTagDecl->getLocation(), 2214 diag::err_type_defined_in_param_type) 2215 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 2216 D.setInvalidType(true); 2217 break; 2218 case Declarator::ConditionContext: 2219 // C++ 6.4p2: 2220 // The type-specifier-seq shall not contain typedef and shall not declare 2221 // a new class or enumeration. 2222 SemaRef.Diag(OwnedTagDecl->getLocation(), 2223 diag::err_type_defined_in_condition); 2224 D.setInvalidType(true); 2225 break; 2226 } 2227 } 2228 2229 return T; 2230 } 2231 2232 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ 2233 std::string Quals = 2234 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString(); 2235 2236 switch (FnTy->getRefQualifier()) { 2237 case RQ_None: 2238 break; 2239 2240 case RQ_LValue: 2241 if (!Quals.empty()) 2242 Quals += ' '; 2243 Quals += '&'; 2244 break; 2245 2246 case RQ_RValue: 2247 if (!Quals.empty()) 2248 Quals += ' '; 2249 Quals += "&&"; 2250 break; 2251 } 2252 2253 return Quals; 2254 } 2255 2256 /// Check that the function type T, which has a cv-qualifier or a ref-qualifier, 2257 /// can be contained within the declarator chunk DeclType, and produce an 2258 /// appropriate diagnostic if not. 2259 static void checkQualifiedFunction(Sema &S, QualType T, 2260 DeclaratorChunk &DeclType) { 2261 // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a 2262 // cv-qualifier or a ref-qualifier can only appear at the topmost level 2263 // of a type. 2264 int DiagKind = -1; 2265 switch (DeclType.Kind) { 2266 case DeclaratorChunk::Paren: 2267 case DeclaratorChunk::MemberPointer: 2268 // These cases are permitted. 2269 return; 2270 case DeclaratorChunk::Array: 2271 case DeclaratorChunk::Function: 2272 // These cases don't allow function types at all; no need to diagnose the 2273 // qualifiers separately. 2274 return; 2275 case DeclaratorChunk::BlockPointer: 2276 DiagKind = 0; 2277 break; 2278 case DeclaratorChunk::Pointer: 2279 DiagKind = 1; 2280 break; 2281 case DeclaratorChunk::Reference: 2282 DiagKind = 2; 2283 break; 2284 } 2285 2286 assert(DiagKind != -1); 2287 S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type) 2288 << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T 2289 << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>()); 2290 } 2291 2292 /// Produce an approprioate diagnostic for an ambiguity between a function 2293 /// declarator and a C++ direct-initializer. 2294 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, 2295 DeclaratorChunk &DeclType, QualType RT) { 2296 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2297 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity"); 2298 2299 // If the return type is void there is no ambiguity. 2300 if (RT->isVoidType()) 2301 return; 2302 2303 // An initializer for a non-class type can have at most one argument. 2304 if (!RT->isRecordType() && FTI.NumArgs > 1) 2305 return; 2306 2307 // An initializer for a reference must have exactly one argument. 2308 if (RT->isReferenceType() && FTI.NumArgs != 1) 2309 return; 2310 2311 // Only warn if this declarator is declaring a function at block scope, and 2312 // doesn't have a storage class (such as 'extern') specified. 2313 if (!D.isFunctionDeclarator() || 2314 D.getFunctionDefinitionKind() != FDK_Declaration || 2315 !S.CurContext->isFunctionOrMethod() || 2316 D.getDeclSpec().getStorageClassSpec() 2317 != DeclSpec::SCS_unspecified) 2318 return; 2319 2320 // Inside a condition, a direct initializer is not permitted. We allow one to 2321 // be parsed in order to give better diagnostics in condition parsing. 2322 if (D.getContext() == Declarator::ConditionContext) 2323 return; 2324 2325 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); 2326 2327 S.Diag(DeclType.Loc, 2328 FTI.NumArgs ? diag::warn_parens_disambiguated_as_function_declaration 2329 : diag::warn_empty_parens_are_function_decl) 2330 << ParenRange; 2331 2332 // If the declaration looks like: 2333 // T var1, 2334 // f(); 2335 // and name lookup finds a function named 'f', then the ',' was 2336 // probably intended to be a ';'. 2337 if (!D.isFirstDeclarator() && D.getIdentifier()) { 2338 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); 2339 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); 2340 if (Comma.getFileID() != Name.getFileID() || 2341 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { 2342 LookupResult Result(S, D.getIdentifier(), SourceLocation(), 2343 Sema::LookupOrdinaryName); 2344 if (S.LookupName(Result, S.getCurScope())) 2345 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) 2346 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") 2347 << D.getIdentifier(); 2348 } 2349 } 2350 2351 if (FTI.NumArgs > 0) { 2352 // For a declaration with parameters, eg. "T var(T());", suggest adding parens 2353 // around the first parameter to turn the declaration into a variable 2354 // declaration. 2355 SourceRange Range = FTI.ArgInfo[0].Param->getSourceRange(); 2356 SourceLocation B = Range.getBegin(); 2357 SourceLocation E = S.PP.getLocForEndOfToken(Range.getEnd()); 2358 // FIXME: Maybe we should suggest adding braces instead of parens 2359 // in C++11 for classes that don't have an initializer_list constructor. 2360 S.Diag(B, diag::note_additional_parens_for_variable_declaration) 2361 << FixItHint::CreateInsertion(B, "(") 2362 << FixItHint::CreateInsertion(E, ")"); 2363 } else { 2364 // For a declaration without parameters, eg. "T var();", suggest replacing the 2365 // parens with an initializer to turn the declaration into a variable 2366 // declaration. 2367 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); 2368 2369 // Empty parens mean value-initialization, and no parens mean 2370 // default initialization. These are equivalent if the default 2371 // constructor is user-provided or if zero-initialization is a 2372 // no-op. 2373 if (RD && RD->hasDefinition() && 2374 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) 2375 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) 2376 << FixItHint::CreateRemoval(ParenRange); 2377 else { 2378 std::string Init = S.getFixItZeroInitializerForType(RT); 2379 if (Init.empty() && S.LangOpts.CPlusPlus11) 2380 Init = "{}"; 2381 if (!Init.empty()) 2382 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) 2383 << FixItHint::CreateReplacement(ParenRange, Init); 2384 } 2385 } 2386 } 2387 2388 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 2389 QualType declSpecType, 2390 TypeSourceInfo *TInfo) { 2391 2392 QualType T = declSpecType; 2393 Declarator &D = state.getDeclarator(); 2394 Sema &S = state.getSema(); 2395 ASTContext &Context = S.Context; 2396 const LangOptions &LangOpts = S.getLangOpts(); 2397 2398 // The name we're declaring, if any. 2399 DeclarationName Name; 2400 if (D.getIdentifier()) 2401 Name = D.getIdentifier(); 2402 2403 // Does this declaration declare a typedef-name? 2404 bool IsTypedefName = 2405 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 2406 D.getContext() == Declarator::AliasDeclContext || 2407 D.getContext() == Declarator::AliasTemplateContext; 2408 2409 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 2410 bool IsQualifiedFunction = T->isFunctionProtoType() && 2411 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 || 2412 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); 2413 2414 // If T is 'decltype(auto)', the only declarators we can have are parens 2415 // and at most one function declarator if this is a function declaration. 2416 if (const AutoType *AT = T->getAs<AutoType>()) { 2417 if (AT->isDecltypeAuto()) { 2418 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 2419 unsigned Index = E - I - 1; 2420 DeclaratorChunk &DeclChunk = D.getTypeObject(Index); 2421 unsigned DiagId = diag::err_decltype_auto_compound_type; 2422 unsigned DiagKind = 0; 2423 switch (DeclChunk.Kind) { 2424 case DeclaratorChunk::Paren: 2425 continue; 2426 case DeclaratorChunk::Function: { 2427 unsigned FnIndex; 2428 if (D.isFunctionDeclarationContext() && 2429 D.isFunctionDeclarator(FnIndex) && FnIndex == Index) 2430 continue; 2431 DiagId = diag::err_decltype_auto_function_declarator_not_declaration; 2432 break; 2433 } 2434 case DeclaratorChunk::Pointer: 2435 case DeclaratorChunk::BlockPointer: 2436 case DeclaratorChunk::MemberPointer: 2437 DiagKind = 0; 2438 break; 2439 case DeclaratorChunk::Reference: 2440 DiagKind = 1; 2441 break; 2442 case DeclaratorChunk::Array: 2443 DiagKind = 2; 2444 break; 2445 } 2446 2447 S.Diag(DeclChunk.Loc, DiagId) << DiagKind; 2448 D.setInvalidType(true); 2449 break; 2450 } 2451 } 2452 } 2453 2454 // Walk the DeclTypeInfo, building the recursive type as we go. 2455 // DeclTypeInfos are ordered from the identifier out, which is 2456 // opposite of what we want :). 2457 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 2458 unsigned chunkIndex = e - i - 1; 2459 state.setCurrentChunkIndex(chunkIndex); 2460 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 2461 if (IsQualifiedFunction) { 2462 checkQualifiedFunction(S, T, DeclType); 2463 IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren; 2464 } 2465 switch (DeclType.Kind) { 2466 case DeclaratorChunk::Paren: 2467 T = S.BuildParenType(T); 2468 break; 2469 case DeclaratorChunk::BlockPointer: 2470 // If blocks are disabled, emit an error. 2471 if (!LangOpts.Blocks) 2472 S.Diag(DeclType.Loc, diag::err_blocks_disable); 2473 2474 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 2475 if (DeclType.Cls.TypeQuals) 2476 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 2477 break; 2478 case DeclaratorChunk::Pointer: 2479 // Verify that we're not building a pointer to pointer to function with 2480 // exception specification. 2481 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2482 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2483 D.setInvalidType(true); 2484 // Build the type anyway. 2485 } 2486 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) { 2487 T = Context.getObjCObjectPointerType(T); 2488 if (DeclType.Ptr.TypeQuals) 2489 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 2490 break; 2491 } 2492 T = S.BuildPointerType(T, DeclType.Loc, Name); 2493 if (DeclType.Ptr.TypeQuals) 2494 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 2495 2496 break; 2497 case DeclaratorChunk::Reference: { 2498 // Verify that we're not building a reference to pointer to function with 2499 // exception specification. 2500 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2501 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2502 D.setInvalidType(true); 2503 // Build the type anyway. 2504 } 2505 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 2506 2507 Qualifiers Quals; 2508 if (DeclType.Ref.HasRestrict) 2509 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 2510 break; 2511 } 2512 case DeclaratorChunk::Array: { 2513 // Verify that we're not building an array of pointers to function with 2514 // exception specification. 2515 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 2516 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 2517 D.setInvalidType(true); 2518 // Build the type anyway. 2519 } 2520 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 2521 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 2522 ArrayType::ArraySizeModifier ASM; 2523 if (ATI.isStar) 2524 ASM = ArrayType::Star; 2525 else if (ATI.hasStatic) 2526 ASM = ArrayType::Static; 2527 else 2528 ASM = ArrayType::Normal; 2529 if (ASM == ArrayType::Star && !D.isPrototypeContext()) { 2530 // FIXME: This check isn't quite right: it allows star in prototypes 2531 // for function definitions, and disallows some edge cases detailed 2532 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 2533 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 2534 ASM = ArrayType::Normal; 2535 D.setInvalidType(true); 2536 } 2537 2538 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static 2539 // shall appear only in a declaration of a function parameter with an 2540 // array type, ... 2541 if (ASM == ArrayType::Static || ATI.TypeQuals) { 2542 if (!(D.isPrototypeContext() || 2543 D.getContext() == Declarator::KNRTypeListContext)) { 2544 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << 2545 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 2546 // Remove the 'static' and the type qualifiers. 2547 if (ASM == ArrayType::Static) 2548 ASM = ArrayType::Normal; 2549 ATI.TypeQuals = 0; 2550 D.setInvalidType(true); 2551 } 2552 2553 // C99 6.7.5.2p1: ... and then only in the outermost array type 2554 // derivation. 2555 unsigned x = chunkIndex; 2556 while (x != 0) { 2557 // Walk outwards along the declarator chunks. 2558 x--; 2559 const DeclaratorChunk &DC = D.getTypeObject(x); 2560 switch (DC.Kind) { 2561 case DeclaratorChunk::Paren: 2562 continue; 2563 case DeclaratorChunk::Array: 2564 case DeclaratorChunk::Pointer: 2565 case DeclaratorChunk::Reference: 2566 case DeclaratorChunk::MemberPointer: 2567 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << 2568 (ASM == ArrayType::Static ? "'static'" : "type qualifier"); 2569 if (ASM == ArrayType::Static) 2570 ASM = ArrayType::Normal; 2571 ATI.TypeQuals = 0; 2572 D.setInvalidType(true); 2573 break; 2574 case DeclaratorChunk::Function: 2575 case DeclaratorChunk::BlockPointer: 2576 // These are invalid anyway, so just ignore. 2577 break; 2578 } 2579 } 2580 } 2581 2582 if (const AutoType *AT = T->getContainedAutoType()) { 2583 // We've already diagnosed this for decltype(auto). 2584 if (!AT->isDecltypeAuto()) 2585 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) 2586 << getPrintableNameForEntity(Name) << T; 2587 T = QualType(); 2588 break; 2589 } 2590 2591 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 2592 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 2593 break; 2594 } 2595 case DeclaratorChunk::Function: { 2596 // If the function declarator has a prototype (i.e. it is not () and 2597 // does not have a K&R-style identifier list), then the arguments are part 2598 // of the type, otherwise the argument list is (). 2599 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 2600 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier(); 2601 2602 // Check for auto functions and trailing return type and adjust the 2603 // return type accordingly. 2604 if (!D.isInvalidType()) { 2605 // trailing-return-type is only required if we're declaring a function, 2606 // and not, for instance, a pointer to a function. 2607 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 2608 !FTI.hasTrailingReturnType() && chunkIndex == 0 && 2609 !S.getLangOpts().CPlusPlus1y) { 2610 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2611 diag::err_auto_missing_trailing_return); 2612 T = Context.IntTy; 2613 D.setInvalidType(true); 2614 } else if (FTI.hasTrailingReturnType()) { 2615 // T must be exactly 'auto' at this point. See CWG issue 681. 2616 if (isa<ParenType>(T)) { 2617 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2618 diag::err_trailing_return_in_parens) 2619 << T << D.getDeclSpec().getSourceRange(); 2620 D.setInvalidType(true); 2621 } else if (D.getContext() != Declarator::LambdaExprContext && 2622 (T.hasQualifiers() || !isa<AutoType>(T) || 2623 cast<AutoType>(T)->isDecltypeAuto())) { 2624 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 2625 diag::err_trailing_return_without_auto) 2626 << T << D.getDeclSpec().getSourceRange(); 2627 D.setInvalidType(true); 2628 } 2629 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); 2630 if (T.isNull()) { 2631 // An error occurred parsing the trailing return type. 2632 T = Context.IntTy; 2633 D.setInvalidType(true); 2634 } 2635 } 2636 } 2637 2638 // C99 6.7.5.3p1: The return type may not be a function or array type. 2639 // For conversion functions, we'll diagnose this particular error later. 2640 if ((T->isArrayType() || T->isFunctionType()) && 2641 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 2642 unsigned diagID = diag::err_func_returning_array_function; 2643 // Last processing chunk in block context means this function chunk 2644 // represents the block. 2645 if (chunkIndex == 0 && 2646 D.getContext() == Declarator::BlockLiteralContext) 2647 diagID = diag::err_block_returning_array_function; 2648 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 2649 T = Context.IntTy; 2650 D.setInvalidType(true); 2651 } 2652 2653 // Do not allow returning half FP value. 2654 // FIXME: This really should be in BuildFunctionType. 2655 if (T->isHalfType()) { 2656 if (S.getLangOpts().OpenCL) { 2657 if (!S.getOpenCLOptions().cl_khr_fp16) { 2658 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T; 2659 D.setInvalidType(true); 2660 } 2661 } else { 2662 S.Diag(D.getIdentifierLoc(), 2663 diag::err_parameters_retval_cannot_have_fp16_type) << 1; 2664 D.setInvalidType(true); 2665 } 2666 } 2667 2668 // cv-qualifiers on return types are pointless except when the type is a 2669 // class type in C++. 2670 if ((T.getCVRQualifiers() || T->isAtomicType()) && 2671 !(S.getLangOpts().CPlusPlus && 2672 (T->isDependentType() || T->isRecordType()))) 2673 diagnoseIgnoredFunctionQualifiers(S, T, D, chunkIndex); 2674 2675 // Objective-C ARC ownership qualifiers are ignored on the function 2676 // return type (by type canonicalization). Complain if this attribute 2677 // was written here. 2678 if (T.getQualifiers().hasObjCLifetime()) { 2679 SourceLocation AttrLoc; 2680 if (chunkIndex + 1 < D.getNumTypeObjects()) { 2681 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 2682 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs(); 2683 Attr; Attr = Attr->getNext()) { 2684 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 2685 AttrLoc = Attr->getLoc(); 2686 break; 2687 } 2688 } 2689 } 2690 if (AttrLoc.isInvalid()) { 2691 for (const AttributeList *Attr 2692 = D.getDeclSpec().getAttributes().getList(); 2693 Attr; Attr = Attr->getNext()) { 2694 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) { 2695 AttrLoc = Attr->getLoc(); 2696 break; 2697 } 2698 } 2699 } 2700 2701 if (AttrLoc.isValid()) { 2702 // The ownership attributes are almost always written via 2703 // the predefined 2704 // __strong/__weak/__autoreleasing/__unsafe_unretained. 2705 if (AttrLoc.isMacroID()) 2706 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first; 2707 2708 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) 2709 << T.getQualifiers().getObjCLifetime(); 2710 } 2711 } 2712 2713 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) { 2714 // C++ [dcl.fct]p6: 2715 // Types shall not be defined in return or parameter types. 2716 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 2717 if (Tag->isCompleteDefinition()) 2718 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 2719 << Context.getTypeDeclType(Tag); 2720 } 2721 2722 // Exception specs are not allowed in typedefs. Complain, but add it 2723 // anyway. 2724 if (IsTypedefName && FTI.getExceptionSpecType()) 2725 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef) 2726 << (D.getContext() == Declarator::AliasDeclContext || 2727 D.getContext() == Declarator::AliasTemplateContext); 2728 2729 // If we see "T var();" or "T var(T());" at block scope, it is probably 2730 // an attempt to initialize a variable, not a function declaration. 2731 if (FTI.isAmbiguous) 2732 warnAboutAmbiguousFunction(S, D, DeclType, T); 2733 2734 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) { 2735 // Simple void foo(), where the incoming T is the result type. 2736 T = Context.getFunctionNoProtoType(T); 2737 } else { 2738 // We allow a zero-parameter variadic function in C if the 2739 // function is marked with the "overloadable" attribute. Scan 2740 // for this attribute now. 2741 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) { 2742 bool Overloadable = false; 2743 for (const AttributeList *Attrs = D.getAttributes(); 2744 Attrs; Attrs = Attrs->getNext()) { 2745 if (Attrs->getKind() == AttributeList::AT_Overloadable) { 2746 Overloadable = true; 2747 break; 2748 } 2749 } 2750 2751 if (!Overloadable) 2752 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); 2753 } 2754 2755 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) { 2756 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 2757 // definition. 2758 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 2759 D.setInvalidType(true); 2760 // Recover by creating a K&R-style function type. 2761 T = Context.getFunctionNoProtoType(T); 2762 break; 2763 } 2764 2765 FunctionProtoType::ExtProtoInfo EPI; 2766 EPI.Variadic = FTI.isVariadic; 2767 EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); 2768 EPI.TypeQuals = FTI.TypeQuals; 2769 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 2770 : FTI.RefQualifierIsLValueRef? RQ_LValue 2771 : RQ_RValue; 2772 2773 // Otherwise, we have a function with an argument list that is 2774 // potentially variadic. 2775 SmallVector<QualType, 16> ArgTys; 2776 ArgTys.reserve(FTI.NumArgs); 2777 2778 SmallVector<bool, 16> ConsumedArguments; 2779 ConsumedArguments.reserve(FTI.NumArgs); 2780 bool HasAnyConsumedArguments = false; 2781 2782 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 2783 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 2784 QualType ArgTy = Param->getType(); 2785 assert(!ArgTy.isNull() && "Couldn't parse type?"); 2786 2787 // Adjust the parameter type. 2788 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) && 2789 "Unadjusted type?"); 2790 2791 // Look for 'void'. void is allowed only as a single argument to a 2792 // function with no other parameters (C99 6.7.5.3p10). We record 2793 // int(void) as a FunctionProtoType with an empty argument list. 2794 if (ArgTy->isVoidType()) { 2795 // If this is something like 'float(int, void)', reject it. 'void' 2796 // is an incomplete type (C99 6.2.5p19) and function decls cannot 2797 // have arguments of incomplete type. 2798 if (FTI.NumArgs != 1 || FTI.isVariadic) { 2799 S.Diag(DeclType.Loc, diag::err_void_only_param); 2800 ArgTy = Context.IntTy; 2801 Param->setType(ArgTy); 2802 } else if (FTI.ArgInfo[i].Ident) { 2803 // Reject, but continue to parse 'int(void abc)'. 2804 S.Diag(FTI.ArgInfo[i].IdentLoc, 2805 diag::err_param_with_void_type); 2806 ArgTy = Context.IntTy; 2807 Param->setType(ArgTy); 2808 } else { 2809 // Reject, but continue to parse 'float(const void)'. 2810 if (ArgTy.hasQualifiers()) 2811 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 2812 2813 // Do not add 'void' to the ArgTys list. 2814 break; 2815 } 2816 } else if (ArgTy->isHalfType()) { 2817 // Disallow half FP arguments. 2818 // FIXME: This really should be in BuildFunctionType. 2819 if (S.getLangOpts().OpenCL) { 2820 if (!S.getOpenCLOptions().cl_khr_fp16) { 2821 S.Diag(Param->getLocation(), 2822 diag::err_opencl_half_argument) << ArgTy; 2823 D.setInvalidType(); 2824 Param->setInvalidDecl(); 2825 } 2826 } else { 2827 S.Diag(Param->getLocation(), 2828 diag::err_parameters_retval_cannot_have_fp16_type) << 0; 2829 D.setInvalidType(); 2830 } 2831 } else if (!FTI.hasPrototype) { 2832 if (ArgTy->isPromotableIntegerType()) { 2833 ArgTy = Context.getPromotedIntegerType(ArgTy); 2834 Param->setKNRPromoted(true); 2835 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) { 2836 if (BTy->getKind() == BuiltinType::Float) { 2837 ArgTy = Context.DoubleTy; 2838 Param->setKNRPromoted(true); 2839 } 2840 } 2841 } 2842 2843 if (LangOpts.ObjCAutoRefCount) { 2844 bool Consumed = Param->hasAttr<NSConsumedAttr>(); 2845 ConsumedArguments.push_back(Consumed); 2846 HasAnyConsumedArguments |= Consumed; 2847 } 2848 2849 ArgTys.push_back(ArgTy); 2850 } 2851 2852 if (HasAnyConsumedArguments) 2853 EPI.ConsumedArguments = ConsumedArguments.data(); 2854 2855 SmallVector<QualType, 4> Exceptions; 2856 SmallVector<ParsedType, 2> DynamicExceptions; 2857 SmallVector<SourceRange, 2> DynamicExceptionRanges; 2858 Expr *NoexceptExpr = 0; 2859 2860 if (FTI.getExceptionSpecType() == EST_Dynamic) { 2861 // FIXME: It's rather inefficient to have to split into two vectors 2862 // here. 2863 unsigned N = FTI.NumExceptions; 2864 DynamicExceptions.reserve(N); 2865 DynamicExceptionRanges.reserve(N); 2866 for (unsigned I = 0; I != N; ++I) { 2867 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 2868 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 2869 } 2870 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 2871 NoexceptExpr = FTI.NoexceptExpr; 2872 } 2873 2874 S.checkExceptionSpecification(FTI.getExceptionSpecType(), 2875 DynamicExceptions, 2876 DynamicExceptionRanges, 2877 NoexceptExpr, 2878 Exceptions, 2879 EPI); 2880 2881 T = Context.getFunctionType(T, ArgTys, EPI); 2882 } 2883 2884 break; 2885 } 2886 case DeclaratorChunk::MemberPointer: 2887 // The scope spec must refer to a class, or be dependent. 2888 CXXScopeSpec &SS = DeclType.Mem.Scope(); 2889 QualType ClsType; 2890 if (SS.isInvalid()) { 2891 // Avoid emitting extra errors if we already errored on the scope. 2892 D.setInvalidType(true); 2893 } else if (S.isDependentScopeSpecifier(SS) || 2894 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 2895 NestedNameSpecifier *NNS 2896 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2897 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 2898 switch (NNS->getKind()) { 2899 case NestedNameSpecifier::Identifier: 2900 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 2901 NNS->getAsIdentifier()); 2902 break; 2903 2904 case NestedNameSpecifier::Namespace: 2905 case NestedNameSpecifier::NamespaceAlias: 2906 case NestedNameSpecifier::Global: 2907 llvm_unreachable("Nested-name-specifier must name a type"); 2908 2909 case NestedNameSpecifier::TypeSpec: 2910 case NestedNameSpecifier::TypeSpecWithTemplate: 2911 ClsType = QualType(NNS->getAsType(), 0); 2912 // Note: if the NNS has a prefix and ClsType is a nondependent 2913 // TemplateSpecializationType, then the NNS prefix is NOT included 2914 // in ClsType; hence we wrap ClsType into an ElaboratedType. 2915 // NOTE: in particular, no wrap occurs if ClsType already is an 2916 // Elaborated, DependentName, or DependentTemplateSpecialization. 2917 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 2918 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 2919 break; 2920 } 2921 } else { 2922 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 2923 diag::err_illegal_decl_mempointer_in_nonclass) 2924 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 2925 << DeclType.Mem.Scope().getRange(); 2926 D.setInvalidType(true); 2927 } 2928 2929 if (!ClsType.isNull()) 2930 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier()); 2931 if (T.isNull()) { 2932 T = Context.IntTy; 2933 D.setInvalidType(true); 2934 } else if (DeclType.Mem.TypeQuals) { 2935 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 2936 } 2937 break; 2938 } 2939 2940 if (T.isNull()) { 2941 D.setInvalidType(true); 2942 T = Context.IntTy; 2943 } 2944 2945 // See if there are any attributes on this declarator chunk. 2946 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs())) 2947 processTypeAttrs(state, T, TAL_DeclChunk, attrs); 2948 } 2949 2950 if (LangOpts.CPlusPlus && T->isFunctionType()) { 2951 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 2952 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 2953 2954 // C++ 8.3.5p4: 2955 // A cv-qualifier-seq shall only be part of the function type 2956 // for a nonstatic member function, the function type to which a pointer 2957 // to member refers, or the top-level function type of a function typedef 2958 // declaration. 2959 // 2960 // Core issue 547 also allows cv-qualifiers on function types that are 2961 // top-level template type arguments. 2962 bool FreeFunction; 2963 if (!D.getCXXScopeSpec().isSet()) { 2964 FreeFunction = ((D.getContext() != Declarator::MemberContext && 2965 D.getContext() != Declarator::LambdaExprContext) || 2966 D.getDeclSpec().isFriendSpecified()); 2967 } else { 2968 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 2969 FreeFunction = (DC && !DC->isRecord()); 2970 } 2971 2972 // C++11 [dcl.fct]p6 (w/DR1417): 2973 // An attempt to specify a function type with a cv-qualifier-seq or a 2974 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 2975 // - the function type for a non-static member function, 2976 // - the function type to which a pointer to member refers, 2977 // - the top-level function type of a function typedef declaration or 2978 // alias-declaration, 2979 // - the type-id in the default argument of a type-parameter, or 2980 // - the type-id of a template-argument for a type-parameter 2981 if (IsQualifiedFunction && 2982 !(!FreeFunction && 2983 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 2984 !IsTypedefName && 2985 D.getContext() != Declarator::TemplateTypeArgContext) { 2986 SourceLocation Loc = D.getLocStart(); 2987 SourceRange RemovalRange; 2988 unsigned I; 2989 if (D.isFunctionDeclarator(I)) { 2990 SmallVector<SourceLocation, 4> RemovalLocs; 2991 const DeclaratorChunk &Chunk = D.getTypeObject(I); 2992 assert(Chunk.Kind == DeclaratorChunk::Function); 2993 if (Chunk.Fun.hasRefQualifier()) 2994 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 2995 if (Chunk.Fun.TypeQuals & Qualifiers::Const) 2996 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); 2997 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) 2998 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); 2999 // FIXME: We do not track the location of the __restrict qualifier. 3000 //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) 3001 // RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); 3002 if (!RemovalLocs.empty()) { 3003 std::sort(RemovalLocs.begin(), RemovalLocs.end(), 3004 BeforeThanCompare<SourceLocation>(S.getSourceManager())); 3005 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 3006 Loc = RemovalLocs.front(); 3007 } 3008 } 3009 3010 S.Diag(Loc, diag::err_invalid_qualified_function_type) 3011 << FreeFunction << D.isFunctionDeclarator() << T 3012 << getFunctionQualifiersAsString(FnTy) 3013 << FixItHint::CreateRemoval(RemovalRange); 3014 3015 // Strip the cv-qualifiers and ref-qualifiers from the type. 3016 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 3017 EPI.TypeQuals = 0; 3018 EPI.RefQualifier = RQ_None; 3019 3020 T = Context.getFunctionType(FnTy->getResultType(), 3021 ArrayRef<QualType>(FnTy->arg_type_begin(), 3022 FnTy->getNumArgs()), 3023 EPI); 3024 // Rebuild any parens around the identifier in the function type. 3025 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3026 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) 3027 break; 3028 T = S.BuildParenType(T); 3029 } 3030 } 3031 } 3032 3033 // Apply any undistributed attributes from the declarator. 3034 if (!T.isNull()) 3035 if (AttributeList *attrs = D.getAttributes()) 3036 processTypeAttrs(state, T, TAL_DeclName, attrs); 3037 3038 // Diagnose any ignored type attributes. 3039 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T); 3040 3041 // C++0x [dcl.constexpr]p9: 3042 // A constexpr specifier used in an object declaration declares the object 3043 // as const. 3044 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 3045 T.addConst(); 3046 } 3047 3048 // If there was an ellipsis in the declarator, the declaration declares a 3049 // parameter pack whose type may be a pack expansion type. 3050 if (D.hasEllipsis() && !T.isNull()) { 3051 // C++0x [dcl.fct]p13: 3052 // A declarator-id or abstract-declarator containing an ellipsis shall 3053 // only be used in a parameter-declaration. Such a parameter-declaration 3054 // is a parameter pack (14.5.3). [...] 3055 switch (D.getContext()) { 3056 case Declarator::PrototypeContext: 3057 // C++0x [dcl.fct]p13: 3058 // [...] When it is part of a parameter-declaration-clause, the 3059 // parameter pack is a function parameter pack (14.5.3). The type T 3060 // of the declarator-id of the function parameter pack shall contain 3061 // a template parameter pack; each template parameter pack in T is 3062 // expanded by the function parameter pack. 3063 // 3064 // We represent function parameter packs as function parameters whose 3065 // type is a pack expansion. 3066 if (!T->containsUnexpandedParameterPack()) { 3067 S.Diag(D.getEllipsisLoc(), 3068 diag::err_function_parameter_pack_without_parameter_packs) 3069 << T << D.getSourceRange(); 3070 D.setEllipsisLoc(SourceLocation()); 3071 } else { 3072 T = Context.getPackExpansionType(T, None); 3073 } 3074 break; 3075 3076 case Declarator::TemplateParamContext: 3077 // C++0x [temp.param]p15: 3078 // If a template-parameter is a [...] is a parameter-declaration that 3079 // declares a parameter pack (8.3.5), then the template-parameter is a 3080 // template parameter pack (14.5.3). 3081 // 3082 // Note: core issue 778 clarifies that, if there are any unexpanded 3083 // parameter packs in the type of the non-type template parameter, then 3084 // it expands those parameter packs. 3085 if (T->containsUnexpandedParameterPack()) 3086 T = Context.getPackExpansionType(T, None); 3087 else 3088 S.Diag(D.getEllipsisLoc(), 3089 LangOpts.CPlusPlus11 3090 ? diag::warn_cxx98_compat_variadic_templates 3091 : diag::ext_variadic_templates); 3092 break; 3093 3094 case Declarator::FileContext: 3095 case Declarator::KNRTypeListContext: 3096 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here? 3097 case Declarator::ObjCResultContext: // FIXME: special diagnostic here? 3098 case Declarator::TypeNameContext: 3099 case Declarator::CXXNewContext: 3100 case Declarator::AliasDeclContext: 3101 case Declarator::AliasTemplateContext: 3102 case Declarator::MemberContext: 3103 case Declarator::BlockContext: 3104 case Declarator::ForContext: 3105 case Declarator::ConditionContext: 3106 case Declarator::CXXCatchContext: 3107 case Declarator::ObjCCatchContext: 3108 case Declarator::BlockLiteralContext: 3109 case Declarator::LambdaExprContext: 3110 case Declarator::ConversionIdContext: 3111 case Declarator::TrailingReturnContext: 3112 case Declarator::TemplateTypeArgContext: 3113 // FIXME: We may want to allow parameter packs in block-literal contexts 3114 // in the future. 3115 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter); 3116 D.setEllipsisLoc(SourceLocation()); 3117 break; 3118 } 3119 } 3120 3121 if (T.isNull()) 3122 return Context.getNullTypeSourceInfo(); 3123 else if (D.isInvalidType()) 3124 return Context.getTrivialTypeSourceInfo(T); 3125 3126 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); 3127 } 3128 3129 /// GetTypeForDeclarator - Convert the type for the specified 3130 /// declarator to Type instances. 3131 /// 3132 /// The result of this call will never be null, but the associated 3133 /// type may be a null type if there's an unrecoverable error. 3134 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 3135 // Determine the type of the declarator. Not all forms of declarator 3136 // have a type. 3137 3138 TypeProcessingState state(*this, D); 3139 3140 TypeSourceInfo *ReturnTypeInfo = 0; 3141 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 3142 if (T.isNull()) 3143 return Context.getNullTypeSourceInfo(); 3144 3145 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 3146 inferARCWriteback(state, T); 3147 3148 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 3149 } 3150 3151 static void transferARCOwnershipToDeclSpec(Sema &S, 3152 QualType &declSpecTy, 3153 Qualifiers::ObjCLifetime ownership) { 3154 if (declSpecTy->isObjCRetainableType() && 3155 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 3156 Qualifiers qs; 3157 qs.addObjCLifetime(ownership); 3158 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 3159 } 3160 } 3161 3162 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 3163 Qualifiers::ObjCLifetime ownership, 3164 unsigned chunkIndex) { 3165 Sema &S = state.getSema(); 3166 Declarator &D = state.getDeclarator(); 3167 3168 // Look for an explicit lifetime attribute. 3169 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 3170 for (const AttributeList *attr = chunk.getAttrs(); attr; 3171 attr = attr->getNext()) 3172 if (attr->getKind() == AttributeList::AT_ObjCOwnership) 3173 return; 3174 3175 const char *attrStr = 0; 3176 switch (ownership) { 3177 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 3178 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 3179 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 3180 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 3181 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 3182 } 3183 3184 // If there wasn't one, add one (with an invalid source location 3185 // so that we don't make an AttributedType for it). 3186 AttributeList *attr = D.getAttributePool() 3187 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), 3188 /*scope*/ 0, SourceLocation(), 3189 &S.Context.Idents.get(attrStr), SourceLocation(), 3190 /*args*/ 0, 0, AttributeList::AS_GNU); 3191 spliceAttrIntoList(*attr, chunk.getAttrListRef()); 3192 3193 // TODO: mark whether we did this inference? 3194 } 3195 3196 /// \brief Used for transferring ownership in casts resulting in l-values. 3197 static void transferARCOwnership(TypeProcessingState &state, 3198 QualType &declSpecTy, 3199 Qualifiers::ObjCLifetime ownership) { 3200 Sema &S = state.getSema(); 3201 Declarator &D = state.getDeclarator(); 3202 3203 int inner = -1; 3204 bool hasIndirection = false; 3205 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3206 DeclaratorChunk &chunk = D.getTypeObject(i); 3207 switch (chunk.Kind) { 3208 case DeclaratorChunk::Paren: 3209 // Ignore parens. 3210 break; 3211 3212 case DeclaratorChunk::Array: 3213 case DeclaratorChunk::Reference: 3214 case DeclaratorChunk::Pointer: 3215 if (inner != -1) 3216 hasIndirection = true; 3217 inner = i; 3218 break; 3219 3220 case DeclaratorChunk::BlockPointer: 3221 if (inner != -1) 3222 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 3223 return; 3224 3225 case DeclaratorChunk::Function: 3226 case DeclaratorChunk::MemberPointer: 3227 return; 3228 } 3229 } 3230 3231 if (inner == -1) 3232 return; 3233 3234 DeclaratorChunk &chunk = D.getTypeObject(inner); 3235 if (chunk.Kind == DeclaratorChunk::Pointer) { 3236 if (declSpecTy->isObjCRetainableType()) 3237 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 3238 if (declSpecTy->isObjCObjectType() && hasIndirection) 3239 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 3240 } else { 3241 assert(chunk.Kind == DeclaratorChunk::Array || 3242 chunk.Kind == DeclaratorChunk::Reference); 3243 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 3244 } 3245 } 3246 3247 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 3248 TypeProcessingState state(*this, D); 3249 3250 TypeSourceInfo *ReturnTypeInfo = 0; 3251 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 3252 if (declSpecTy.isNull()) 3253 return Context.getNullTypeSourceInfo(); 3254 3255 if (getLangOpts().ObjCAutoRefCount) { 3256 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 3257 if (ownership != Qualifiers::OCL_None) 3258 transferARCOwnership(state, declSpecTy, ownership); 3259 } 3260 3261 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 3262 } 3263 3264 /// Map an AttributedType::Kind to an AttributeList::Kind. 3265 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 3266 switch (kind) { 3267 case AttributedType::attr_address_space: 3268 return AttributeList::AT_AddressSpace; 3269 case AttributedType::attr_regparm: 3270 return AttributeList::AT_Regparm; 3271 case AttributedType::attr_vector_size: 3272 return AttributeList::AT_VectorSize; 3273 case AttributedType::attr_neon_vector_type: 3274 return AttributeList::AT_NeonVectorType; 3275 case AttributedType::attr_neon_polyvector_type: 3276 return AttributeList::AT_NeonPolyVectorType; 3277 case AttributedType::attr_objc_gc: 3278 return AttributeList::AT_ObjCGC; 3279 case AttributedType::attr_objc_ownership: 3280 return AttributeList::AT_ObjCOwnership; 3281 case AttributedType::attr_noreturn: 3282 return AttributeList::AT_NoReturn; 3283 case AttributedType::attr_cdecl: 3284 return AttributeList::AT_CDecl; 3285 case AttributedType::attr_fastcall: 3286 return AttributeList::AT_FastCall; 3287 case AttributedType::attr_stdcall: 3288 return AttributeList::AT_StdCall; 3289 case AttributedType::attr_thiscall: 3290 return AttributeList::AT_ThisCall; 3291 case AttributedType::attr_pascal: 3292 return AttributeList::AT_Pascal; 3293 case AttributedType::attr_pcs: 3294 return AttributeList::AT_Pcs; 3295 case AttributedType::attr_pnaclcall: 3296 return AttributeList::AT_PnaclCall; 3297 case AttributedType::attr_inteloclbicc: 3298 return AttributeList::AT_IntelOclBicc; 3299 } 3300 llvm_unreachable("unexpected attribute kind!"); 3301 } 3302 3303 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 3304 const AttributeList *attrs) { 3305 AttributedType::Kind kind = TL.getAttrKind(); 3306 3307 assert(attrs && "no type attributes in the expected location!"); 3308 AttributeList::Kind parsedKind = getAttrListKind(kind); 3309 while (attrs->getKind() != parsedKind) { 3310 attrs = attrs->getNext(); 3311 assert(attrs && "no matching attribute in expected location!"); 3312 } 3313 3314 TL.setAttrNameLoc(attrs->getLoc()); 3315 if (TL.hasAttrExprOperand()) 3316 TL.setAttrExprOperand(attrs->getArg(0)); 3317 else if (TL.hasAttrEnumOperand()) 3318 TL.setAttrEnumOperandLoc(attrs->getParameterLoc()); 3319 3320 // FIXME: preserve this information to here. 3321 if (TL.hasAttrOperand()) 3322 TL.setAttrOperandParensRange(SourceRange()); 3323 } 3324 3325 namespace { 3326 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 3327 ASTContext &Context; 3328 const DeclSpec &DS; 3329 3330 public: 3331 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 3332 : Context(Context), DS(DS) {} 3333 3334 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 3335 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 3336 Visit(TL.getModifiedLoc()); 3337 } 3338 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 3339 Visit(TL.getUnqualifiedLoc()); 3340 } 3341 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 3342 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 3343 } 3344 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 3345 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 3346 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 3347 // addition field. What we have is good enough for dispay of location 3348 // of 'fixit' on interface name. 3349 TL.setNameEndLoc(DS.getLocEnd()); 3350 } 3351 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 3352 // Handle the base type, which might not have been written explicitly. 3353 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { 3354 TL.setHasBaseTypeAsWritten(false); 3355 TL.getBaseLoc().initialize(Context, SourceLocation()); 3356 } else { 3357 TL.setHasBaseTypeAsWritten(true); 3358 Visit(TL.getBaseLoc()); 3359 } 3360 3361 // Protocol qualifiers. 3362 if (DS.getProtocolQualifiers()) { 3363 assert(TL.getNumProtocols() > 0); 3364 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers()); 3365 TL.setLAngleLoc(DS.getProtocolLAngleLoc()); 3366 TL.setRAngleLoc(DS.getSourceRange().getEnd()); 3367 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i) 3368 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]); 3369 } else { 3370 assert(TL.getNumProtocols() == 0); 3371 TL.setLAngleLoc(SourceLocation()); 3372 TL.setRAngleLoc(SourceLocation()); 3373 } 3374 } 3375 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 3376 TL.setStarLoc(SourceLocation()); 3377 Visit(TL.getPointeeLoc()); 3378 } 3379 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 3380 TypeSourceInfo *TInfo = 0; 3381 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3382 3383 // If we got no declarator info from previous Sema routines, 3384 // just fill with the typespec loc. 3385 if (!TInfo) { 3386 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 3387 return; 3388 } 3389 3390 TypeLoc OldTL = TInfo->getTypeLoc(); 3391 if (TInfo->getType()->getAs<ElaboratedType>()) { 3392 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); 3393 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() 3394 .castAs<TemplateSpecializationTypeLoc>(); 3395 TL.copy(NamedTL); 3396 } 3397 else 3398 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); 3399 } 3400 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 3401 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 3402 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 3403 TL.setParensRange(DS.getTypeofParensRange()); 3404 } 3405 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 3406 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 3407 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 3408 TL.setParensRange(DS.getTypeofParensRange()); 3409 assert(DS.getRepAsType()); 3410 TypeSourceInfo *TInfo = 0; 3411 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3412 TL.setUnderlyingTInfo(TInfo); 3413 } 3414 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 3415 // FIXME: This holds only because we only have one unary transform. 3416 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 3417 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 3418 TL.setParensRange(DS.getTypeofParensRange()); 3419 assert(DS.getRepAsType()); 3420 TypeSourceInfo *TInfo = 0; 3421 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3422 TL.setUnderlyingTInfo(TInfo); 3423 } 3424 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 3425 // By default, use the source location of the type specifier. 3426 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 3427 if (TL.needsExtraLocalData()) { 3428 // Set info for the written builtin specifiers. 3429 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 3430 // Try to have a meaningful source location. 3431 if (TL.getWrittenSignSpec() != TSS_unspecified) 3432 // Sign spec loc overrides the others (e.g., 'unsigned long'). 3433 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 3434 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 3435 // Width spec loc overrides type spec loc (e.g., 'short int'). 3436 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 3437 } 3438 } 3439 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 3440 ElaboratedTypeKeyword Keyword 3441 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 3442 if (DS.getTypeSpecType() == TST_typename) { 3443 TypeSourceInfo *TInfo = 0; 3444 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3445 if (TInfo) { 3446 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); 3447 return; 3448 } 3449 } 3450 TL.setElaboratedKeywordLoc(Keyword != ETK_None 3451 ? DS.getTypeSpecTypeLoc() 3452 : SourceLocation()); 3453 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 3454 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3455 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 3456 } 3457 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 3458 assert(DS.getTypeSpecType() == TST_typename); 3459 TypeSourceInfo *TInfo = 0; 3460 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3461 assert(TInfo); 3462 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); 3463 } 3464 void VisitDependentTemplateSpecializationTypeLoc( 3465 DependentTemplateSpecializationTypeLoc TL) { 3466 assert(DS.getTypeSpecType() == TST_typename); 3467 TypeSourceInfo *TInfo = 0; 3468 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3469 assert(TInfo); 3470 TL.copy( 3471 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); 3472 } 3473 void VisitTagTypeLoc(TagTypeLoc TL) { 3474 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 3475 } 3476 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 3477 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier 3478 // or an _Atomic qualifier. 3479 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { 3480 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 3481 TL.setParensRange(DS.getTypeofParensRange()); 3482 3483 TypeSourceInfo *TInfo = 0; 3484 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 3485 assert(TInfo); 3486 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 3487 } else { 3488 TL.setKWLoc(DS.getAtomicSpecLoc()); 3489 // No parens, to indicate this was spelled as an _Atomic qualifier. 3490 TL.setParensRange(SourceRange()); 3491 Visit(TL.getValueLoc()); 3492 } 3493 } 3494 3495 void VisitTypeLoc(TypeLoc TL) { 3496 // FIXME: add other typespec types and change this to an assert. 3497 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 3498 } 3499 }; 3500 3501 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 3502 ASTContext &Context; 3503 const DeclaratorChunk &Chunk; 3504 3505 public: 3506 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 3507 : Context(Context), Chunk(Chunk) {} 3508 3509 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 3510 llvm_unreachable("qualified type locs not expected here!"); 3511 } 3512 3513 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 3514 fillAttributedTypeLoc(TL, Chunk.getAttrs()); 3515 } 3516 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 3517 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 3518 TL.setCaretLoc(Chunk.Loc); 3519 } 3520 void VisitPointerTypeLoc(PointerTypeLoc TL) { 3521 assert(Chunk.Kind == DeclaratorChunk::Pointer); 3522 TL.setStarLoc(Chunk.Loc); 3523 } 3524 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 3525 assert(Chunk.Kind == DeclaratorChunk::Pointer); 3526 TL.setStarLoc(Chunk.Loc); 3527 } 3528 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 3529 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 3530 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 3531 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 3532 3533 const Type* ClsTy = TL.getClass(); 3534 QualType ClsQT = QualType(ClsTy, 0); 3535 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 3536 // Now copy source location info into the type loc component. 3537 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 3538 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 3539 case NestedNameSpecifier::Identifier: 3540 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 3541 { 3542 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); 3543 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 3544 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 3545 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 3546 } 3547 break; 3548 3549 case NestedNameSpecifier::TypeSpec: 3550 case NestedNameSpecifier::TypeSpecWithTemplate: 3551 if (isa<ElaboratedType>(ClsTy)) { 3552 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); 3553 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 3554 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 3555 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 3556 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 3557 } else { 3558 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 3559 } 3560 break; 3561 3562 case NestedNameSpecifier::Namespace: 3563 case NestedNameSpecifier::NamespaceAlias: 3564 case NestedNameSpecifier::Global: 3565 llvm_unreachable("Nested-name-specifier must name a type"); 3566 } 3567 3568 // Finally fill in MemberPointerLocInfo fields. 3569 TL.setStarLoc(Chunk.Loc); 3570 TL.setClassTInfo(ClsTInfo); 3571 } 3572 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 3573 assert(Chunk.Kind == DeclaratorChunk::Reference); 3574 // 'Amp' is misleading: this might have been originally 3575 /// spelled with AmpAmp. 3576 TL.setAmpLoc(Chunk.Loc); 3577 } 3578 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 3579 assert(Chunk.Kind == DeclaratorChunk::Reference); 3580 assert(!Chunk.Ref.LValueRef); 3581 TL.setAmpAmpLoc(Chunk.Loc); 3582 } 3583 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 3584 assert(Chunk.Kind == DeclaratorChunk::Array); 3585 TL.setLBracketLoc(Chunk.Loc); 3586 TL.setRBracketLoc(Chunk.EndLoc); 3587 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 3588 } 3589 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 3590 assert(Chunk.Kind == DeclaratorChunk::Function); 3591 TL.setLocalRangeBegin(Chunk.Loc); 3592 TL.setLocalRangeEnd(Chunk.EndLoc); 3593 3594 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 3595 TL.setLParenLoc(FTI.getLParenLoc()); 3596 TL.setRParenLoc(FTI.getRParenLoc()); 3597 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) { 3598 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 3599 TL.setArg(tpi++, Param); 3600 } 3601 // FIXME: exception specs 3602 } 3603 void VisitParenTypeLoc(ParenTypeLoc TL) { 3604 assert(Chunk.Kind == DeclaratorChunk::Paren); 3605 TL.setLParenLoc(Chunk.Loc); 3606 TL.setRParenLoc(Chunk.EndLoc); 3607 } 3608 3609 void VisitTypeLoc(TypeLoc TL) { 3610 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 3611 } 3612 }; 3613 } 3614 3615 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { 3616 SourceLocation Loc; 3617 switch (Chunk.Kind) { 3618 case DeclaratorChunk::Function: 3619 case DeclaratorChunk::Array: 3620 case DeclaratorChunk::Paren: 3621 llvm_unreachable("cannot be _Atomic qualified"); 3622 3623 case DeclaratorChunk::Pointer: 3624 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc); 3625 break; 3626 3627 case DeclaratorChunk::BlockPointer: 3628 case DeclaratorChunk::Reference: 3629 case DeclaratorChunk::MemberPointer: 3630 // FIXME: Provide a source location for the _Atomic keyword. 3631 break; 3632 } 3633 3634 ATL.setKWLoc(Loc); 3635 ATL.setParensRange(SourceRange()); 3636 } 3637 3638 /// \brief Create and instantiate a TypeSourceInfo with type source information. 3639 /// 3640 /// \param T QualType referring to the type as written in source code. 3641 /// 3642 /// \param ReturnTypeInfo For declarators whose return type does not show 3643 /// up in the normal place in the declaration specifiers (such as a C++ 3644 /// conversion function), this pointer will refer to a type source information 3645 /// for that return type. 3646 TypeSourceInfo * 3647 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 3648 TypeSourceInfo *ReturnTypeInfo) { 3649 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 3650 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 3651 3652 // Handle parameter packs whose type is a pack expansion. 3653 if (isa<PackExpansionType>(T)) { 3654 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); 3655 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 3656 } 3657 3658 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 3659 // An AtomicTypeLoc might be produced by an atomic qualifier in this 3660 // declarator chunk. 3661 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { 3662 fillAtomicQualLoc(ATL, D.getTypeObject(i)); 3663 CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); 3664 } 3665 3666 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { 3667 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs()); 3668 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 3669 } 3670 3671 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 3672 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 3673 } 3674 3675 // If we have different source information for the return type, use 3676 // that. This really only applies to C++ conversion functions. 3677 if (ReturnTypeInfo) { 3678 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 3679 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 3680 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 3681 } else { 3682 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 3683 } 3684 3685 return TInfo; 3686 } 3687 3688 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 3689 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 3690 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 3691 // and Sema during declaration parsing. Try deallocating/caching them when 3692 // it's appropriate, instead of allocating them and keeping them around. 3693 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 3694 TypeAlignment); 3695 new (LocT) LocInfoType(T, TInfo); 3696 assert(LocT->getTypeClass() != T->getTypeClass() && 3697 "LocInfoType's TypeClass conflicts with an existing Type class"); 3698 return ParsedType::make(QualType(LocT, 0)); 3699 } 3700 3701 void LocInfoType::getAsStringInternal(std::string &Str, 3702 const PrintingPolicy &Policy) const { 3703 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 3704 " was used directly instead of getting the QualType through" 3705 " GetTypeFromParser"); 3706 } 3707 3708 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 3709 // C99 6.7.6: Type names have no identifier. This is already validated by 3710 // the parser. 3711 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 3712 3713 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3714 QualType T = TInfo->getType(); 3715 if (D.isInvalidType()) 3716 return true; 3717 3718 // Make sure there are no unused decl attributes on the declarator. 3719 // We don't want to do this for ObjC parameters because we're going 3720 // to apply them to the actual parameter declaration. 3721 // Likewise, we don't want to do this for alias declarations, because 3722 // we are actually going to build a declaration from this eventually. 3723 if (D.getContext() != Declarator::ObjCParameterContext && 3724 D.getContext() != Declarator::AliasDeclContext && 3725 D.getContext() != Declarator::AliasTemplateContext) 3726 checkUnusedDeclAttributes(D); 3727 3728 if (getLangOpts().CPlusPlus) { 3729 // Check that there are no default arguments (C++ only). 3730 CheckExtraCXXDefaultArguments(D); 3731 } 3732 3733 return CreateParsedType(T, TInfo); 3734 } 3735 3736 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 3737 QualType T = Context.getObjCInstanceType(); 3738 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 3739 return CreateParsedType(T, TInfo); 3740 } 3741 3742 3743 //===----------------------------------------------------------------------===// 3744 // Type Attribute Processing 3745 //===----------------------------------------------------------------------===// 3746 3747 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 3748 /// specified type. The attribute contains 1 argument, the id of the address 3749 /// space for the type. 3750 static void HandleAddressSpaceTypeAttribute(QualType &Type, 3751 const AttributeList &Attr, Sema &S){ 3752 3753 // If this type is already address space qualified, reject it. 3754 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by 3755 // qualifiers for two or more different address spaces." 3756 if (Type.getAddressSpace()) { 3757 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 3758 Attr.setInvalid(); 3759 return; 3760 } 3761 3762 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 3763 // qualified by an address-space qualifier." 3764 if (Type->isFunctionType()) { 3765 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 3766 Attr.setInvalid(); 3767 return; 3768 } 3769 3770 // Check the attribute arguments. 3771 if (Attr.getNumArgs() != 1) { 3772 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 3773 Attr.setInvalid(); 3774 return; 3775 } 3776 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 3777 llvm::APSInt addrSpace(32); 3778 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 3779 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 3780 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) 3781 << ASArgExpr->getSourceRange(); 3782 Attr.setInvalid(); 3783 return; 3784 } 3785 3786 // Bounds checking. 3787 if (addrSpace.isSigned()) { 3788 if (addrSpace.isNegative()) { 3789 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 3790 << ASArgExpr->getSourceRange(); 3791 Attr.setInvalid(); 3792 return; 3793 } 3794 addrSpace.setIsSigned(false); 3795 } 3796 llvm::APSInt max(addrSpace.getBitWidth()); 3797 max = Qualifiers::MaxAddressSpace; 3798 if (addrSpace > max) { 3799 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 3800 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange(); 3801 Attr.setInvalid(); 3802 return; 3803 } 3804 3805 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 3806 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 3807 } 3808 3809 /// Does this type have a "direct" ownership qualifier? That is, 3810 /// is it written like "__strong id", as opposed to something like 3811 /// "typeof(foo)", where that happens to be strong? 3812 static bool hasDirectOwnershipQualifier(QualType type) { 3813 // Fast path: no qualifier at all. 3814 assert(type.getQualifiers().hasObjCLifetime()); 3815 3816 while (true) { 3817 // __strong id 3818 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { 3819 if (attr->getAttrKind() == AttributedType::attr_objc_ownership) 3820 return true; 3821 3822 type = attr->getModifiedType(); 3823 3824 // X *__strong (...) 3825 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { 3826 type = paren->getInnerType(); 3827 3828 // That's it for things we want to complain about. In particular, 3829 // we do not want to look through typedefs, typeof(expr), 3830 // typeof(type), or any other way that the type is somehow 3831 // abstracted. 3832 } else { 3833 3834 return false; 3835 } 3836 } 3837 } 3838 3839 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 3840 /// attribute on the specified type. 3841 /// 3842 /// Returns 'true' if the attribute was handled. 3843 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 3844 AttributeList &attr, 3845 QualType &type) { 3846 bool NonObjCPointer = false; 3847 3848 if (!type->isDependentType() && !type->isUndeducedType()) { 3849 if (const PointerType *ptr = type->getAs<PointerType>()) { 3850 QualType pointee = ptr->getPointeeType(); 3851 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 3852 return false; 3853 // It is important not to lose the source info that there was an attribute 3854 // applied to non-objc pointer. We will create an attributed type but 3855 // its type will be the same as the original type. 3856 NonObjCPointer = true; 3857 } else if (!type->isObjCRetainableType()) { 3858 return false; 3859 } 3860 3861 // Don't accept an ownership attribute in the declspec if it would 3862 // just be the return type of a block pointer. 3863 if (state.isProcessingDeclSpec()) { 3864 Declarator &D = state.getDeclarator(); 3865 if (maybeMovePastReturnType(D, D.getNumTypeObjects())) 3866 return false; 3867 } 3868 } 3869 3870 Sema &S = state.getSema(); 3871 SourceLocation AttrLoc = attr.getLoc(); 3872 if (AttrLoc.isMacroID()) 3873 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first; 3874 3875 if (!attr.getParameterName()) { 3876 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string) 3877 << "objc_ownership" << 1; 3878 attr.setInvalid(); 3879 return true; 3880 } 3881 3882 // Consume lifetime attributes without further comment outside of 3883 // ARC mode. 3884 if (!S.getLangOpts().ObjCAutoRefCount) 3885 return true; 3886 3887 Qualifiers::ObjCLifetime lifetime; 3888 if (attr.getParameterName()->isStr("none")) 3889 lifetime = Qualifiers::OCL_ExplicitNone; 3890 else if (attr.getParameterName()->isStr("strong")) 3891 lifetime = Qualifiers::OCL_Strong; 3892 else if (attr.getParameterName()->isStr("weak")) 3893 lifetime = Qualifiers::OCL_Weak; 3894 else if (attr.getParameterName()->isStr("autoreleasing")) 3895 lifetime = Qualifiers::OCL_Autoreleasing; 3896 else { 3897 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 3898 << "objc_ownership" << attr.getParameterName(); 3899 attr.setInvalid(); 3900 return true; 3901 } 3902 3903 SplitQualType underlyingType = type.split(); 3904 3905 // Check for redundant/conflicting ownership qualifiers. 3906 if (Qualifiers::ObjCLifetime previousLifetime 3907 = type.getQualifiers().getObjCLifetime()) { 3908 // If it's written directly, that's an error. 3909 if (hasDirectOwnershipQualifier(type)) { 3910 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 3911 << type; 3912 return true; 3913 } 3914 3915 // Otherwise, if the qualifiers actually conflict, pull sugar off 3916 // until we reach a type that is directly qualified. 3917 if (previousLifetime != lifetime) { 3918 // This should always terminate: the canonical type is 3919 // qualified, so some bit of sugar must be hiding it. 3920 while (!underlyingType.Quals.hasObjCLifetime()) { 3921 underlyingType = underlyingType.getSingleStepDesugaredType(); 3922 } 3923 underlyingType.Quals.removeObjCLifetime(); 3924 } 3925 } 3926 3927 underlyingType.Quals.addObjCLifetime(lifetime); 3928 3929 if (NonObjCPointer) { 3930 StringRef name = attr.getName()->getName(); 3931 switch (lifetime) { 3932 case Qualifiers::OCL_None: 3933 case Qualifiers::OCL_ExplicitNone: 3934 break; 3935 case Qualifiers::OCL_Strong: name = "__strong"; break; 3936 case Qualifiers::OCL_Weak: name = "__weak"; break; 3937 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 3938 } 3939 S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type) 3940 << name << type; 3941 } 3942 3943 QualType origType = type; 3944 if (!NonObjCPointer) 3945 type = S.Context.getQualifiedType(underlyingType); 3946 3947 // If we have a valid source location for the attribute, use an 3948 // AttributedType instead. 3949 if (AttrLoc.isValid()) 3950 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, 3951 origType, type); 3952 3953 // Forbid __weak if the runtime doesn't support it. 3954 if (lifetime == Qualifiers::OCL_Weak && 3955 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) { 3956 3957 // Actually, delay this until we know what we're parsing. 3958 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 3959 S.DelayedDiagnostics.add( 3960 sema::DelayedDiagnostic::makeForbiddenType( 3961 S.getSourceManager().getExpansionLoc(AttrLoc), 3962 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0)); 3963 } else { 3964 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime); 3965 } 3966 3967 attr.setInvalid(); 3968 return true; 3969 } 3970 3971 // Forbid __weak for class objects marked as 3972 // objc_arc_weak_reference_unavailable 3973 if (lifetime == Qualifiers::OCL_Weak) { 3974 if (const ObjCObjectPointerType *ObjT = 3975 type->getAs<ObjCObjectPointerType>()) { 3976 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { 3977 if (Class->isArcWeakrefUnavailable()) { 3978 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 3979 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 3980 diag::note_class_declared); 3981 } 3982 } 3983 } 3984 } 3985 3986 return true; 3987 } 3988 3989 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 3990 /// attribute on the specified type. Returns true to indicate that 3991 /// the attribute was handled, false to indicate that the type does 3992 /// not permit the attribute. 3993 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 3994 AttributeList &attr, 3995 QualType &type) { 3996 Sema &S = state.getSema(); 3997 3998 // Delay if this isn't some kind of pointer. 3999 if (!type->isPointerType() && 4000 !type->isObjCObjectPointerType() && 4001 !type->isBlockPointerType()) 4002 return false; 4003 4004 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 4005 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 4006 attr.setInvalid(); 4007 return true; 4008 } 4009 4010 // Check the attribute arguments. 4011 if (!attr.getParameterName()) { 4012 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string) 4013 << "objc_gc" << 1; 4014 attr.setInvalid(); 4015 return true; 4016 } 4017 Qualifiers::GC GCAttr; 4018 if (attr.getNumArgs() != 0) { 4019 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 4020 attr.setInvalid(); 4021 return true; 4022 } 4023 if (attr.getParameterName()->isStr("weak")) 4024 GCAttr = Qualifiers::Weak; 4025 else if (attr.getParameterName()->isStr("strong")) 4026 GCAttr = Qualifiers::Strong; 4027 else { 4028 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 4029 << "objc_gc" << attr.getParameterName(); 4030 attr.setInvalid(); 4031 return true; 4032 } 4033 4034 QualType origType = type; 4035 type = S.Context.getObjCGCQualType(origType, GCAttr); 4036 4037 // Make an attributed type to preserve the source information. 4038 if (attr.getLoc().isValid()) 4039 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 4040 origType, type); 4041 4042 return true; 4043 } 4044 4045 namespace { 4046 /// A helper class to unwrap a type down to a function for the 4047 /// purposes of applying attributes there. 4048 /// 4049 /// Use: 4050 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 4051 /// if (unwrapped.isFunctionType()) { 4052 /// const FunctionType *fn = unwrapped.get(); 4053 /// // change fn somehow 4054 /// T = unwrapped.wrap(fn); 4055 /// } 4056 struct FunctionTypeUnwrapper { 4057 enum WrapKind { 4058 Desugar, 4059 Parens, 4060 Pointer, 4061 BlockPointer, 4062 Reference, 4063 MemberPointer 4064 }; 4065 4066 QualType Original; 4067 const FunctionType *Fn; 4068 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 4069 4070 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 4071 while (true) { 4072 const Type *Ty = T.getTypePtr(); 4073 if (isa<FunctionType>(Ty)) { 4074 Fn = cast<FunctionType>(Ty); 4075 return; 4076 } else if (isa<ParenType>(Ty)) { 4077 T = cast<ParenType>(Ty)->getInnerType(); 4078 Stack.push_back(Parens); 4079 } else if (isa<PointerType>(Ty)) { 4080 T = cast<PointerType>(Ty)->getPointeeType(); 4081 Stack.push_back(Pointer); 4082 } else if (isa<BlockPointerType>(Ty)) { 4083 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4084 Stack.push_back(BlockPointer); 4085 } else if (isa<MemberPointerType>(Ty)) { 4086 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4087 Stack.push_back(MemberPointer); 4088 } else if (isa<ReferenceType>(Ty)) { 4089 T = cast<ReferenceType>(Ty)->getPointeeType(); 4090 Stack.push_back(Reference); 4091 } else { 4092 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 4093 if (Ty == DTy) { 4094 Fn = 0; 4095 return; 4096 } 4097 4098 T = QualType(DTy, 0); 4099 Stack.push_back(Desugar); 4100 } 4101 } 4102 } 4103 4104 bool isFunctionType() const { return (Fn != 0); } 4105 const FunctionType *get() const { return Fn; } 4106 4107 QualType wrap(Sema &S, const FunctionType *New) { 4108 // If T wasn't modified from the unwrapped type, do nothing. 4109 if (New == get()) return Original; 4110 4111 Fn = New; 4112 return wrap(S.Context, Original, 0); 4113 } 4114 4115 private: 4116 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 4117 if (I == Stack.size()) 4118 return C.getQualifiedType(Fn, Old.getQualifiers()); 4119 4120 // Build up the inner type, applying the qualifiers from the old 4121 // type to the new type. 4122 SplitQualType SplitOld = Old.split(); 4123 4124 // As a special case, tail-recurse if there are no qualifiers. 4125 if (SplitOld.Quals.empty()) 4126 return wrap(C, SplitOld.Ty, I); 4127 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 4128 } 4129 4130 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 4131 if (I == Stack.size()) return QualType(Fn, 0); 4132 4133 switch (static_cast<WrapKind>(Stack[I++])) { 4134 case Desugar: 4135 // This is the point at which we potentially lose source 4136 // information. 4137 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 4138 4139 case Parens: { 4140 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 4141 return C.getParenType(New); 4142 } 4143 4144 case Pointer: { 4145 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 4146 return C.getPointerType(New); 4147 } 4148 4149 case BlockPointer: { 4150 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 4151 return C.getBlockPointerType(New); 4152 } 4153 4154 case MemberPointer: { 4155 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 4156 QualType New = wrap(C, OldMPT->getPointeeType(), I); 4157 return C.getMemberPointerType(New, OldMPT->getClass()); 4158 } 4159 4160 case Reference: { 4161 const ReferenceType *OldRef = cast<ReferenceType>(Old); 4162 QualType New = wrap(C, OldRef->getPointeeType(), I); 4163 if (isa<LValueReferenceType>(OldRef)) 4164 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 4165 else 4166 return C.getRValueReferenceType(New); 4167 } 4168 } 4169 4170 llvm_unreachable("unknown wrapping kind"); 4171 } 4172 }; 4173 } 4174 4175 /// Process an individual function attribute. Returns true to 4176 /// indicate that the attribute was handled, false if it wasn't. 4177 static bool handleFunctionTypeAttr(TypeProcessingState &state, 4178 AttributeList &attr, 4179 QualType &type) { 4180 Sema &S = state.getSema(); 4181 4182 FunctionTypeUnwrapper unwrapped(S, type); 4183 4184 if (attr.getKind() == AttributeList::AT_NoReturn) { 4185 if (S.CheckNoReturnAttr(attr)) 4186 return true; 4187 4188 // Delay if this is not a function type. 4189 if (!unwrapped.isFunctionType()) 4190 return false; 4191 4192 // Otherwise we can process right away. 4193 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 4194 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4195 return true; 4196 } 4197 4198 // ns_returns_retained is not always a type attribute, but if we got 4199 // here, we're treating it as one right now. 4200 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) { 4201 assert(S.getLangOpts().ObjCAutoRefCount && 4202 "ns_returns_retained treated as type attribute in non-ARC"); 4203 if (attr.getNumArgs()) return true; 4204 4205 // Delay if this is not a function type. 4206 if (!unwrapped.isFunctionType()) 4207 return false; 4208 4209 FunctionType::ExtInfo EI 4210 = unwrapped.get()->getExtInfo().withProducesResult(true); 4211 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4212 return true; 4213 } 4214 4215 if (attr.getKind() == AttributeList::AT_Regparm) { 4216 unsigned value; 4217 if (S.CheckRegparmAttr(attr, value)) 4218 return true; 4219 4220 // Delay if this is not a function type. 4221 if (!unwrapped.isFunctionType()) 4222 return false; 4223 4224 // Diagnose regparm with fastcall. 4225 const FunctionType *fn = unwrapped.get(); 4226 CallingConv CC = fn->getCallConv(); 4227 if (CC == CC_X86FastCall) { 4228 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 4229 << FunctionType::getNameForCallConv(CC) 4230 << "regparm"; 4231 attr.setInvalid(); 4232 return true; 4233 } 4234 4235 FunctionType::ExtInfo EI = 4236 unwrapped.get()->getExtInfo().withRegParm(value); 4237 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4238 return true; 4239 } 4240 4241 // Delay if the type didn't work out to a function. 4242 if (!unwrapped.isFunctionType()) return false; 4243 4244 // Otherwise, a calling convention. 4245 CallingConv CC; 4246 if (S.CheckCallingConvAttr(attr, CC)) 4247 return true; 4248 4249 const FunctionType *fn = unwrapped.get(); 4250 CallingConv CCOld = fn->getCallConv(); 4251 if (S.Context.getCanonicalCallConv(CC) == 4252 S.Context.getCanonicalCallConv(CCOld)) { 4253 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC); 4254 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4255 return true; 4256 } 4257 4258 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) { 4259 // Should we diagnose reapplications of the same convention? 4260 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 4261 << FunctionType::getNameForCallConv(CC) 4262 << FunctionType::getNameForCallConv(CCOld); 4263 attr.setInvalid(); 4264 return true; 4265 } 4266 4267 // Diagnose the use of X86 fastcall on varargs or unprototyped functions. 4268 if (CC == CC_X86FastCall) { 4269 if (isa<FunctionNoProtoType>(fn)) { 4270 S.Diag(attr.getLoc(), diag::err_cconv_knr) 4271 << FunctionType::getNameForCallConv(CC); 4272 attr.setInvalid(); 4273 return true; 4274 } 4275 4276 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn); 4277 if (FnP->isVariadic()) { 4278 S.Diag(attr.getLoc(), diag::err_cconv_varargs) 4279 << FunctionType::getNameForCallConv(CC); 4280 attr.setInvalid(); 4281 return true; 4282 } 4283 4284 // Also diagnose fastcall with regparm. 4285 if (fn->getHasRegParm()) { 4286 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 4287 << "regparm" 4288 << FunctionType::getNameForCallConv(CC); 4289 attr.setInvalid(); 4290 return true; 4291 } 4292 } 4293 4294 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 4295 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 4296 return true; 4297 } 4298 4299 /// Handle OpenCL image access qualifiers: read_only, write_only, read_write 4300 static void HandleOpenCLImageAccessAttribute(QualType& CurType, 4301 const AttributeList &Attr, 4302 Sema &S) { 4303 // Check the attribute arguments. 4304 if (Attr.getNumArgs() != 1) { 4305 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 4306 Attr.setInvalid(); 4307 return; 4308 } 4309 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 4310 llvm::APSInt arg(32); 4311 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 4312 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) { 4313 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 4314 << "opencl_image_access" << sizeExpr->getSourceRange(); 4315 Attr.setInvalid(); 4316 return; 4317 } 4318 unsigned iarg = static_cast<unsigned>(arg.getZExtValue()); 4319 switch (iarg) { 4320 case CLIA_read_only: 4321 case CLIA_write_only: 4322 case CLIA_read_write: 4323 // Implemented in a separate patch 4324 break; 4325 default: 4326 // Implemented in a separate patch 4327 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 4328 << sizeExpr->getSourceRange(); 4329 Attr.setInvalid(); 4330 break; 4331 } 4332 } 4333 4334 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 4335 /// and float scalars, although arrays, pointers, and function return values are 4336 /// allowed in conjunction with this construct. Aggregates with this attribute 4337 /// are invalid, even if they are of the same size as a corresponding scalar. 4338 /// The raw attribute should contain precisely 1 argument, the vector size for 4339 /// the variable, measured in bytes. If curType and rawAttr are well formed, 4340 /// this routine will return a new vector type. 4341 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 4342 Sema &S) { 4343 // Check the attribute arguments. 4344 if (Attr.getNumArgs() != 1) { 4345 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 4346 Attr.setInvalid(); 4347 return; 4348 } 4349 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 4350 llvm::APSInt vecSize(32); 4351 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 4352 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 4353 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 4354 << "vector_size" << sizeExpr->getSourceRange(); 4355 Attr.setInvalid(); 4356 return; 4357 } 4358 // the base type must be integer or float, and can't already be a vector. 4359 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) { 4360 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 4361 Attr.setInvalid(); 4362 return; 4363 } 4364 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 4365 // vecSize is specified in bytes - convert to bits. 4366 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 4367 4368 // the vector size needs to be an integral multiple of the type size. 4369 if (vectorSize % typeSize) { 4370 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 4371 << sizeExpr->getSourceRange(); 4372 Attr.setInvalid(); 4373 return; 4374 } 4375 if (vectorSize == 0) { 4376 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 4377 << sizeExpr->getSourceRange(); 4378 Attr.setInvalid(); 4379 return; 4380 } 4381 4382 // Success! Instantiate the vector type, the number of elements is > 0, and 4383 // not required to be a power of 2, unlike GCC. 4384 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 4385 VectorType::GenericVector); 4386 } 4387 4388 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on 4389 /// a type. 4390 static void HandleExtVectorTypeAttr(QualType &CurType, 4391 const AttributeList &Attr, 4392 Sema &S) { 4393 Expr *sizeExpr; 4394 4395 // Special case where the argument is a template id. 4396 if (Attr.getParameterName()) { 4397 CXXScopeSpec SS; 4398 SourceLocation TemplateKWLoc; 4399 UnqualifiedId id; 4400 id.setIdentifier(Attr.getParameterName(), Attr.getLoc()); 4401 4402 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 4403 id, false, false); 4404 if (Size.isInvalid()) 4405 return; 4406 4407 sizeExpr = Size.get(); 4408 } else { 4409 // check the attribute arguments. 4410 if (Attr.getNumArgs() != 1) { 4411 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 4412 return; 4413 } 4414 sizeExpr = Attr.getArg(0); 4415 } 4416 4417 // Create the vector type. 4418 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 4419 if (!T.isNull()) 4420 CurType = T; 4421 } 4422 4423 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 4424 /// "neon_polyvector_type" attributes are used to create vector types that 4425 /// are mangled according to ARM's ABI. Otherwise, these types are identical 4426 /// to those created with the "vector_size" attribute. Unlike "vector_size" 4427 /// the argument to these Neon attributes is the number of vector elements, 4428 /// not the vector size in bytes. The vector width and element type must 4429 /// match one of the standard Neon vector types. 4430 static void HandleNeonVectorTypeAttr(QualType& CurType, 4431 const AttributeList &Attr, Sema &S, 4432 VectorType::VectorKind VecKind, 4433 const char *AttrName) { 4434 // Check the attribute arguments. 4435 if (Attr.getNumArgs() != 1) { 4436 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 4437 Attr.setInvalid(); 4438 return; 4439 } 4440 // The number of elements must be an ICE. 4441 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0)); 4442 llvm::APSInt numEltsInt(32); 4443 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 4444 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 4445 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 4446 << AttrName << numEltsExpr->getSourceRange(); 4447 Attr.setInvalid(); 4448 return; 4449 } 4450 // Only certain element types are supported for Neon vectors. 4451 const BuiltinType* BTy = CurType->getAs<BuiltinType>(); 4452 if (!BTy || 4453 (VecKind == VectorType::NeonPolyVector && 4454 BTy->getKind() != BuiltinType::SChar && 4455 BTy->getKind() != BuiltinType::Short) || 4456 (BTy->getKind() != BuiltinType::SChar && 4457 BTy->getKind() != BuiltinType::UChar && 4458 BTy->getKind() != BuiltinType::Short && 4459 BTy->getKind() != BuiltinType::UShort && 4460 BTy->getKind() != BuiltinType::Int && 4461 BTy->getKind() != BuiltinType::UInt && 4462 BTy->getKind() != BuiltinType::LongLong && 4463 BTy->getKind() != BuiltinType::ULongLong && 4464 BTy->getKind() != BuiltinType::Float)) { 4465 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType; 4466 Attr.setInvalid(); 4467 return; 4468 } 4469 // The total size of the vector must be 64 or 128 bits. 4470 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 4471 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 4472 unsigned vecSize = typeSize * numElts; 4473 if (vecSize != 64 && vecSize != 128) { 4474 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 4475 Attr.setInvalid(); 4476 return; 4477 } 4478 4479 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 4480 } 4481 4482 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 4483 TypeAttrLocation TAL, AttributeList *attrs) { 4484 // Scan through and apply attributes to this type where it makes sense. Some 4485 // attributes (such as __address_space__, __vector_size__, etc) apply to the 4486 // type, but others can be present in the type specifiers even though they 4487 // apply to the decl. Here we apply type attributes and ignore the rest. 4488 4489 AttributeList *next; 4490 do { 4491 AttributeList &attr = *attrs; 4492 next = attr.getNext(); 4493 4494 // Skip attributes that were marked to be invalid. 4495 if (attr.isInvalid()) 4496 continue; 4497 4498 if (attr.isCXX11Attribute()) { 4499 // [[gnu::...]] attributes are treated as declaration attributes, so may 4500 // not appertain to a DeclaratorChunk, even if we handle them as type 4501 // attributes. 4502 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) { 4503 if (TAL == TAL_DeclChunk) { 4504 state.getSema().Diag(attr.getLoc(), 4505 diag::warn_cxx11_gnu_attribute_on_type) 4506 << attr.getName(); 4507 continue; 4508 } 4509 } else if (TAL != TAL_DeclChunk) { 4510 // Otherwise, only consider type processing for a C++11 attribute if 4511 // it's actually been applied to a type. 4512 continue; 4513 } 4514 } 4515 4516 // If this is an attribute we can handle, do so now, 4517 // otherwise, add it to the FnAttrs list for rechaining. 4518 switch (attr.getKind()) { 4519 default: 4520 // A C++11 attribute on a declarator chunk must appertain to a type. 4521 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) { 4522 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) 4523 << attr.getName(); 4524 attr.setUsedAsTypeAttr(); 4525 } 4526 break; 4527 4528 case AttributeList::UnknownAttribute: 4529 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) 4530 state.getSema().Diag(attr.getLoc(), 4531 diag::warn_unknown_attribute_ignored) 4532 << attr.getName(); 4533 break; 4534 4535 case AttributeList::IgnoredAttribute: 4536 break; 4537 4538 case AttributeList::AT_MayAlias: 4539 // FIXME: This attribute needs to actually be handled, but if we ignore 4540 // it it breaks large amounts of Linux software. 4541 attr.setUsedAsTypeAttr(); 4542 break; 4543 case AttributeList::AT_AddressSpace: 4544 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 4545 attr.setUsedAsTypeAttr(); 4546 break; 4547 OBJC_POINTER_TYPE_ATTRS_CASELIST: 4548 if (!handleObjCPointerTypeAttr(state, attr, type)) 4549 distributeObjCPointerTypeAttr(state, attr, type); 4550 attr.setUsedAsTypeAttr(); 4551 break; 4552 case AttributeList::AT_VectorSize: 4553 HandleVectorSizeAttr(type, attr, state.getSema()); 4554 attr.setUsedAsTypeAttr(); 4555 break; 4556 case AttributeList::AT_ExtVectorType: 4557 HandleExtVectorTypeAttr(type, attr, state.getSema()); 4558 attr.setUsedAsTypeAttr(); 4559 break; 4560 case AttributeList::AT_NeonVectorType: 4561 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 4562 VectorType::NeonVector, "neon_vector_type"); 4563 attr.setUsedAsTypeAttr(); 4564 break; 4565 case AttributeList::AT_NeonPolyVectorType: 4566 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 4567 VectorType::NeonPolyVector, 4568 "neon_polyvector_type"); 4569 attr.setUsedAsTypeAttr(); 4570 break; 4571 case AttributeList::AT_OpenCLImageAccess: 4572 HandleOpenCLImageAccessAttribute(type, attr, state.getSema()); 4573 attr.setUsedAsTypeAttr(); 4574 break; 4575 4576 case AttributeList::AT_Win64: 4577 case AttributeList::AT_Ptr32: 4578 case AttributeList::AT_Ptr64: 4579 // FIXME: Don't ignore these. We have partial handling for them as 4580 // declaration attributes in SemaDeclAttr.cpp; that should be moved here. 4581 attr.setUsedAsTypeAttr(); 4582 break; 4583 4584 case AttributeList::AT_NSReturnsRetained: 4585 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 4586 break; 4587 // fallthrough into the function attrs 4588 4589 FUNCTION_TYPE_ATTRS_CASELIST: 4590 attr.setUsedAsTypeAttr(); 4591 4592 // Never process function type attributes as part of the 4593 // declaration-specifiers. 4594 if (TAL == TAL_DeclSpec) 4595 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 4596 4597 // Otherwise, handle the possible delays. 4598 else if (!handleFunctionTypeAttr(state, attr, type)) 4599 distributeFunctionTypeAttr(state, attr, type); 4600 break; 4601 } 4602 } while ((attrs = next)); 4603 } 4604 4605 /// \brief Ensure that the type of the given expression is complete. 4606 /// 4607 /// This routine checks whether the expression \p E has a complete type. If the 4608 /// expression refers to an instantiable construct, that instantiation is 4609 /// performed as needed to complete its type. Furthermore 4610 /// Sema::RequireCompleteType is called for the expression's type (or in the 4611 /// case of a reference type, the referred-to type). 4612 /// 4613 /// \param E The expression whose type is required to be complete. 4614 /// \param Diagnoser The object that will emit a diagnostic if the type is 4615 /// incomplete. 4616 /// 4617 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 4618 /// otherwise. 4619 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){ 4620 QualType T = E->getType(); 4621 4622 // Fast path the case where the type is already complete. 4623 if (!T->isIncompleteType()) 4624 return false; 4625 4626 // Incomplete array types may be completed by the initializer attached to 4627 // their definitions. For static data members of class templates we need to 4628 // instantiate the definition to get this initializer and complete the type. 4629 if (T->isIncompleteArrayType()) { 4630 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4631 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 4632 if (Var->isStaticDataMember() && 4633 Var->getInstantiatedFromStaticDataMember()) { 4634 4635 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 4636 assert(MSInfo && "Missing member specialization information?"); 4637 if (MSInfo->getTemplateSpecializationKind() 4638 != TSK_ExplicitSpecialization) { 4639 // If we don't already have a point of instantiation, this is it. 4640 if (MSInfo->getPointOfInstantiation().isInvalid()) { 4641 MSInfo->setPointOfInstantiation(E->getLocStart()); 4642 4643 // This is a modification of an existing AST node. Notify 4644 // listeners. 4645 if (ASTMutationListener *L = getASTMutationListener()) 4646 L->StaticDataMemberInstantiated(Var); 4647 } 4648 4649 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var); 4650 4651 // Update the type to the newly instantiated definition's type both 4652 // here and within the expression. 4653 if (VarDecl *Def = Var->getDefinition()) { 4654 DRE->setDecl(Def); 4655 T = Def->getType(); 4656 DRE->setType(T); 4657 E->setType(T); 4658 } 4659 } 4660 4661 // We still go on to try to complete the type independently, as it 4662 // may also require instantiations or diagnostics if it remains 4663 // incomplete. 4664 } 4665 } 4666 } 4667 } 4668 4669 // FIXME: Are there other cases which require instantiating something other 4670 // than the type to complete the type of an expression? 4671 4672 // Look through reference types and complete the referred type. 4673 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 4674 T = Ref->getPointeeType(); 4675 4676 return RequireCompleteType(E->getExprLoc(), T, Diagnoser); 4677 } 4678 4679 namespace { 4680 struct TypeDiagnoserDiag : Sema::TypeDiagnoser { 4681 unsigned DiagID; 4682 4683 TypeDiagnoserDiag(unsigned DiagID) 4684 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {} 4685 4686 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 4687 if (Suppressed) return; 4688 S.Diag(Loc, DiagID) << T; 4689 } 4690 }; 4691 } 4692 4693 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 4694 TypeDiagnoserDiag Diagnoser(DiagID); 4695 return RequireCompleteExprType(E, Diagnoser); 4696 } 4697 4698 /// @brief Ensure that the type T is a complete type. 4699 /// 4700 /// This routine checks whether the type @p T is complete in any 4701 /// context where a complete type is required. If @p T is a complete 4702 /// type, returns false. If @p T is a class template specialization, 4703 /// this routine then attempts to perform class template 4704 /// instantiation. If instantiation fails, or if @p T is incomplete 4705 /// and cannot be completed, issues the diagnostic @p diag (giving it 4706 /// the type @p T) and returns true. 4707 /// 4708 /// @param Loc The location in the source that the incomplete type 4709 /// diagnostic should refer to. 4710 /// 4711 /// @param T The type that this routine is examining for completeness. 4712 /// 4713 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 4714 /// @c false otherwise. 4715 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 4716 TypeDiagnoser &Diagnoser) { 4717 // FIXME: Add this assertion to make sure we always get instantiation points. 4718 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 4719 // FIXME: Add this assertion to help us flush out problems with 4720 // checking for dependent types and type-dependent expressions. 4721 // 4722 // assert(!T->isDependentType() && 4723 // "Can't ask whether a dependent type is complete"); 4724 4725 // If we have a complete type, we're done. 4726 NamedDecl *Def = 0; 4727 if (!T->isIncompleteType(&Def)) { 4728 // If we know about the definition but it is not visible, complain. 4729 if (!Diagnoser.Suppressed && Def && !LookupResult::isVisible(Def)) { 4730 // Suppress this error outside of a SFINAE context if we've already 4731 // emitted the error once for this type. There's no usefulness in 4732 // repeating the diagnostic. 4733 // FIXME: Add a Fix-It that imports the corresponding module or includes 4734 // the header. 4735 Module *Owner = Def->getOwningModule(); 4736 Diag(Loc, diag::err_module_private_definition) 4737 << T << Owner->getFullModuleName(); 4738 Diag(Def->getLocation(), diag::note_previous_definition); 4739 4740 if (!isSFINAEContext()) { 4741 // Recover by implicitly importing this module. 4742 createImplicitModuleImport(Loc, Owner); 4743 } 4744 } 4745 4746 return false; 4747 } 4748 4749 const TagType *Tag = T->getAs<TagType>(); 4750 const ObjCInterfaceType *IFace = 0; 4751 4752 if (Tag) { 4753 // Avoid diagnosing invalid decls as incomplete. 4754 if (Tag->getDecl()->isInvalidDecl()) 4755 return true; 4756 4757 // Give the external AST source a chance to complete the type. 4758 if (Tag->getDecl()->hasExternalLexicalStorage()) { 4759 Context.getExternalSource()->CompleteType(Tag->getDecl()); 4760 if (!Tag->isIncompleteType()) 4761 return false; 4762 } 4763 } 4764 else if ((IFace = T->getAs<ObjCInterfaceType>())) { 4765 // Avoid diagnosing invalid decls as incomplete. 4766 if (IFace->getDecl()->isInvalidDecl()) 4767 return true; 4768 4769 // Give the external AST source a chance to complete the type. 4770 if (IFace->getDecl()->hasExternalLexicalStorage()) { 4771 Context.getExternalSource()->CompleteType(IFace->getDecl()); 4772 if (!IFace->isIncompleteType()) 4773 return false; 4774 } 4775 } 4776 4777 // If we have a class template specialization or a class member of a 4778 // class template specialization, or an array with known size of such, 4779 // try to instantiate it. 4780 QualType MaybeTemplate = T; 4781 while (const ConstantArrayType *Array 4782 = Context.getAsConstantArrayType(MaybeTemplate)) 4783 MaybeTemplate = Array->getElementType(); 4784 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 4785 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 4786 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 4787 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) 4788 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec, 4789 TSK_ImplicitInstantiation, 4790 /*Complain=*/!Diagnoser.Suppressed); 4791 } else if (CXXRecordDecl *Rec 4792 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 4793 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass(); 4794 if (!Rec->isBeingDefined() && Pattern) { 4795 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo(); 4796 assert(MSI && "Missing member specialization information?"); 4797 // This record was instantiated from a class within a template. 4798 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 4799 return InstantiateClass(Loc, Rec, Pattern, 4800 getTemplateInstantiationArgs(Rec), 4801 TSK_ImplicitInstantiation, 4802 /*Complain=*/!Diagnoser.Suppressed); 4803 } 4804 } 4805 } 4806 4807 if (Diagnoser.Suppressed) 4808 return true; 4809 4810 // We have an incomplete type. Produce a diagnostic. 4811 Diagnoser.diagnose(*this, Loc, T); 4812 4813 // If the type was a forward declaration of a class/struct/union 4814 // type, produce a note. 4815 if (Tag && !Tag->getDecl()->isInvalidDecl()) 4816 Diag(Tag->getDecl()->getLocation(), 4817 Tag->isBeingDefined() ? diag::note_type_being_defined 4818 : diag::note_forward_declaration) 4819 << QualType(Tag, 0); 4820 4821 // If the Objective-C class was a forward declaration, produce a note. 4822 if (IFace && !IFace->getDecl()->isInvalidDecl()) 4823 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class); 4824 4825 return true; 4826 } 4827 4828 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 4829 unsigned DiagID) { 4830 TypeDiagnoserDiag Diagnoser(DiagID); 4831 return RequireCompleteType(Loc, T, Diagnoser); 4832 } 4833 4834 /// \brief Get diagnostic %select index for tag kind for 4835 /// literal type diagnostic message. 4836 /// WARNING: Indexes apply to particular diagnostics only! 4837 /// 4838 /// \returns diagnostic %select index. 4839 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { 4840 switch (Tag) { 4841 case TTK_Struct: return 0; 4842 case TTK_Interface: return 1; 4843 case TTK_Class: return 2; 4844 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!"); 4845 } 4846 } 4847 4848 /// @brief Ensure that the type T is a literal type. 4849 /// 4850 /// This routine checks whether the type @p T is a literal type. If @p T is an 4851 /// incomplete type, an attempt is made to complete it. If @p T is a literal 4852 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 4853 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 4854 /// it the type @p T), along with notes explaining why the type is not a 4855 /// literal type, and returns true. 4856 /// 4857 /// @param Loc The location in the source that the non-literal type 4858 /// diagnostic should refer to. 4859 /// 4860 /// @param T The type that this routine is examining for literalness. 4861 /// 4862 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 4863 /// 4864 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 4865 /// @c false otherwise. 4866 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 4867 TypeDiagnoser &Diagnoser) { 4868 assert(!T->isDependentType() && "type should not be dependent"); 4869 4870 QualType ElemType = Context.getBaseElementType(T); 4871 RequireCompleteType(Loc, ElemType, 0); 4872 4873 if (T->isLiteralType(Context)) 4874 return false; 4875 4876 if (Diagnoser.Suppressed) 4877 return true; 4878 4879 Diagnoser.diagnose(*this, Loc, T); 4880 4881 if (T->isVariableArrayType()) 4882 return true; 4883 4884 const RecordType *RT = ElemType->getAs<RecordType>(); 4885 if (!RT) 4886 return true; 4887 4888 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4889 4890 // A partially-defined class type can't be a literal type, because a literal 4891 // class type must have a trivial destructor (which can't be checked until 4892 // the class definition is complete). 4893 if (!RD->isCompleteDefinition()) { 4894 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T); 4895 return true; 4896 } 4897 4898 // If the class has virtual base classes, then it's not an aggregate, and 4899 // cannot have any constexpr constructors or a trivial default constructor, 4900 // so is non-literal. This is better to diagnose than the resulting absence 4901 // of constexpr constructors. 4902 if (RD->getNumVBases()) { 4903 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 4904 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 4905 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 4906 E = RD->vbases_end(); I != E; ++I) 4907 Diag(I->getLocStart(), 4908 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 4909 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 4910 !RD->hasTrivialDefaultConstructor()) { 4911 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 4912 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 4913 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4914 E = RD->bases_end(); I != E; ++I) { 4915 if (!I->getType()->isLiteralType(Context)) { 4916 Diag(I->getLocStart(), 4917 diag::note_non_literal_base_class) 4918 << RD << I->getType() << I->getSourceRange(); 4919 return true; 4920 } 4921 } 4922 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 4923 E = RD->field_end(); I != E; ++I) { 4924 if (!I->getType()->isLiteralType(Context) || 4925 I->getType().isVolatileQualified()) { 4926 Diag(I->getLocation(), diag::note_non_literal_field) 4927 << RD << *I << I->getType() 4928 << I->getType().isVolatileQualified(); 4929 return true; 4930 } 4931 } 4932 } else if (!RD->hasTrivialDestructor()) { 4933 // All fields and bases are of literal types, so have trivial destructors. 4934 // If this class's destructor is non-trivial it must be user-declared. 4935 CXXDestructorDecl *Dtor = RD->getDestructor(); 4936 assert(Dtor && "class has literal fields and bases but no dtor?"); 4937 if (!Dtor) 4938 return true; 4939 4940 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 4941 diag::note_non_literal_user_provided_dtor : 4942 diag::note_non_literal_nontrivial_dtor) << RD; 4943 if (!Dtor->isUserProvided()) 4944 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true); 4945 } 4946 4947 return true; 4948 } 4949 4950 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 4951 TypeDiagnoserDiag Diagnoser(DiagID); 4952 return RequireLiteralType(Loc, T, Diagnoser); 4953 } 4954 4955 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 4956 /// and qualified by the nested-name-specifier contained in SS. 4957 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 4958 const CXXScopeSpec &SS, QualType T) { 4959 if (T.isNull()) 4960 return T; 4961 NestedNameSpecifier *NNS; 4962 if (SS.isValid()) 4963 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 4964 else { 4965 if (Keyword == ETK_None) 4966 return T; 4967 NNS = 0; 4968 } 4969 return Context.getElaboratedType(Keyword, NNS, T); 4970 } 4971 4972 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 4973 ExprResult ER = CheckPlaceholderExpr(E); 4974 if (ER.isInvalid()) return QualType(); 4975 E = ER.take(); 4976 4977 if (!E->isTypeDependent()) { 4978 QualType T = E->getType(); 4979 if (const TagType *TT = T->getAs<TagType>()) 4980 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 4981 } 4982 return Context.getTypeOfExprType(E); 4983 } 4984 4985 /// getDecltypeForExpr - Given an expr, will return the decltype for 4986 /// that expression, according to the rules in C++11 4987 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 4988 static QualType getDecltypeForExpr(Sema &S, Expr *E) { 4989 if (E->isTypeDependent()) 4990 return S.Context.DependentTy; 4991 4992 // C++11 [dcl.type.simple]p4: 4993 // The type denoted by decltype(e) is defined as follows: 4994 // 4995 // - if e is an unparenthesized id-expression or an unparenthesized class 4996 // member access (5.2.5), decltype(e) is the type of the entity named 4997 // by e. If there is no such entity, or if e names a set of overloaded 4998 // functions, the program is ill-formed; 4999 // 5000 // We apply the same rules for Objective-C ivar and property references. 5001 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 5002 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 5003 return VD->getType(); 5004 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 5005 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 5006 return FD->getType(); 5007 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) { 5008 return IR->getDecl()->getType(); 5009 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) { 5010 if (PR->isExplicitProperty()) 5011 return PR->getExplicitProperty()->getType(); 5012 } 5013 5014 // C++11 [expr.lambda.prim]p18: 5015 // Every occurrence of decltype((x)) where x is a possibly 5016 // parenthesized id-expression that names an entity of automatic 5017 // storage duration is treated as if x were transformed into an 5018 // access to a corresponding data member of the closure type that 5019 // would have been declared if x were an odr-use of the denoted 5020 // entity. 5021 using namespace sema; 5022 if (S.getCurLambda()) { 5023 if (isa<ParenExpr>(E)) { 5024 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 5025 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 5026 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); 5027 if (!T.isNull()) 5028 return S.Context.getLValueReferenceType(T); 5029 } 5030 } 5031 } 5032 } 5033 5034 5035 // C++11 [dcl.type.simple]p4: 5036 // [...] 5037 QualType T = E->getType(); 5038 switch (E->getValueKind()) { 5039 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 5040 // type of e; 5041 case VK_XValue: T = S.Context.getRValueReferenceType(T); break; 5042 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 5043 // type of e; 5044 case VK_LValue: T = S.Context.getLValueReferenceType(T); break; 5045 // - otherwise, decltype(e) is the type of e. 5046 case VK_RValue: break; 5047 } 5048 5049 return T; 5050 } 5051 5052 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) { 5053 ExprResult ER = CheckPlaceholderExpr(E); 5054 if (ER.isInvalid()) return QualType(); 5055 E = ER.take(); 5056 5057 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); 5058 } 5059 5060 QualType Sema::BuildUnaryTransformType(QualType BaseType, 5061 UnaryTransformType::UTTKind UKind, 5062 SourceLocation Loc) { 5063 switch (UKind) { 5064 case UnaryTransformType::EnumUnderlyingType: 5065 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 5066 Diag(Loc, diag::err_only_enums_have_underlying_types); 5067 return QualType(); 5068 } else { 5069 QualType Underlying = BaseType; 5070 if (!BaseType->isDependentType()) { 5071 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 5072 assert(ED && "EnumType has no EnumDecl"); 5073 DiagnoseUseOfDecl(ED, Loc); 5074 Underlying = ED->getIntegerType(); 5075 } 5076 assert(!Underlying.isNull()); 5077 return Context.getUnaryTransformType(BaseType, Underlying, 5078 UnaryTransformType::EnumUnderlyingType); 5079 } 5080 } 5081 llvm_unreachable("unknown unary transform type"); 5082 } 5083 5084 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 5085 if (!T->isDependentType()) { 5086 // FIXME: It isn't entirely clear whether incomplete atomic types 5087 // are allowed or not; for simplicity, ban them for the moment. 5088 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 5089 return QualType(); 5090 5091 int DisallowedKind = -1; 5092 if (T->isArrayType()) 5093 DisallowedKind = 1; 5094 else if (T->isFunctionType()) 5095 DisallowedKind = 2; 5096 else if (T->isReferenceType()) 5097 DisallowedKind = 3; 5098 else if (T->isAtomicType()) 5099 DisallowedKind = 4; 5100 else if (T.hasQualifiers()) 5101 DisallowedKind = 5; 5102 else if (!T.isTriviallyCopyableType(Context)) 5103 // Some other non-trivially-copyable type (probably a C++ class) 5104 DisallowedKind = 6; 5105 5106 if (DisallowedKind != -1) { 5107 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 5108 return QualType(); 5109 } 5110 5111 // FIXME: Do we need any handling for ARC here? 5112 } 5113 5114 // Build the pointer type. 5115 return Context.getAtomicType(T); 5116 } 5117