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