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