clang API Documentation
00001 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements type-related semantic analysis. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Sema/ScopeInfo.h" 00015 #include "clang/Sema/SemaInternal.h" 00016 #include "clang/Sema/Template.h" 00017 #include "clang/Basic/OpenCL.h" 00018 #include "clang/AST/ASTContext.h" 00019 #include "clang/AST/ASTMutationListener.h" 00020 #include "clang/AST/CXXInheritance.h" 00021 #include "clang/AST/DeclObjC.h" 00022 #include "clang/AST/DeclTemplate.h" 00023 #include "clang/AST/TypeLoc.h" 00024 #include "clang/AST/TypeLocVisitor.h" 00025 #include "clang/AST/Expr.h" 00026 #include "clang/Basic/PartialDiagnostic.h" 00027 #include "clang/Basic/TargetInfo.h" 00028 #include "clang/Lex/Preprocessor.h" 00029 #include "clang/Parse/ParseDiagnostic.h" 00030 #include "clang/Sema/DeclSpec.h" 00031 #include "clang/Sema/DelayedDiagnostic.h" 00032 #include "clang/Sema/Lookup.h" 00033 #include "llvm/ADT/SmallPtrSet.h" 00034 #include "llvm/Support/ErrorHandling.h" 00035 using namespace clang; 00036 00037 /// isOmittedBlockReturnType - Return true if this declarator is missing a 00038 /// return type because this is a omitted return type on a block literal. 00039 static bool isOmittedBlockReturnType(const Declarator &D) { 00040 if (D.getContext() != Declarator::BlockLiteralContext || 00041 D.getDeclSpec().hasTypeSpecifier()) 00042 return false; 00043 00044 if (D.getNumTypeObjects() == 0) 00045 return true; // ^{ ... } 00046 00047 if (D.getNumTypeObjects() == 1 && 00048 D.getTypeObject(0).Kind == DeclaratorChunk::Function) 00049 return true; // ^(int X, float Y) { ... } 00050 00051 return false; 00052 } 00053 00054 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which 00055 /// doesn't apply to the given type. 00056 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr, 00057 QualType type) { 00058 bool useExpansionLoc = false; 00059 00060 unsigned diagID = 0; 00061 switch (attr.getKind()) { 00062 case AttributeList::AT_objc_gc: 00063 diagID = diag::warn_pointer_attribute_wrong_type; 00064 useExpansionLoc = true; 00065 break; 00066 00067 case AttributeList::AT_objc_ownership: 00068 diagID = diag::warn_objc_object_attribute_wrong_type; 00069 useExpansionLoc = true; 00070 break; 00071 00072 default: 00073 // Assume everything else was a function attribute. 00074 diagID = diag::warn_function_attribute_wrong_type; 00075 break; 00076 } 00077 00078 SourceLocation loc = attr.getLoc(); 00079 StringRef name = attr.getName()->getName(); 00080 00081 // The GC attributes are usually written with macros; special-case them. 00082 if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) { 00083 if (attr.getParameterName()->isStr("strong")) { 00084 if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; 00085 } else if (attr.getParameterName()->isStr("weak")) { 00086 if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; 00087 } 00088 } 00089 00090 S.Diag(loc, diagID) << name << type; 00091 } 00092 00093 // objc_gc applies to Objective-C pointers or, otherwise, to the 00094 // smallest available pointer type (i.e. 'void*' in 'void**'). 00095 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \ 00096 case AttributeList::AT_objc_gc: \ 00097 case AttributeList::AT_objc_ownership 00098 00099 // Function type attributes. 00100 #define FUNCTION_TYPE_ATTRS_CASELIST \ 00101 case AttributeList::AT_noreturn: \ 00102 case AttributeList::AT_cdecl: \ 00103 case AttributeList::AT_fastcall: \ 00104 case AttributeList::AT_stdcall: \ 00105 case AttributeList::AT_thiscall: \ 00106 case AttributeList::AT_pascal: \ 00107 case AttributeList::AT_regparm: \ 00108 case AttributeList::AT_pcs \ 00109 00110 namespace { 00111 /// An object which stores processing state for the entire 00112 /// GetTypeForDeclarator process. 00113 class TypeProcessingState { 00114 Sema &sema; 00115 00116 /// The declarator being processed. 00117 Declarator &declarator; 00118 00119 /// The index of the declarator chunk we're currently processing. 00120 /// May be the total number of valid chunks, indicating the 00121 /// DeclSpec. 00122 unsigned chunkIndex; 00123 00124 /// Whether there are non-trivial modifications to the decl spec. 00125 bool trivial; 00126 00127 /// Whether we saved the attributes in the decl spec. 00128 bool hasSavedAttrs; 00129 00130 /// The original set of attributes on the DeclSpec. 00131 SmallVector<AttributeList*, 2> savedAttrs; 00132 00133 /// A list of attributes to diagnose the uselessness of when the 00134 /// processing is complete. 00135 SmallVector<AttributeList*, 2> ignoredTypeAttrs; 00136 00137 public: 00138 TypeProcessingState(Sema &sema, Declarator &declarator) 00139 : sema(sema), declarator(declarator), 00140 chunkIndex(declarator.getNumTypeObjects()), 00141 trivial(true), hasSavedAttrs(false) {} 00142 00143 Sema &getSema() const { 00144 return sema; 00145 } 00146 00147 Declarator &getDeclarator() const { 00148 return declarator; 00149 } 00150 00151 unsigned getCurrentChunkIndex() const { 00152 return chunkIndex; 00153 } 00154 00155 void setCurrentChunkIndex(unsigned idx) { 00156 assert(idx <= declarator.getNumTypeObjects()); 00157 chunkIndex = idx; 00158 } 00159 00160 AttributeList *&getCurrentAttrListRef() const { 00161 assert(chunkIndex <= declarator.getNumTypeObjects()); 00162 if (chunkIndex == declarator.getNumTypeObjects()) 00163 return getMutableDeclSpec().getAttributes().getListRef(); 00164 return declarator.getTypeObject(chunkIndex).getAttrListRef(); 00165 } 00166 00167 /// Save the current set of attributes on the DeclSpec. 00168 void saveDeclSpecAttrs() { 00169 // Don't try to save them multiple times. 00170 if (hasSavedAttrs) return; 00171 00172 DeclSpec &spec = getMutableDeclSpec(); 00173 for (AttributeList *attr = spec.getAttributes().getList(); attr; 00174 attr = attr->getNext()) 00175 savedAttrs.push_back(attr); 00176 trivial &= savedAttrs.empty(); 00177 hasSavedAttrs = true; 00178 } 00179 00180 /// Record that we had nowhere to put the given type attribute. 00181 /// We will diagnose such attributes later. 00182 void addIgnoredTypeAttr(AttributeList &attr) { 00183 ignoredTypeAttrs.push_back(&attr); 00184 } 00185 00186 /// Diagnose all the ignored type attributes, given that the 00187 /// declarator worked out to the given type. 00188 void diagnoseIgnoredTypeAttrs(QualType type) const { 00189 for (SmallVectorImpl<AttributeList*>::const_iterator 00190 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end(); 00191 i != e; ++i) 00192 diagnoseBadTypeAttribute(getSema(), **i, type); 00193 } 00194 00195 ~TypeProcessingState() { 00196 if (trivial) return; 00197 00198 restoreDeclSpecAttrs(); 00199 } 00200 00201 private: 00202 DeclSpec &getMutableDeclSpec() const { 00203 return const_cast<DeclSpec&>(declarator.getDeclSpec()); 00204 } 00205 00206 void restoreDeclSpecAttrs() { 00207 assert(hasSavedAttrs); 00208 00209 if (savedAttrs.empty()) { 00210 getMutableDeclSpec().getAttributes().set(0); 00211 return; 00212 } 00213 00214 getMutableDeclSpec().getAttributes().set(savedAttrs[0]); 00215 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i) 00216 savedAttrs[i]->setNext(savedAttrs[i+1]); 00217 savedAttrs.back()->setNext(0); 00218 } 00219 }; 00220 00221 /// Basically std::pair except that we really want to avoid an 00222 /// implicit operator= for safety concerns. It's also a minor 00223 /// link-time optimization for this to be a private type. 00224 struct AttrAndList { 00225 /// The attribute. 00226 AttributeList &first; 00227 00228 /// The head of the list the attribute is currently in. 00229 AttributeList *&second; 00230 00231 AttrAndList(AttributeList &attr, AttributeList *&head) 00232 : first(attr), second(head) {} 00233 }; 00234 } 00235 00236 namespace llvm { 00237 template <> struct isPodLike<AttrAndList> { 00238 static const bool value = true; 00239 }; 00240 } 00241 00242 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) { 00243 attr.setNext(head); 00244 head = &attr; 00245 } 00246 00247 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) { 00248 if (head == &attr) { 00249 head = attr.getNext(); 00250 return; 00251 } 00252 00253 AttributeList *cur = head; 00254 while (true) { 00255 assert(cur && cur->getNext() && "ran out of attrs?"); 00256 if (cur->getNext() == &attr) { 00257 cur->setNext(attr.getNext()); 00258 return; 00259 } 00260 cur = cur->getNext(); 00261 } 00262 } 00263 00264 static void moveAttrFromListToList(AttributeList &attr, 00265 AttributeList *&fromList, 00266 AttributeList *&toList) { 00267 spliceAttrOutOfList(attr, fromList); 00268 spliceAttrIntoList(attr, toList); 00269 } 00270 00271 static void processTypeAttrs(TypeProcessingState &state, 00272 QualType &type, bool isDeclSpec, 00273 AttributeList *attrs); 00274 00275 static bool handleFunctionTypeAttr(TypeProcessingState &state, 00276 AttributeList &attr, 00277 QualType &type); 00278 00279 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 00280 AttributeList &attr, QualType &type); 00281 00282 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 00283 AttributeList &attr, QualType &type); 00284 00285 static bool handleObjCPointerTypeAttr(TypeProcessingState &state, 00286 AttributeList &attr, QualType &type) { 00287 if (attr.getKind() == AttributeList::AT_objc_gc) 00288 return handleObjCGCTypeAttr(state, attr, type); 00289 assert(attr.getKind() == AttributeList::AT_objc_ownership); 00290 return handleObjCOwnershipTypeAttr(state, attr, type); 00291 } 00292 00293 /// Given that an objc_gc attribute was written somewhere on a 00294 /// declaration *other* than on the declarator itself (for which, use 00295 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it 00296 /// didn't apply in whatever position it was written in, try to move 00297 /// it to a more appropriate position. 00298 static void distributeObjCPointerTypeAttr(TypeProcessingState &state, 00299 AttributeList &attr, 00300 QualType type) { 00301 Declarator &declarator = state.getDeclarator(); 00302 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 00303 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 00304 switch (chunk.Kind) { 00305 case DeclaratorChunk::Pointer: 00306 case DeclaratorChunk::BlockPointer: 00307 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 00308 chunk.getAttrListRef()); 00309 return; 00310 00311 case DeclaratorChunk::Paren: 00312 case DeclaratorChunk::Array: 00313 continue; 00314 00315 // Don't walk through these. 00316 case DeclaratorChunk::Reference: 00317 case DeclaratorChunk::Function: 00318 case DeclaratorChunk::MemberPointer: 00319 goto error; 00320 } 00321 } 00322 error: 00323 00324 diagnoseBadTypeAttribute(state.getSema(), attr, type); 00325 } 00326 00327 /// Distribute an objc_gc type attribute that was written on the 00328 /// declarator. 00329 static void 00330 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, 00331 AttributeList &attr, 00332 QualType &declSpecType) { 00333 Declarator &declarator = state.getDeclarator(); 00334 00335 // objc_gc goes on the innermost pointer to something that's not a 00336 // pointer. 00337 unsigned innermost = -1U; 00338 bool considerDeclSpec = true; 00339 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 00340 DeclaratorChunk &chunk = declarator.getTypeObject(i); 00341 switch (chunk.Kind) { 00342 case DeclaratorChunk::Pointer: 00343 case DeclaratorChunk::BlockPointer: 00344 innermost = i; 00345 continue; 00346 00347 case DeclaratorChunk::Reference: 00348 case DeclaratorChunk::MemberPointer: 00349 case DeclaratorChunk::Paren: 00350 case DeclaratorChunk::Array: 00351 continue; 00352 00353 case DeclaratorChunk::Function: 00354 considerDeclSpec = false; 00355 goto done; 00356 } 00357 } 00358 done: 00359 00360 // That might actually be the decl spec if we weren't blocked by 00361 // anything in the declarator. 00362 if (considerDeclSpec) { 00363 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { 00364 // Splice the attribute into the decl spec. Prevents the 00365 // attribute from being applied multiple times and gives 00366 // the source-location-filler something to work with. 00367 state.saveDeclSpecAttrs(); 00368 moveAttrFromListToList(attr, declarator.getAttrListRef(), 00369 declarator.getMutableDeclSpec().getAttributes().getListRef()); 00370 return; 00371 } 00372 } 00373 00374 // Otherwise, if we found an appropriate chunk, splice the attribute 00375 // into it. 00376 if (innermost != -1U) { 00377 moveAttrFromListToList(attr, declarator.getAttrListRef(), 00378 declarator.getTypeObject(innermost).getAttrListRef()); 00379 return; 00380 } 00381 00382 // Otherwise, diagnose when we're done building the type. 00383 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 00384 state.addIgnoredTypeAttr(attr); 00385 } 00386 00387 /// A function type attribute was written somewhere in a declaration 00388 /// *other* than on the declarator itself or in the decl spec. Given 00389 /// that it didn't apply in whatever position it was written in, try 00390 /// to move it to a more appropriate position. 00391 static void distributeFunctionTypeAttr(TypeProcessingState &state, 00392 AttributeList &attr, 00393 QualType type) { 00394 Declarator &declarator = state.getDeclarator(); 00395 00396 // Try to push the attribute from the return type of a function to 00397 // the function itself. 00398 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { 00399 DeclaratorChunk &chunk = declarator.getTypeObject(i-1); 00400 switch (chunk.Kind) { 00401 case DeclaratorChunk::Function: 00402 moveAttrFromListToList(attr, state.getCurrentAttrListRef(), 00403 chunk.getAttrListRef()); 00404 return; 00405 00406 case DeclaratorChunk::Paren: 00407 case DeclaratorChunk::Pointer: 00408 case DeclaratorChunk::BlockPointer: 00409 case DeclaratorChunk::Array: 00410 case DeclaratorChunk::Reference: 00411 case DeclaratorChunk::MemberPointer: 00412 continue; 00413 } 00414 } 00415 00416 diagnoseBadTypeAttribute(state.getSema(), attr, type); 00417 } 00418 00419 /// Try to distribute a function type attribute to the innermost 00420 /// function chunk or type. Returns true if the attribute was 00421 /// distributed, false if no location was found. 00422 static bool 00423 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, 00424 AttributeList &attr, 00425 AttributeList *&attrList, 00426 QualType &declSpecType) { 00427 Declarator &declarator = state.getDeclarator(); 00428 00429 // Put it on the innermost function chunk, if there is one. 00430 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 00431 DeclaratorChunk &chunk = declarator.getTypeObject(i); 00432 if (chunk.Kind != DeclaratorChunk::Function) continue; 00433 00434 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef()); 00435 return true; 00436 } 00437 00438 if (handleFunctionTypeAttr(state, attr, declSpecType)) { 00439 spliceAttrOutOfList(attr, attrList); 00440 return true; 00441 } 00442 00443 return false; 00444 } 00445 00446 /// A function type attribute was written in the decl spec. Try to 00447 /// apply it somewhere. 00448 static void 00449 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, 00450 AttributeList &attr, 00451 QualType &declSpecType) { 00452 state.saveDeclSpecAttrs(); 00453 00454 // Try to distribute to the innermost. 00455 if (distributeFunctionTypeAttrToInnermost(state, attr, 00456 state.getCurrentAttrListRef(), 00457 declSpecType)) 00458 return; 00459 00460 // If that failed, diagnose the bad attribute when the declarator is 00461 // fully built. 00462 state.addIgnoredTypeAttr(attr); 00463 } 00464 00465 /// A function type attribute was written on the declarator. Try to 00466 /// apply it somewhere. 00467 static void 00468 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, 00469 AttributeList &attr, 00470 QualType &declSpecType) { 00471 Declarator &declarator = state.getDeclarator(); 00472 00473 // Try to distribute to the innermost. 00474 if (distributeFunctionTypeAttrToInnermost(state, attr, 00475 declarator.getAttrListRef(), 00476 declSpecType)) 00477 return; 00478 00479 // If that failed, diagnose the bad attribute when the declarator is 00480 // fully built. 00481 spliceAttrOutOfList(attr, declarator.getAttrListRef()); 00482 state.addIgnoredTypeAttr(attr); 00483 } 00484 00485 /// \brief Given that there are attributes written on the declarator 00486 /// itself, try to distribute any type attributes to the appropriate 00487 /// declarator chunk. 00488 /// 00489 /// These are attributes like the following: 00490 /// int f ATTR; 00491 /// int (f ATTR)(); 00492 /// but not necessarily this: 00493 /// int f() ATTR; 00494 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, 00495 QualType &declSpecType) { 00496 // Collect all the type attributes from the declarator itself. 00497 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!"); 00498 AttributeList *attr = state.getDeclarator().getAttributes(); 00499 AttributeList *next; 00500 do { 00501 next = attr->getNext(); 00502 00503 switch (attr->getKind()) { 00504 OBJC_POINTER_TYPE_ATTRS_CASELIST: 00505 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType); 00506 break; 00507 00508 case AttributeList::AT_ns_returns_retained: 00509 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 00510 break; 00511 // fallthrough 00512 00513 FUNCTION_TYPE_ATTRS_CASELIST: 00514 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType); 00515 break; 00516 00517 default: 00518 break; 00519 } 00520 } while ((attr = next)); 00521 } 00522 00523 /// Add a synthetic '()' to a block-literal declarator if it is 00524 /// required, given the return type. 00525 static void maybeSynthesizeBlockSignature(TypeProcessingState &state, 00526 QualType declSpecType) { 00527 Declarator &declarator = state.getDeclarator(); 00528 00529 // First, check whether the declarator would produce a function, 00530 // i.e. whether the innermost semantic chunk is a function. 00531 if (declarator.isFunctionDeclarator()) { 00532 // If so, make that declarator a prototyped declarator. 00533 declarator.getFunctionTypeInfo().hasPrototype = true; 00534 return; 00535 } 00536 00537 // If there are any type objects, the type as written won't name a 00538 // function, regardless of the decl spec type. This is because a 00539 // block signature declarator is always an abstract-declarator, and 00540 // abstract-declarators can't just be parentheses chunks. Therefore 00541 // we need to build a function chunk unless there are no type 00542 // objects and the decl spec type is a function. 00543 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) 00544 return; 00545 00546 // Note that there *are* cases with invalid declarators where 00547 // declarators consist solely of parentheses. In general, these 00548 // occur only in failed efforts to make function declarators, so 00549 // faking up the function chunk is still the right thing to do. 00550 00551 // Otherwise, we need to fake up a function declarator. 00552 SourceLocation loc = declarator.getLocStart(); 00553 00554 // ...and *prepend* it to the declarator. 00555 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( 00556 /*proto*/ true, 00557 /*variadic*/ false, SourceLocation(), 00558 /*args*/ 0, 0, 00559 /*type quals*/ 0, 00560 /*ref-qualifier*/true, SourceLocation(), 00561 /*const qualifier*/SourceLocation(), 00562 /*volatile qualifier*/SourceLocation(), 00563 /*mutable qualifier*/SourceLocation(), 00564 /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0, 00565 /*parens*/ loc, loc, 00566 declarator)); 00567 00568 // For consistency, make sure the state still has us as processing 00569 // the decl spec. 00570 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1); 00571 state.setCurrentChunkIndex(declarator.getNumTypeObjects()); 00572 } 00573 00574 /// \brief Convert the specified declspec to the appropriate type 00575 /// object. 00576 /// \param D the declarator containing the declaration specifier. 00577 /// \returns The type described by the declaration specifiers. This function 00578 /// never returns null. 00579 static QualType ConvertDeclSpecToType(TypeProcessingState &state) { 00580 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 00581 // checking. 00582 00583 Sema &S = state.getSema(); 00584 Declarator &declarator = state.getDeclarator(); 00585 const DeclSpec &DS = declarator.getDeclSpec(); 00586 SourceLocation DeclLoc = declarator.getIdentifierLoc(); 00587 if (DeclLoc.isInvalid()) 00588 DeclLoc = DS.getLocStart(); 00589 00590 ASTContext &Context = S.Context; 00591 00592 QualType Result; 00593 switch (DS.getTypeSpecType()) { 00594 case DeclSpec::TST_void: 00595 Result = Context.VoidTy; 00596 break; 00597 case DeclSpec::TST_char: 00598 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 00599 Result = Context.CharTy; 00600 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 00601 Result = Context.SignedCharTy; 00602 else { 00603 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 00604 "Unknown TSS value"); 00605 Result = Context.UnsignedCharTy; 00606 } 00607 break; 00608 case DeclSpec::TST_wchar: 00609 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 00610 Result = Context.WCharTy; 00611 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 00612 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 00613 << DS.getSpecifierName(DS.getTypeSpecType()); 00614 Result = Context.getSignedWCharType(); 00615 } else { 00616 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 00617 "Unknown TSS value"); 00618 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 00619 << DS.getSpecifierName(DS.getTypeSpecType()); 00620 Result = Context.getUnsignedWCharType(); 00621 } 00622 break; 00623 case DeclSpec::TST_char16: 00624 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 00625 "Unknown TSS value"); 00626 Result = Context.Char16Ty; 00627 break; 00628 case DeclSpec::TST_char32: 00629 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 00630 "Unknown TSS value"); 00631 Result = Context.Char32Ty; 00632 break; 00633 case DeclSpec::TST_unspecified: 00634 // "<proto1,proto2>" is an objc qualified ID with a missing id. 00635 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 00636 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 00637 (ObjCProtocolDecl**)PQ, 00638 DS.getNumProtocolQualifiers()); 00639 Result = Context.getObjCObjectPointerType(Result); 00640 break; 00641 } 00642 00643 // If this is a missing declspec in a block literal return context, then it 00644 // is inferred from the return statements inside the block. 00645 // The declspec is always missing in a lambda expr context; it is either 00646 // specified with a trailing return type or inferred. 00647 if (declarator.getContext() == Declarator::LambdaExprContext || 00648 isOmittedBlockReturnType(declarator)) { 00649 Result = Context.DependentTy; 00650 break; 00651 } 00652 00653 // Unspecified typespec defaults to int in C90. However, the C90 grammar 00654 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 00655 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 00656 // Note that the one exception to this is function definitions, which are 00657 // allowed to be completely missing a declspec. This is handled in the 00658 // parser already though by it pretending to have seen an 'int' in this 00659 // case. 00660 if (S.getLangOpts().ImplicitInt) { 00661 // In C89 mode, we only warn if there is a completely missing declspec 00662 // when one is not allowed. 00663 if (DS.isEmpty()) { 00664 S.Diag(DeclLoc, diag::ext_missing_declspec) 00665 << DS.getSourceRange() 00666 << FixItHint::CreateInsertion(DS.getLocStart(), "int"); 00667 } 00668 } else if (!DS.hasTypeSpecifier()) { 00669 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 00670 // "At least one type specifier shall be given in the declaration 00671 // specifiers in each declaration, and in the specifier-qualifier list in 00672 // each struct declaration and type name." 00673 // FIXME: Does Microsoft really have the implicit int extension in C++? 00674 if (S.getLangOpts().CPlusPlus && 00675 !S.getLangOpts().MicrosoftExt) { 00676 S.Diag(DeclLoc, diag::err_missing_type_specifier) 00677 << DS.getSourceRange(); 00678 00679 // When this occurs in C++ code, often something is very broken with the 00680 // value being declared, poison it as invalid so we don't get chains of 00681 // errors. 00682 declarator.setInvalidType(true); 00683 } else { 00684 S.Diag(DeclLoc, diag::ext_missing_type_specifier) 00685 << DS.getSourceRange(); 00686 } 00687 } 00688 00689 // FALL THROUGH. 00690 case DeclSpec::TST_int: { 00691 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 00692 switch (DS.getTypeSpecWidth()) { 00693 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 00694 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 00695 case DeclSpec::TSW_long: Result = Context.LongTy; break; 00696 case DeclSpec::TSW_longlong: 00697 Result = Context.LongLongTy; 00698 00699 // long long is a C99 feature. 00700 if (!S.getLangOpts().C99) 00701 S.Diag(DS.getTypeSpecWidthLoc(), 00702 S.getLangOpts().CPlusPlus0x ? 00703 diag::warn_cxx98_compat_longlong : diag::ext_longlong); 00704 break; 00705 } 00706 } else { 00707 switch (DS.getTypeSpecWidth()) { 00708 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 00709 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 00710 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 00711 case DeclSpec::TSW_longlong: 00712 Result = Context.UnsignedLongLongTy; 00713 00714 // long long is a C99 feature. 00715 if (!S.getLangOpts().C99) 00716 S.Diag(DS.getTypeSpecWidthLoc(), 00717 S.getLangOpts().CPlusPlus0x ? 00718 diag::warn_cxx98_compat_longlong : diag::ext_longlong); 00719 break; 00720 } 00721 } 00722 break; 00723 } 00724 case DeclSpec::TST_int128: 00725 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned) 00726 Result = Context.UnsignedInt128Ty; 00727 else 00728 Result = Context.Int128Ty; 00729 break; 00730 case DeclSpec::TST_half: Result = Context.HalfTy; break; 00731 case DeclSpec::TST_float: Result = Context.FloatTy; break; 00732 case DeclSpec::TST_double: 00733 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 00734 Result = Context.LongDoubleTy; 00735 else 00736 Result = Context.DoubleTy; 00737 00738 if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) { 00739 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64); 00740 declarator.setInvalidType(true); 00741 } 00742 break; 00743 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 00744 case DeclSpec::TST_decimal32: // _Decimal32 00745 case DeclSpec::TST_decimal64: // _Decimal64 00746 case DeclSpec::TST_decimal128: // _Decimal128 00747 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 00748 Result = Context.IntTy; 00749 declarator.setInvalidType(true); 00750 break; 00751 case DeclSpec::TST_class: 00752 case DeclSpec::TST_enum: 00753 case DeclSpec::TST_union: 00754 case DeclSpec::TST_struct: { 00755 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl()); 00756 if (!D) { 00757 // This can happen in C++ with ambiguous lookups. 00758 Result = Context.IntTy; 00759 declarator.setInvalidType(true); 00760 break; 00761 } 00762 00763 // If the type is deprecated or unavailable, diagnose it. 00764 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); 00765 00766 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 00767 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!"); 00768 00769 // TypeQuals handled by caller. 00770 Result = Context.getTypeDeclType(D); 00771 00772 // In both C and C++, make an ElaboratedType. 00773 ElaboratedTypeKeyword Keyword 00774 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); 00775 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result); 00776 break; 00777 } 00778 case DeclSpec::TST_typename: { 00779 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 00780 DS.getTypeSpecSign() == 0 && 00781 "Can't handle qualifiers on typedef names yet!"); 00782 Result = S.GetTypeFromParser(DS.getRepAsType()); 00783 if (Result.isNull()) 00784 declarator.setInvalidType(true); 00785 else if (DeclSpec::ProtocolQualifierListTy PQ 00786 = DS.getProtocolQualifiers()) { 00787 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) { 00788 // Silently drop any existing protocol qualifiers. 00789 // TODO: determine whether that's the right thing to do. 00790 if (ObjT->getNumProtocols()) 00791 Result = ObjT->getBaseType(); 00792 00793 if (DS.getNumProtocolQualifiers()) 00794 Result = Context.getObjCObjectType(Result, 00795 (ObjCProtocolDecl**) PQ, 00796 DS.getNumProtocolQualifiers()); 00797 } else if (Result->isObjCIdType()) { 00798 // id<protocol-list> 00799 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 00800 (ObjCProtocolDecl**) PQ, 00801 DS.getNumProtocolQualifiers()); 00802 Result = Context.getObjCObjectPointerType(Result); 00803 } else if (Result->isObjCClassType()) { 00804 // Class<protocol-list> 00805 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 00806 (ObjCProtocolDecl**) PQ, 00807 DS.getNumProtocolQualifiers()); 00808 Result = Context.getObjCObjectPointerType(Result); 00809 } else { 00810 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers) 00811 << DS.getSourceRange(); 00812 declarator.setInvalidType(true); 00813 } 00814 } 00815 00816 // TypeQuals handled by caller. 00817 break; 00818 } 00819 case DeclSpec::TST_typeofType: 00820 // FIXME: Preserve type source info. 00821 Result = S.GetTypeFromParser(DS.getRepAsType()); 00822 assert(!Result.isNull() && "Didn't get a type for typeof?"); 00823 if (!Result->isDependentType()) 00824 if (const TagType *TT = Result->getAs<TagType>()) 00825 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); 00826 // TypeQuals handled by caller. 00827 Result = Context.getTypeOfType(Result); 00828 break; 00829 case DeclSpec::TST_typeofExpr: { 00830 Expr *E = DS.getRepAsExpr(); 00831 assert(E && "Didn't get an expression for typeof?"); 00832 // TypeQuals handled by caller. 00833 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc()); 00834 if (Result.isNull()) { 00835 Result = Context.IntTy; 00836 declarator.setInvalidType(true); 00837 } 00838 break; 00839 } 00840 case DeclSpec::TST_decltype: { 00841 Expr *E = DS.getRepAsExpr(); 00842 assert(E && "Didn't get an expression for decltype?"); 00843 // TypeQuals handled by caller. 00844 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc()); 00845 if (Result.isNull()) { 00846 Result = Context.IntTy; 00847 declarator.setInvalidType(true); 00848 } 00849 break; 00850 } 00851 case DeclSpec::TST_underlyingType: 00852 Result = S.GetTypeFromParser(DS.getRepAsType()); 00853 assert(!Result.isNull() && "Didn't get a type for __underlying_type?"); 00854 Result = S.BuildUnaryTransformType(Result, 00855 UnaryTransformType::EnumUnderlyingType, 00856 DS.getTypeSpecTypeLoc()); 00857 if (Result.isNull()) { 00858 Result = Context.IntTy; 00859 declarator.setInvalidType(true); 00860 } 00861 break; 00862 00863 case DeclSpec::TST_auto: { 00864 // TypeQuals handled by caller. 00865 Result = Context.getAutoType(QualType()); 00866 break; 00867 } 00868 00869 case DeclSpec::TST_unknown_anytype: 00870 Result = Context.UnknownAnyTy; 00871 break; 00872 00873 case DeclSpec::TST_atomic: 00874 Result = S.GetTypeFromParser(DS.getRepAsType()); 00875 assert(!Result.isNull() && "Didn't get a type for _Atomic?"); 00876 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); 00877 if (Result.isNull()) { 00878 Result = Context.IntTy; 00879 declarator.setInvalidType(true); 00880 } 00881 break; 00882 00883 case DeclSpec::TST_error: 00884 Result = Context.IntTy; 00885 declarator.setInvalidType(true); 00886 break; 00887 } 00888 00889 // Handle complex types. 00890 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 00891 if (S.getLangOpts().Freestanding) 00892 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 00893 Result = Context.getComplexType(Result); 00894 } else if (DS.isTypeAltiVecVector()) { 00895 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); 00896 assert(typeSize > 0 && "type size for vector must be greater than 0 bits"); 00897 VectorType::VectorKind VecKind = VectorType::AltiVecVector; 00898 if (DS.isTypeAltiVecPixel()) 00899 VecKind = VectorType::AltiVecPixel; 00900 else if (DS.isTypeAltiVecBool()) 00901 VecKind = VectorType::AltiVecBool; 00902 Result = Context.getVectorType(Result, 128/typeSize, VecKind); 00903 } 00904 00905 // FIXME: Imaginary. 00906 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) 00907 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); 00908 00909 // Before we process any type attributes, synthesize a block literal 00910 // function declarator if necessary. 00911 if (declarator.getContext() == Declarator::BlockLiteralContext) 00912 maybeSynthesizeBlockSignature(state, Result); 00913 00914 // Apply any type attributes from the decl spec. This may cause the 00915 // list of type attributes to be temporarily saved while the type 00916 // attributes are pushed around. 00917 if (AttributeList *attrs = DS.getAttributes().getList()) 00918 processTypeAttrs(state, Result, true, attrs); 00919 00920 // Apply const/volatile/restrict qualifiers to T. 00921 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 00922 00923 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 00924 // or incomplete types shall not be restrict-qualified." C++ also allows 00925 // restrict-qualified references. 00926 if (TypeQuals & DeclSpec::TQ_restrict) { 00927 if (Result->isAnyPointerType() || Result->isReferenceType()) { 00928 QualType EltTy; 00929 if (Result->isObjCObjectPointerType()) 00930 EltTy = Result; 00931 else 00932 EltTy = Result->isPointerType() ? 00933 Result->getAs<PointerType>()->getPointeeType() : 00934 Result->getAs<ReferenceType>()->getPointeeType(); 00935 00936 // If we have a pointer or reference, the pointee must have an object 00937 // incomplete type. 00938 if (!EltTy->isIncompleteOrObjectType()) { 00939 S.Diag(DS.getRestrictSpecLoc(), 00940 diag::err_typecheck_invalid_restrict_invalid_pointee) 00941 << EltTy << DS.getSourceRange(); 00942 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier. 00943 } 00944 } else { 00945 S.Diag(DS.getRestrictSpecLoc(), 00946 diag::err_typecheck_invalid_restrict_not_pointer) 00947 << Result << DS.getSourceRange(); 00948 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier. 00949 } 00950 } 00951 00952 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification 00953 // of a function type includes any type qualifiers, the behavior is 00954 // undefined." 00955 if (Result->isFunctionType() && TypeQuals) { 00956 // Get some location to point at, either the C or V location. 00957 SourceLocation Loc; 00958 if (TypeQuals & DeclSpec::TQ_const) 00959 Loc = DS.getConstSpecLoc(); 00960 else if (TypeQuals & DeclSpec::TQ_volatile) 00961 Loc = DS.getVolatileSpecLoc(); 00962 else { 00963 assert((TypeQuals & DeclSpec::TQ_restrict) && 00964 "Has CVR quals but not C, V, or R?"); 00965 Loc = DS.getRestrictSpecLoc(); 00966 } 00967 S.Diag(Loc, diag::warn_typecheck_function_qualifiers) 00968 << Result << DS.getSourceRange(); 00969 } 00970 00971 // C++ [dcl.ref]p1: 00972 // Cv-qualified references are ill-formed except when the 00973 // cv-qualifiers are introduced through the use of a typedef 00974 // (7.1.3) or of a template type argument (14.3), in which 00975 // case the cv-qualifiers are ignored. 00976 // FIXME: Shouldn't we be checking SCS_typedef here? 00977 if (DS.getTypeSpecType() == DeclSpec::TST_typename && 00978 TypeQuals && Result->isReferenceType()) { 00979 TypeQuals &= ~DeclSpec::TQ_const; 00980 TypeQuals &= ~DeclSpec::TQ_volatile; 00981 } 00982 00983 // C90 6.5.3 constraints: "The same type qualifier shall not appear more 00984 // than once in the same specifier-list or qualifier-list, either directly 00985 // or via one or more typedefs." 00986 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus 00987 && TypeQuals & Result.getCVRQualifiers()) { 00988 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { 00989 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) 00990 << "const"; 00991 } 00992 00993 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { 00994 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) 00995 << "volatile"; 00996 } 00997 00998 // C90 doesn't have restrict, so it doesn't force us to produce a warning 00999 // in this case. 01000 } 01001 01002 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals); 01003 Result = Context.getQualifiedType(Result, Quals); 01004 } 01005 01006 return Result; 01007 } 01008 01009 static std::string getPrintableNameForEntity(DeclarationName Entity) { 01010 if (Entity) 01011 return Entity.getAsString(); 01012 01013 return "type name"; 01014 } 01015 01016 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, 01017 Qualifiers Qs) { 01018 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 01019 // object or incomplete types shall not be restrict-qualified." 01020 if (Qs.hasRestrict()) { 01021 unsigned DiagID = 0; 01022 QualType ProblemTy; 01023 01024 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr(); 01025 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) { 01026 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) { 01027 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 01028 ProblemTy = T->getAs<ReferenceType>()->getPointeeType(); 01029 } 01030 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) { 01031 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) { 01032 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 01033 ProblemTy = T->getAs<PointerType>()->getPointeeType(); 01034 } 01035 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) { 01036 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) { 01037 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 01038 ProblemTy = T->getAs<PointerType>()->getPointeeType(); 01039 } 01040 } else if (!Ty->isDependentType()) { 01041 // FIXME: this deserves a proper diagnostic 01042 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; 01043 ProblemTy = T; 01044 } 01045 01046 if (DiagID) { 01047 Diag(Loc, DiagID) << ProblemTy; 01048 Qs.removeRestrict(); 01049 } 01050 } 01051 01052 return Context.getQualifiedType(T, Qs); 01053 } 01054 01055 /// \brief Build a paren type including \p T. 01056 QualType Sema::BuildParenType(QualType T) { 01057 return Context.getParenType(T); 01058 } 01059 01060 /// Given that we're building a pointer or reference to the given 01061 static QualType inferARCLifetimeForPointee(Sema &S, QualType type, 01062 SourceLocation loc, 01063 bool isReference) { 01064 // Bail out if retention is unrequired or already specified. 01065 if (!type->isObjCLifetimeType() || 01066 type.getObjCLifetime() != Qualifiers::OCL_None) 01067 return type; 01068 01069 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; 01070 01071 // If the object type is const-qualified, we can safely use 01072 // __unsafe_unretained. This is safe (because there are no read 01073 // barriers), and it'll be safe to coerce anything but __weak* to 01074 // the resulting type. 01075 if (type.isConstQualified()) { 01076 implicitLifetime = Qualifiers::OCL_ExplicitNone; 01077 01078 // Otherwise, check whether the static type does not require 01079 // retaining. This currently only triggers for Class (possibly 01080 // protocol-qualifed, and arrays thereof). 01081 } else if (type->isObjCARCImplicitlyUnretainedType()) { 01082 implicitLifetime = Qualifiers::OCL_ExplicitNone; 01083 01084 // If we are in an unevaluated context, like sizeof, skip adding a 01085 // qualification. 01086 } else if (S.ExprEvalContexts.back().Context == Sema::Unevaluated) { 01087 return type; 01088 01089 // If that failed, give an error and recover using __strong. __strong 01090 // is the option most likely to prevent spurious second-order diagnostics, 01091 // like when binding a reference to a field. 01092 } else { 01093 // These types can show up in private ivars in system headers, so 01094 // we need this to not be an error in those cases. Instead we 01095 // want to delay. 01096 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 01097 S.DelayedDiagnostics.add( 01098 sema::DelayedDiagnostic::makeForbiddenType(loc, 01099 diag::err_arc_indirect_no_ownership, type, isReference)); 01100 } else { 01101 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; 01102 } 01103 implicitLifetime = Qualifiers::OCL_Strong; 01104 } 01105 assert(implicitLifetime && "didn't infer any lifetime!"); 01106 01107 Qualifiers qs; 01108 qs.addObjCLifetime(implicitLifetime); 01109 return S.Context.getQualifiedType(type, qs); 01110 } 01111 01112 /// \brief Build a pointer type. 01113 /// 01114 /// \param T The type to which we'll be building a pointer. 01115 /// 01116 /// \param Loc The location of the entity whose type involves this 01117 /// pointer type or, if there is no such entity, the location of the 01118 /// type that will have pointer type. 01119 /// 01120 /// \param Entity The name of the entity that involves the pointer 01121 /// type, if known. 01122 /// 01123 /// \returns A suitable pointer type, if there are no 01124 /// errors. Otherwise, returns a NULL type. 01125 QualType Sema::BuildPointerType(QualType T, 01126 SourceLocation Loc, DeclarationName Entity) { 01127 if (T->isReferenceType()) { 01128 // C++ 8.3.2p4: There shall be no ... pointers to references ... 01129 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 01130 << getPrintableNameForEntity(Entity) << T; 01131 return QualType(); 01132 } 01133 01134 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType"); 01135 01136 // In ARC, it is forbidden to build pointers to unqualified pointers. 01137 if (getLangOpts().ObjCAutoRefCount) 01138 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); 01139 01140 // Build the pointer type. 01141 return Context.getPointerType(T); 01142 } 01143 01144 /// \brief Build a reference type. 01145 /// 01146 /// \param T The type to which we'll be building a reference. 01147 /// 01148 /// \param Loc The location of the entity whose type involves this 01149 /// reference type or, if there is no such entity, the location of the 01150 /// type that will have reference type. 01151 /// 01152 /// \param Entity The name of the entity that involves the reference 01153 /// type, if known. 01154 /// 01155 /// \returns A suitable reference type, if there are no 01156 /// errors. Otherwise, returns a NULL type. 01157 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, 01158 SourceLocation Loc, 01159 DeclarationName Entity) { 01160 assert(Context.getCanonicalType(T) != Context.OverloadTy && 01161 "Unresolved overloaded function type"); 01162 01163 // C++0x [dcl.ref]p6: 01164 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a 01165 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a 01166 // type T, an attempt to create the type "lvalue reference to cv TR" creates 01167 // the type "lvalue reference to T", while an attempt to create the type 01168 // "rvalue reference to cv TR" creates the type TR. 01169 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); 01170 01171 // C++ [dcl.ref]p4: There shall be no references to references. 01172 // 01173 // According to C++ DR 106, references to references are only 01174 // diagnosed when they are written directly (e.g., "int & &"), 01175 // but not when they happen via a typedef: 01176 // 01177 // typedef int& intref; 01178 // typedef intref& intref2; 01179 // 01180 // Parser::ParseDeclaratorInternal diagnoses the case where 01181 // references are written directly; here, we handle the 01182 // collapsing of references-to-references as described in C++0x. 01183 // DR 106 and 540 introduce reference-collapsing into C++98/03. 01184 01185 // C++ [dcl.ref]p1: 01186 // A declarator that specifies the type "reference to cv void" 01187 // is ill-formed. 01188 if (T->isVoidType()) { 01189 Diag(Loc, diag::err_reference_to_void); 01190 return QualType(); 01191 } 01192 01193 // In ARC, it is forbidden to build references to unqualified pointers. 01194 if (getLangOpts().ObjCAutoRefCount) 01195 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); 01196 01197 // Handle restrict on references. 01198 if (LValueRef) 01199 return Context.getLValueReferenceType(T, SpelledAsLValue); 01200 return Context.getRValueReferenceType(T); 01201 } 01202 01203 /// Check whether the specified array size makes the array type a VLA. If so, 01204 /// return true, if not, return the size of the array in SizeVal. 01205 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) { 01206 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode 01207 // (like gnu99, but not c99) accept any evaluatable value as an extension. 01208 class VLADiagnoser : public Sema::VerifyICEDiagnoser { 01209 public: 01210 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {} 01211 01212 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 01213 } 01214 01215 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) { 01216 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR; 01217 } 01218 } Diagnoser; 01219 01220 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser, 01221 S.LangOpts.GNUMode).isInvalid(); 01222 } 01223 01224 01225 /// \brief Build an array type. 01226 /// 01227 /// \param T The type of each element in the array. 01228 /// 01229 /// \param ASM C99 array size modifier (e.g., '*', 'static'). 01230 /// 01231 /// \param ArraySize Expression describing the size of the array. 01232 /// 01233 /// \param Loc The location of the entity whose type involves this 01234 /// array type or, if there is no such entity, the location of the 01235 /// type that will have array type. 01236 /// 01237 /// \param Entity The name of the entity that involves the array 01238 /// type, if known. 01239 /// 01240 /// \returns A suitable array type, if there are no errors. Otherwise, 01241 /// returns a NULL type. 01242 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 01243 Expr *ArraySize, unsigned Quals, 01244 SourceRange Brackets, DeclarationName Entity) { 01245 01246 SourceLocation Loc = Brackets.getBegin(); 01247 if (getLangOpts().CPlusPlus) { 01248 // C++ [dcl.array]p1: 01249 // T is called the array element type; this type shall not be a reference 01250 // type, the (possibly cv-qualified) type void, a function type or an 01251 // abstract class type. 01252 // 01253 // Note: function types are handled in the common path with C. 01254 if (T->isReferenceType()) { 01255 Diag(Loc, diag::err_illegal_decl_array_of_references) 01256 << getPrintableNameForEntity(Entity) << T; 01257 return QualType(); 01258 } 01259 01260 if (T->isVoidType()) { 01261 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; 01262 return QualType(); 01263 } 01264 01265 if (RequireNonAbstractType(Brackets.getBegin(), T, 01266 diag::err_array_of_abstract_type)) 01267 return QualType(); 01268 01269 } else { 01270 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 01271 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 01272 if (RequireCompleteType(Loc, T, 01273 diag::err_illegal_decl_array_incomplete_type)) 01274 return QualType(); 01275 } 01276 01277 if (T->isFunctionType()) { 01278 Diag(Loc, diag::err_illegal_decl_array_of_functions) 01279 << getPrintableNameForEntity(Entity) << T; 01280 return QualType(); 01281 } 01282 01283 if (T->getContainedAutoType()) { 01284 Diag(Loc, diag::err_illegal_decl_array_of_auto) 01285 << getPrintableNameForEntity(Entity) << T; 01286 return QualType(); 01287 } 01288 01289 if (const RecordType *EltTy = T->getAs<RecordType>()) { 01290 // If the element type is a struct or union that contains a variadic 01291 // array, accept it as a GNU extension: C99 6.7.2.1p2. 01292 if (EltTy->getDecl()->hasFlexibleArrayMember()) 01293 Diag(Loc, diag::ext_flexible_array_in_array) << T; 01294 } else if (T->isObjCObjectType()) { 01295 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 01296 return QualType(); 01297 } 01298 01299 // Do placeholder conversions on the array size expression. 01300 if (ArraySize && ArraySize->hasPlaceholderType()) { 01301 ExprResult Result = CheckPlaceholderExpr(ArraySize); 01302 if (Result.isInvalid()) return QualType(); 01303 ArraySize = Result.take(); 01304 } 01305 01306 // Do lvalue-to-rvalue conversions on the array size expression. 01307 if (ArraySize && !ArraySize->isRValue()) { 01308 ExprResult Result = DefaultLvalueConversion(ArraySize); 01309 if (Result.isInvalid()) 01310 return QualType(); 01311 01312 ArraySize = Result.take(); 01313 } 01314 01315 // C99 6.7.5.2p1: The size expression shall have integer type. 01316 // C++11 allows contextual conversions to such types. 01317 if (!getLangOpts().CPlusPlus0x && 01318 ArraySize && !ArraySize->isTypeDependent() && 01319 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 01320 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 01321 << ArraySize->getType() << ArraySize->getSourceRange(); 01322 return QualType(); 01323 } 01324 01325 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); 01326 if (!ArraySize) { 01327 if (ASM == ArrayType::Star) 01328 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets); 01329 else 01330 T = Context.getIncompleteArrayType(T, ASM, Quals); 01331 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { 01332 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 01333 } else if ((!T->isDependentType() && !T->isIncompleteType() && 01334 !T->isConstantSizeType()) || 01335 isArraySizeVLA(*this, ArraySize, ConstVal)) { 01336 // Even in C++11, don't allow contextual conversions in the array bound 01337 // of a VLA. 01338 if (getLangOpts().CPlusPlus0x && 01339 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { 01340 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 01341 << ArraySize->getType() << ArraySize->getSourceRange(); 01342 return QualType(); 01343 } 01344 01345 // C99: an array with an element type that has a non-constant-size is a VLA. 01346 // C99: an array with a non-ICE size is a VLA. We accept any expression 01347 // that we can fold to a non-zero positive value as an extension. 01348 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 01349 } else { 01350 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 01351 // have a value greater than zero. 01352 if (ConstVal.isSigned() && ConstVal.isNegative()) { 01353 if (Entity) 01354 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size) 01355 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange(); 01356 else 01357 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size) 01358 << ArraySize->getSourceRange(); 01359 return QualType(); 01360 } 01361 if (ConstVal == 0) { 01362 // GCC accepts zero sized static arrays. We allow them when 01363 // we're not in a SFINAE context. 01364 Diag(ArraySize->getLocStart(), 01365 isSFINAEContext()? diag::err_typecheck_zero_array_size 01366 : diag::ext_typecheck_zero_array_size) 01367 << ArraySize->getSourceRange(); 01368 01369 if (ASM == ArrayType::Static) { 01370 Diag(ArraySize->getLocStart(), 01371 diag::warn_typecheck_zero_static_array_size) 01372 << ArraySize->getSourceRange(); 01373 ASM = ArrayType::Normal; 01374 } 01375 } else if (!T->isDependentType() && !T->isVariablyModifiedType() && 01376 !T->isIncompleteType()) { 01377 // Is the array too large? 01378 unsigned ActiveSizeBits 01379 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal); 01380 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) 01381 Diag(ArraySize->getLocStart(), diag::err_array_too_large) 01382 << ConstVal.toString(10) 01383 << ArraySize->getSourceRange(); 01384 } 01385 01386 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); 01387 } 01388 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 01389 if (!getLangOpts().C99) { 01390 if (T->isVariableArrayType()) { 01391 // Prohibit the use of non-POD types in VLAs. 01392 QualType BaseT = Context.getBaseElementType(T); 01393 if (!T->isDependentType() && 01394 !BaseT.isPODType(Context) && 01395 !BaseT->isObjCLifetimeType()) { 01396 Diag(Loc, diag::err_vla_non_pod) 01397 << BaseT; 01398 return QualType(); 01399 } 01400 // Prohibit the use of VLAs during template argument deduction. 01401 else if (isSFINAEContext()) { 01402 Diag(Loc, diag::err_vla_in_sfinae); 01403 return QualType(); 01404 } 01405 // Just extwarn about VLAs. 01406 else 01407 Diag(Loc, diag::ext_vla); 01408 } else if (ASM != ArrayType::Normal || Quals != 0) 01409 Diag(Loc, 01410 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx 01411 : diag::ext_c99_array_usage) << ASM; 01412 } 01413 01414 return T; 01415 } 01416 01417 /// \brief Build an ext-vector type. 01418 /// 01419 /// Run the required checks for the extended vector type. 01420 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, 01421 SourceLocation AttrLoc) { 01422 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 01423 // in conjunction with complex types (pointers, arrays, functions, etc.). 01424 if (!T->isDependentType() && 01425 !T->isIntegerType() && !T->isRealFloatingType()) { 01426 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 01427 return QualType(); 01428 } 01429 01430 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { 01431 llvm::APSInt vecSize(32); 01432 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) { 01433 Diag(AttrLoc, diag::err_attribute_argument_not_int) 01434 << "ext_vector_type" << ArraySize->getSourceRange(); 01435 return QualType(); 01436 } 01437 01438 // unlike gcc's vector_size attribute, the size is specified as the 01439 // number of elements, not the number of bytes. 01440 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 01441 01442 if (vectorSize == 0) { 01443 Diag(AttrLoc, diag::err_attribute_zero_size) 01444 << ArraySize->getSourceRange(); 01445 return QualType(); 01446 } 01447 01448 return Context.getExtVectorType(T, vectorSize); 01449 } 01450 01451 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); 01452 } 01453 01454 /// \brief Build a function type. 01455 /// 01456 /// This routine checks the function type according to C++ rules and 01457 /// under the assumption that the result type and parameter types have 01458 /// just been instantiated from a template. It therefore duplicates 01459 /// some of the behavior of GetTypeForDeclarator, but in a much 01460 /// simpler form that is only suitable for this narrow use case. 01461 /// 01462 /// \param T The return type of the function. 01463 /// 01464 /// \param ParamTypes The parameter types of the function. This array 01465 /// will be modified to account for adjustments to the types of the 01466 /// function parameters. 01467 /// 01468 /// \param NumParamTypes The number of parameter types in ParamTypes. 01469 /// 01470 /// \param Variadic Whether this is a variadic function type. 01471 /// 01472 /// \param HasTrailingReturn Whether this function has a trailing return type. 01473 /// 01474 /// \param Quals The cvr-qualifiers to be applied to the function type. 01475 /// 01476 /// \param Loc The location of the entity whose type involves this 01477 /// function type or, if there is no such entity, the location of the 01478 /// type that will have function type. 01479 /// 01480 /// \param Entity The name of the entity that involves the function 01481 /// type, if known. 01482 /// 01483 /// \returns A suitable function type, if there are no 01484 /// errors. Otherwise, returns a NULL type. 01485 QualType Sema::BuildFunctionType(QualType T, 01486 QualType *ParamTypes, 01487 unsigned NumParamTypes, 01488 bool Variadic, bool HasTrailingReturn, 01489 unsigned Quals, 01490 RefQualifierKind RefQualifier, 01491 SourceLocation Loc, DeclarationName Entity, 01492 FunctionType::ExtInfo Info) { 01493 if (T->isArrayType() || T->isFunctionType()) { 01494 Diag(Loc, diag::err_func_returning_array_function) 01495 << T->isFunctionType() << T; 01496 return QualType(); 01497 } 01498 01499 // Functions cannot return half FP. 01500 if (T->isHalfType()) { 01501 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << 01502 FixItHint::CreateInsertion(Loc, "*"); 01503 return QualType(); 01504 } 01505 01506 bool Invalid = false; 01507 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) { 01508 // FIXME: Loc is too inprecise here, should use proper locations for args. 01509 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); 01510 if (ParamType->isVoidType()) { 01511 Diag(Loc, diag::err_param_with_void_type); 01512 Invalid = true; 01513 } else if (ParamType->isHalfType()) { 01514 // Disallow half FP arguments. 01515 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << 01516 FixItHint::CreateInsertion(Loc, "*"); 01517 Invalid = true; 01518 } 01519 01520 ParamTypes[Idx] = ParamType; 01521 } 01522 01523 if (Invalid) 01524 return QualType(); 01525 01526 FunctionProtoType::ExtProtoInfo EPI; 01527 EPI.Variadic = Variadic; 01528 EPI.HasTrailingReturn = HasTrailingReturn; 01529 EPI.TypeQuals = Quals; 01530 EPI.RefQualifier = RefQualifier; 01531 EPI.ExtInfo = Info; 01532 01533 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI); 01534 } 01535 01536 /// \brief Build a member pointer type \c T Class::*. 01537 /// 01538 /// \param T the type to which the member pointer refers. 01539 /// \param Class the class type into which the member pointer points. 01540 /// \param Loc the location where this type begins 01541 /// \param Entity the name of the entity that will have this member pointer type 01542 /// 01543 /// \returns a member pointer type, if successful, or a NULL type if there was 01544 /// an error. 01545 QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 01546 SourceLocation Loc, 01547 DeclarationName Entity) { 01548 // Verify that we're not building a pointer to pointer to function with 01549 // exception specification. 01550 if (CheckDistantExceptionSpec(T)) { 01551 Diag(Loc, diag::err_distant_exception_spec); 01552 01553 // FIXME: If we're doing this as part of template instantiation, 01554 // we should return immediately. 01555 01556 // Build the type anyway, but use the canonical type so that the 01557 // exception specifiers are stripped off. 01558 T = Context.getCanonicalType(T); 01559 } 01560 01561 // C++ 8.3.3p3: A pointer to member shall not point to ... a member 01562 // with reference type, or "cv void." 01563 if (T->isReferenceType()) { 01564 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 01565 << (Entity? Entity.getAsString() : "type name") << T; 01566 return QualType(); 01567 } 01568 01569 if (T->isVoidType()) { 01570 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 01571 << (Entity? Entity.getAsString() : "type name"); 01572 return QualType(); 01573 } 01574 01575 if (!Class->isDependentType() && !Class->isRecordType()) { 01576 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 01577 return QualType(); 01578 } 01579 01580 // In the Microsoft ABI, the class is allowed to be an incomplete 01581 // type. In such cases, the compiler makes a worst-case assumption. 01582 // We make no such assumption right now, so emit an error if the 01583 // class isn't a complete type. 01584 if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft && 01585 RequireCompleteType(Loc, Class, diag::err_incomplete_type)) 01586 return QualType(); 01587 01588 return Context.getMemberPointerType(T, Class.getTypePtr()); 01589 } 01590 01591 /// \brief Build a block pointer type. 01592 /// 01593 /// \param T The type to which we'll be building a block pointer. 01594 /// 01595 /// \param CVR The cvr-qualifiers to be applied to the block pointer type. 01596 /// 01597 /// \param Loc The location of the entity whose type involves this 01598 /// block pointer type or, if there is no such entity, the location of the 01599 /// type that will have block pointer type. 01600 /// 01601 /// \param Entity The name of the entity that involves the block pointer 01602 /// type, if known. 01603 /// 01604 /// \returns A suitable block pointer type, if there are no 01605 /// errors. Otherwise, returns a NULL type. 01606 QualType Sema::BuildBlockPointerType(QualType T, 01607 SourceLocation Loc, 01608 DeclarationName Entity) { 01609 if (!T->isFunctionType()) { 01610 Diag(Loc, diag::err_nonfunction_block_type); 01611 return QualType(); 01612 } 01613 01614 return Context.getBlockPointerType(T); 01615 } 01616 01617 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { 01618 QualType QT = Ty.get(); 01619 if (QT.isNull()) { 01620 if (TInfo) *TInfo = 0; 01621 return QualType(); 01622 } 01623 01624 TypeSourceInfo *DI = 0; 01625 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 01626 QT = LIT->getType(); 01627 DI = LIT->getTypeSourceInfo(); 01628 } 01629 01630 if (TInfo) *TInfo = DI; 01631 return QT; 01632 } 01633 01634 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 01635 Qualifiers::ObjCLifetime ownership, 01636 unsigned chunkIndex); 01637 01638 /// Given that this is the declaration of a parameter under ARC, 01639 /// attempt to infer attributes and such for pointer-to-whatever 01640 /// types. 01641 static void inferARCWriteback(TypeProcessingState &state, 01642 QualType &declSpecType) { 01643 Sema &S = state.getSema(); 01644 Declarator &declarator = state.getDeclarator(); 01645 01646 // TODO: should we care about decl qualifiers? 01647 01648 // Check whether the declarator has the expected form. We walk 01649 // from the inside out in order to make the block logic work. 01650 unsigned outermostPointerIndex = 0; 01651 bool isBlockPointer = false; 01652 unsigned numPointers = 0; 01653 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { 01654 unsigned chunkIndex = i; 01655 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); 01656 switch (chunk.Kind) { 01657 case DeclaratorChunk::Paren: 01658 // Ignore parens. 01659 break; 01660 01661 case DeclaratorChunk::Reference: 01662 case DeclaratorChunk::Pointer: 01663 // Count the number of pointers. Treat references 01664 // interchangeably as pointers; if they're mis-ordered, normal 01665 // type building will discover that. 01666 outermostPointerIndex = chunkIndex; 01667 numPointers++; 01668 break; 01669 01670 case DeclaratorChunk::BlockPointer: 01671 // If we have a pointer to block pointer, that's an acceptable 01672 // indirect reference; anything else is not an application of 01673 // the rules. 01674 if (numPointers != 1) return; 01675 numPointers++; 01676 outermostPointerIndex = chunkIndex; 01677 isBlockPointer = true; 01678 01679 // We don't care about pointer structure in return values here. 01680 goto done; 01681 01682 case DeclaratorChunk::Array: // suppress if written (id[])? 01683 case DeclaratorChunk::Function: 01684 case DeclaratorChunk::MemberPointer: 01685 return; 01686 } 01687 } 01688 done: 01689 01690 // If we have *one* pointer, then we want to throw the qualifier on 01691 // the declaration-specifiers, which means that it needs to be a 01692 // retainable object type. 01693 if (numPointers == 1) { 01694 // If it's not a retainable object type, the rule doesn't apply. 01695 if (!declSpecType->isObjCRetainableType()) return; 01696 01697 // If it already has lifetime, don't do anything. 01698 if (declSpecType.getObjCLifetime()) return; 01699 01700 // Otherwise, modify the type in-place. 01701 Qualifiers qs; 01702 01703 if (declSpecType->isObjCARCImplicitlyUnretainedType()) 01704 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); 01705 else 01706 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); 01707 declSpecType = S.Context.getQualifiedType(declSpecType, qs); 01708 01709 // If we have *two* pointers, then we want to throw the qualifier on 01710 // the outermost pointer. 01711 } else if (numPointers == 2) { 01712 // If we don't have a block pointer, we need to check whether the 01713 // declaration-specifiers gave us something that will turn into a 01714 // retainable object pointer after we slap the first pointer on it. 01715 if (!isBlockPointer && !declSpecType->isObjCObjectType()) 01716 return; 01717 01718 // Look for an explicit lifetime attribute there. 01719 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); 01720 if (chunk.Kind != DeclaratorChunk::Pointer && 01721 chunk.Kind != DeclaratorChunk::BlockPointer) 01722 return; 01723 for (const AttributeList *attr = chunk.getAttrs(); attr; 01724 attr = attr->getNext()) 01725 if (attr->getKind() == AttributeList::AT_objc_ownership) 01726 return; 01727 01728 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, 01729 outermostPointerIndex); 01730 01731 // Any other number of pointers/references does not trigger the rule. 01732 } else return; 01733 01734 // TODO: mark whether we did this inference? 01735 } 01736 01737 static void DiagnoseIgnoredQualifiers(unsigned Quals, 01738 SourceLocation ConstQualLoc, 01739 SourceLocation VolatileQualLoc, 01740 SourceLocation RestrictQualLoc, 01741 Sema& S) { 01742 std::string QualStr; 01743 unsigned NumQuals = 0; 01744 SourceLocation Loc; 01745 01746 FixItHint ConstFixIt; 01747 FixItHint VolatileFixIt; 01748 FixItHint RestrictFixIt; 01749 01750 const SourceManager &SM = S.getSourceManager(); 01751 01752 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to 01753 // find a range and grow it to encompass all the qualifiers, regardless of 01754 // the order in which they textually appear. 01755 if (Quals & Qualifiers::Const) { 01756 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc); 01757 QualStr = "const"; 01758 ++NumQuals; 01759 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc)) 01760 Loc = ConstQualLoc; 01761 } 01762 if (Quals & Qualifiers::Volatile) { 01763 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc); 01764 QualStr += (NumQuals == 0 ? "volatile" : " volatile"); 01765 ++NumQuals; 01766 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc)) 01767 Loc = VolatileQualLoc; 01768 } 01769 if (Quals & Qualifiers::Restrict) { 01770 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc); 01771 QualStr += (NumQuals == 0 ? "restrict" : " restrict"); 01772 ++NumQuals; 01773 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc)) 01774 Loc = RestrictQualLoc; 01775 } 01776 01777 assert(NumQuals > 0 && "No known qualifiers?"); 01778 01779 S.Diag(Loc, diag::warn_qual_return_type) 01780 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt; 01781 } 01782 01783 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, 01784 TypeSourceInfo *&ReturnTypeInfo) { 01785 Sema &SemaRef = state.getSema(); 01786 Declarator &D = state.getDeclarator(); 01787 QualType T; 01788 ReturnTypeInfo = 0; 01789 01790 // The TagDecl owned by the DeclSpec. 01791 TagDecl *OwnedTagDecl = 0; 01792 01793 switch (D.getName().getKind()) { 01794 case UnqualifiedId::IK_ImplicitSelfParam: 01795 case UnqualifiedId::IK_OperatorFunctionId: 01796 case UnqualifiedId::IK_Identifier: 01797 case UnqualifiedId::IK_LiteralOperatorId: 01798 case UnqualifiedId::IK_TemplateId: 01799 T = ConvertDeclSpecToType(state); 01800 01801 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 01802 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 01803 // Owned declaration is embedded in declarator. 01804 OwnedTagDecl->setEmbeddedInDeclarator(true); 01805 } 01806 break; 01807 01808 case UnqualifiedId::IK_ConstructorName: 01809 case UnqualifiedId::IK_ConstructorTemplateId: 01810 case UnqualifiedId::IK_DestructorName: 01811 // Constructors and destructors don't have return types. Use 01812 // "void" instead. 01813 T = SemaRef.Context.VoidTy; 01814 break; 01815 01816 case UnqualifiedId::IK_ConversionFunctionId: 01817 // The result type of a conversion function is the type that it 01818 // converts to. 01819 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, 01820 &ReturnTypeInfo); 01821 break; 01822 } 01823 01824 if (D.getAttributes()) 01825 distributeTypeAttrsFromDeclarator(state, T); 01826 01827 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. 01828 // In C++11, a function declarator using 'auto' must have a trailing return 01829 // type (this is checked later) and we can skip this. In other languages 01830 // using auto, we need to check regardless. 01831 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 01832 (!SemaRef.getLangOpts().CPlusPlus0x || !D.isFunctionDeclarator())) { 01833 int Error = -1; 01834 01835 switch (D.getContext()) { 01836 case Declarator::KNRTypeListContext: 01837 llvm_unreachable("K&R type lists aren't allowed in C++"); 01838 case Declarator::LambdaExprContext: 01839 llvm_unreachable("Can't specify a type specifier in lambda grammar"); 01840 case Declarator::ObjCParameterContext: 01841 case Declarator::ObjCResultContext: 01842 case Declarator::PrototypeContext: 01843 Error = 0; // Function prototype 01844 break; 01845 case Declarator::MemberContext: 01846 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) 01847 break; 01848 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { 01849 case TTK_Enum: llvm_unreachable("unhandled tag kind"); 01850 case TTK_Struct: Error = 1; /* Struct member */ break; 01851 case TTK_Union: Error = 2; /* Union member */ break; 01852 case TTK_Class: Error = 3; /* Class member */ break; 01853 } 01854 break; 01855 case Declarator::CXXCatchContext: 01856 case Declarator::ObjCCatchContext: 01857 Error = 4; // Exception declaration 01858 break; 01859 case Declarator::TemplateParamContext: 01860 Error = 5; // Template parameter 01861 break; 01862 case Declarator::BlockLiteralContext: 01863 Error = 6; // Block literal 01864 break; 01865 case Declarator::TemplateTypeArgContext: 01866 Error = 7; // Template type argument 01867 break; 01868 case Declarator::AliasDeclContext: 01869 case Declarator::AliasTemplateContext: 01870 Error = 9; // Type alias 01871 break; 01872 case Declarator::TrailingReturnContext: 01873 Error = 10; // Function return type 01874 break; 01875 case Declarator::TypeNameContext: 01876 Error = 11; // Generic 01877 break; 01878 case Declarator::FileContext: 01879 case Declarator::BlockContext: 01880 case Declarator::ForContext: 01881 case Declarator::ConditionContext: 01882 case Declarator::CXXNewContext: 01883 break; 01884 } 01885 01886 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 01887 Error = 8; 01888 01889 // In Objective-C it is an error to use 'auto' on a function declarator. 01890 if (D.isFunctionDeclarator()) 01891 Error = 10; 01892 01893 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator 01894 // contains a trailing return type. That is only legal at the outermost 01895 // level. Check all declarator chunks (outermost first) anyway, to give 01896 // better diagnostics. 01897 if (SemaRef.getLangOpts().CPlusPlus0x && Error != -1) { 01898 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 01899 unsigned chunkIndex = e - i - 1; 01900 state.setCurrentChunkIndex(chunkIndex); 01901 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 01902 if (DeclType.Kind == DeclaratorChunk::Function) { 01903 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 01904 if (FTI.TrailingReturnType) { 01905 Error = -1; 01906 break; 01907 } 01908 } 01909 } 01910 } 01911 01912 if (Error != -1) { 01913 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 01914 diag::err_auto_not_allowed) 01915 << Error; 01916 T = SemaRef.Context.IntTy; 01917 D.setInvalidType(true); 01918 } else 01919 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 01920 diag::warn_cxx98_compat_auto_type_specifier); 01921 } 01922 01923 if (SemaRef.getLangOpts().CPlusPlus && 01924 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { 01925 // Check the contexts where C++ forbids the declaration of a new class 01926 // or enumeration in a type-specifier-seq. 01927 switch (D.getContext()) { 01928 case Declarator::TrailingReturnContext: 01929 // Class and enumeration definitions are syntactically not allowed in 01930 // trailing return types. 01931 llvm_unreachable("parser should not have allowed this"); 01932 break; 01933 case Declarator::FileContext: 01934 case Declarator::MemberContext: 01935 case Declarator::BlockContext: 01936 case Declarator::ForContext: 01937 case Declarator::BlockLiteralContext: 01938 case Declarator::LambdaExprContext: 01939 // C++11 [dcl.type]p3: 01940 // A type-specifier-seq shall not define a class or enumeration unless 01941 // it appears in the type-id of an alias-declaration (7.1.3) that is not 01942 // the declaration of a template-declaration. 01943 case Declarator::AliasDeclContext: 01944 break; 01945 case Declarator::AliasTemplateContext: 01946 SemaRef.Diag(OwnedTagDecl->getLocation(), 01947 diag::err_type_defined_in_alias_template) 01948 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 01949 break; 01950 case Declarator::TypeNameContext: 01951 case Declarator::TemplateParamContext: 01952 case Declarator::CXXNewContext: 01953 case Declarator::CXXCatchContext: 01954 case Declarator::ObjCCatchContext: 01955 case Declarator::TemplateTypeArgContext: 01956 SemaRef.Diag(OwnedTagDecl->getLocation(), 01957 diag::err_type_defined_in_type_specifier) 01958 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 01959 break; 01960 case Declarator::PrototypeContext: 01961 case Declarator::ObjCParameterContext: 01962 case Declarator::ObjCResultContext: 01963 case Declarator::KNRTypeListContext: 01964 // C++ [dcl.fct]p6: 01965 // Types shall not be defined in return or parameter types. 01966 SemaRef.Diag(OwnedTagDecl->getLocation(), 01967 diag::err_type_defined_in_param_type) 01968 << SemaRef.Context.getTypeDeclType(OwnedTagDecl); 01969 break; 01970 case Declarator::ConditionContext: 01971 // C++ 6.4p2: 01972 // The type-specifier-seq shall not contain typedef and shall not declare 01973 // a new class or enumeration. 01974 SemaRef.Diag(OwnedTagDecl->getLocation(), 01975 diag::err_type_defined_in_condition); 01976 break; 01977 } 01978 } 01979 01980 return T; 01981 } 01982 01983 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ 01984 std::string Quals = 01985 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString(); 01986 01987 switch (FnTy->getRefQualifier()) { 01988 case RQ_None: 01989 break; 01990 01991 case RQ_LValue: 01992 if (!Quals.empty()) 01993 Quals += ' '; 01994 Quals += '&'; 01995 break; 01996 01997 case RQ_RValue: 01998 if (!Quals.empty()) 01999 Quals += ' '; 02000 Quals += "&&"; 02001 break; 02002 } 02003 02004 return Quals; 02005 } 02006 02007 /// Check that the function type T, which has a cv-qualifier or a ref-qualifier, 02008 /// can be contained within the declarator chunk DeclType, and produce an 02009 /// appropriate diagnostic if not. 02010 static void checkQualifiedFunction(Sema &S, QualType T, 02011 DeclaratorChunk &DeclType) { 02012 // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a 02013 // cv-qualifier or a ref-qualifier can only appear at the topmost level 02014 // of a type. 02015 int DiagKind = -1; 02016 switch (DeclType.Kind) { 02017 case DeclaratorChunk::Paren: 02018 case DeclaratorChunk::MemberPointer: 02019 // These cases are permitted. 02020 return; 02021 case DeclaratorChunk::Array: 02022 case DeclaratorChunk::Function: 02023 // These cases don't allow function types at all; no need to diagnose the 02024 // qualifiers separately. 02025 return; 02026 case DeclaratorChunk::BlockPointer: 02027 DiagKind = 0; 02028 break; 02029 case DeclaratorChunk::Pointer: 02030 DiagKind = 1; 02031 break; 02032 case DeclaratorChunk::Reference: 02033 DiagKind = 2; 02034 break; 02035 } 02036 02037 assert(DiagKind != -1); 02038 S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type) 02039 << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T 02040 << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>()); 02041 } 02042 02043 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, 02044 QualType declSpecType, 02045 TypeSourceInfo *TInfo) { 02046 02047 QualType T = declSpecType; 02048 Declarator &D = state.getDeclarator(); 02049 Sema &S = state.getSema(); 02050 ASTContext &Context = S.Context; 02051 const LangOptions &LangOpts = S.getLangOpts(); 02052 02053 bool ImplicitlyNoexcept = false; 02054 if (D.getName().getKind() == UnqualifiedId::IK_OperatorFunctionId && 02055 LangOpts.CPlusPlus0x) { 02056 OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator; 02057 /// In C++0x, deallocation functions (normal and array operator delete) 02058 /// are implicitly noexcept. 02059 if (OO == OO_Delete || OO == OO_Array_Delete) 02060 ImplicitlyNoexcept = true; 02061 } 02062 02063 // The name we're declaring, if any. 02064 DeclarationName Name; 02065 if (D.getIdentifier()) 02066 Name = D.getIdentifier(); 02067 02068 // Does this declaration declare a typedef-name? 02069 bool IsTypedefName = 02070 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || 02071 D.getContext() == Declarator::AliasDeclContext || 02072 D.getContext() == Declarator::AliasTemplateContext; 02073 02074 // Does T refer to a function type with a cv-qualifier or a ref-qualifier? 02075 bool IsQualifiedFunction = T->isFunctionProtoType() && 02076 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 || 02077 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); 02078 02079 // Walk the DeclTypeInfo, building the recursive type as we go. 02080 // DeclTypeInfos are ordered from the identifier out, which is 02081 // opposite of what we want :). 02082 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 02083 unsigned chunkIndex = e - i - 1; 02084 state.setCurrentChunkIndex(chunkIndex); 02085 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); 02086 if (IsQualifiedFunction) { 02087 checkQualifiedFunction(S, T, DeclType); 02088 IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren; 02089 } 02090 switch (DeclType.Kind) { 02091 case DeclaratorChunk::Paren: 02092 T = S.BuildParenType(T); 02093 break; 02094 case DeclaratorChunk::BlockPointer: 02095 // If blocks are disabled, emit an error. 02096 if (!LangOpts.Blocks) 02097 S.Diag(DeclType.Loc, diag::err_blocks_disable); 02098 02099 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); 02100 if (DeclType.Cls.TypeQuals) 02101 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); 02102 break; 02103 case DeclaratorChunk::Pointer: 02104 // Verify that we're not building a pointer to pointer to function with 02105 // exception specification. 02106 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 02107 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 02108 D.setInvalidType(true); 02109 // Build the type anyway. 02110 } 02111 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) { 02112 T = Context.getObjCObjectPointerType(T); 02113 if (DeclType.Ptr.TypeQuals) 02114 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 02115 break; 02116 } 02117 T = S.BuildPointerType(T, DeclType.Loc, Name); 02118 if (DeclType.Ptr.TypeQuals) 02119 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); 02120 02121 break; 02122 case DeclaratorChunk::Reference: { 02123 // Verify that we're not building a reference to pointer to function with 02124 // exception specification. 02125 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 02126 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 02127 D.setInvalidType(true); 02128 // Build the type anyway. 02129 } 02130 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); 02131 02132 Qualifiers Quals; 02133 if (DeclType.Ref.HasRestrict) 02134 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); 02135 break; 02136 } 02137 case DeclaratorChunk::Array: { 02138 // Verify that we're not building an array of pointers to function with 02139 // exception specification. 02140 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { 02141 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 02142 D.setInvalidType(true); 02143 // Build the type anyway. 02144 } 02145 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 02146 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 02147 ArrayType::ArraySizeModifier ASM; 02148 if (ATI.isStar) 02149 ASM = ArrayType::Star; 02150 else if (ATI.hasStatic) 02151 ASM = ArrayType::Static; 02152 else 02153 ASM = ArrayType::Normal; 02154 if (ASM == ArrayType::Star && !D.isPrototypeContext()) { 02155 // FIXME: This check isn't quite right: it allows star in prototypes 02156 // for function definitions, and disallows some edge cases detailed 02157 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 02158 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 02159 ASM = ArrayType::Normal; 02160 D.setInvalidType(true); 02161 } 02162 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 02163 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 02164 break; 02165 } 02166 case DeclaratorChunk::Function: { 02167 // If the function declarator has a prototype (i.e. it is not () and 02168 // does not have a K&R-style identifier list), then the arguments are part 02169 // of the type, otherwise the argument list is (). 02170 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 02171 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier(); 02172 02173 // Check for auto functions and trailing return type and adjust the 02174 // return type accordingly. 02175 if (!D.isInvalidType()) { 02176 // trailing-return-type is only required if we're declaring a function, 02177 // and not, for instance, a pointer to a function. 02178 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 02179 !FTI.TrailingReturnType && chunkIndex == 0) { 02180 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 02181 diag::err_auto_missing_trailing_return); 02182 T = Context.IntTy; 02183 D.setInvalidType(true); 02184 } else if (FTI.TrailingReturnType) { 02185 // T must be exactly 'auto' at this point. See CWG issue 681. 02186 if (isa<ParenType>(T)) { 02187 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 02188 diag::err_trailing_return_in_parens) 02189 << T << D.getDeclSpec().getSourceRange(); 02190 D.setInvalidType(true); 02191 } else if (D.getContext() != Declarator::LambdaExprContext && 02192 (T.hasQualifiers() || !isa<AutoType>(T))) { 02193 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), 02194 diag::err_trailing_return_without_auto) 02195 << T << D.getDeclSpec().getSourceRange(); 02196 D.setInvalidType(true); 02197 } 02198 02199 T = S.GetTypeFromParser( 02200 ParsedType::getFromOpaquePtr(FTI.TrailingReturnType), 02201 &TInfo); 02202 } 02203 } 02204 02205 // C99 6.7.5.3p1: The return type may not be a function or array type. 02206 // For conversion functions, we'll diagnose this particular error later. 02207 if ((T->isArrayType() || T->isFunctionType()) && 02208 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 02209 unsigned diagID = diag::err_func_returning_array_function; 02210 // Last processing chunk in block context means this function chunk 02211 // represents the block. 02212 if (chunkIndex == 0 && 02213 D.getContext() == Declarator::BlockLiteralContext) 02214 diagID = diag::err_block_returning_array_function; 02215 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; 02216 T = Context.IntTy; 02217 D.setInvalidType(true); 02218 } 02219 02220 // Do not allow returning half FP value. 02221 // FIXME: This really should be in BuildFunctionType. 02222 if (T->isHalfType()) { 02223 S.Diag(D.getIdentifierLoc(), 02224 diag::err_parameters_retval_cannot_have_fp16_type) << 1 02225 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*"); 02226 D.setInvalidType(true); 02227 } 02228 02229 // cv-qualifiers on return types are pointless except when the type is a 02230 // class type in C++. 02231 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() && 02232 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) && 02233 (!LangOpts.CPlusPlus || !T->isDependentType())) { 02234 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?"); 02235 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); 02236 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer); 02237 02238 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr; 02239 02240 DiagnoseIgnoredQualifiers(PTI.TypeQuals, 02241 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc), 02242 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc), 02243 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc), 02244 S); 02245 02246 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() && 02247 (!LangOpts.CPlusPlus || 02248 (!T->isDependentType() && !T->isRecordType()))) { 02249 02250 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(), 02251 D.getDeclSpec().getConstSpecLoc(), 02252 D.getDeclSpec().getVolatileSpecLoc(), 02253 D.getDeclSpec().getRestrictSpecLoc(), 02254 S); 02255 } 02256 02257 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) { 02258 // C++ [dcl.fct]p6: 02259 // Types shall not be defined in return or parameter types. 02260 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 02261 if (Tag->isCompleteDefinition()) 02262 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 02263 << Context.getTypeDeclType(Tag); 02264 } 02265 02266 // Exception specs are not allowed in typedefs. Complain, but add it 02267 // anyway. 02268 if (IsTypedefName && FTI.getExceptionSpecType()) 02269 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef) 02270 << (D.getContext() == Declarator::AliasDeclContext || 02271 D.getContext() == Declarator::AliasTemplateContext); 02272 02273 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) { 02274 // Simple void foo(), where the incoming T is the result type. 02275 T = Context.getFunctionNoProtoType(T); 02276 } else { 02277 // We allow a zero-parameter variadic function in C if the 02278 // function is marked with the "overloadable" attribute. Scan 02279 // for this attribute now. 02280 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) { 02281 bool Overloadable = false; 02282 for (const AttributeList *Attrs = D.getAttributes(); 02283 Attrs; Attrs = Attrs->getNext()) { 02284 if (Attrs->getKind() == AttributeList::AT_overloadable) { 02285 Overloadable = true; 02286 break; 02287 } 02288 } 02289 02290 if (!Overloadable) 02291 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); 02292 } 02293 02294 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) { 02295 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function 02296 // definition. 02297 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 02298 D.setInvalidType(true); 02299 break; 02300 } 02301 02302 FunctionProtoType::ExtProtoInfo EPI; 02303 EPI.Variadic = FTI.isVariadic; 02304 EPI.HasTrailingReturn = FTI.TrailingReturnType; 02305 EPI.TypeQuals = FTI.TypeQuals; 02306 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None 02307 : FTI.RefQualifierIsLValueRef? RQ_LValue 02308 : RQ_RValue; 02309 02310 // Otherwise, we have a function with an argument list that is 02311 // potentially variadic. 02312 SmallVector<QualType, 16> ArgTys; 02313 ArgTys.reserve(FTI.NumArgs); 02314 02315 SmallVector<bool, 16> ConsumedArguments; 02316 ConsumedArguments.reserve(FTI.NumArgs); 02317 bool HasAnyConsumedArguments = false; 02318 02319 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 02320 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 02321 QualType ArgTy = Param->getType(); 02322 assert(!ArgTy.isNull() && "Couldn't parse type?"); 02323 02324 // Adjust the parameter type. 02325 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) && 02326 "Unadjusted type?"); 02327 02328 // Look for 'void'. void is allowed only as a single argument to a 02329 // function with no other parameters (C99 6.7.5.3p10). We record 02330 // int(void) as a FunctionProtoType with an empty argument list. 02331 if (ArgTy->isVoidType()) { 02332 // If this is something like 'float(int, void)', reject it. 'void' 02333 // is an incomplete type (C99 6.2.5p19) and function decls cannot 02334 // have arguments of incomplete type. 02335 if (FTI.NumArgs != 1 || FTI.isVariadic) { 02336 S.Diag(DeclType.Loc, diag::err_void_only_param); 02337 ArgTy = Context.IntTy; 02338 Param->setType(ArgTy); 02339 } else if (FTI.ArgInfo[i].Ident) { 02340 // Reject, but continue to parse 'int(void abc)'. 02341 S.Diag(FTI.ArgInfo[i].IdentLoc, 02342 diag::err_param_with_void_type); 02343 ArgTy = Context.IntTy; 02344 Param->setType(ArgTy); 02345 } else { 02346 // Reject, but continue to parse 'float(const void)'. 02347 if (ArgTy.hasQualifiers()) 02348 S.Diag(DeclType.Loc, diag::err_void_param_qualified); 02349 02350 // Do not add 'void' to the ArgTys list. 02351 break; 02352 } 02353 } else if (ArgTy->isHalfType()) { 02354 // Disallow half FP arguments. 02355 // FIXME: This really should be in BuildFunctionType. 02356 S.Diag(Param->getLocation(), 02357 diag::err_parameters_retval_cannot_have_fp16_type) << 0 02358 << FixItHint::CreateInsertion(Param->getLocation(), "*"); 02359 D.setInvalidType(); 02360 } else if (!FTI.hasPrototype) { 02361 if (ArgTy->isPromotableIntegerType()) { 02362 ArgTy = Context.getPromotedIntegerType(ArgTy); 02363 Param->setKNRPromoted(true); 02364 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) { 02365 if (BTy->getKind() == BuiltinType::Float) { 02366 ArgTy = Context.DoubleTy; 02367 Param->setKNRPromoted(true); 02368 } 02369 } 02370 } 02371 02372 if (LangOpts.ObjCAutoRefCount) { 02373 bool Consumed = Param->hasAttr<NSConsumedAttr>(); 02374 ConsumedArguments.push_back(Consumed); 02375 HasAnyConsumedArguments |= Consumed; 02376 } 02377 02378 ArgTys.push_back(ArgTy); 02379 } 02380 02381 if (HasAnyConsumedArguments) 02382 EPI.ConsumedArguments = ConsumedArguments.data(); 02383 02384 SmallVector<QualType, 4> Exceptions; 02385 SmallVector<ParsedType, 2> DynamicExceptions; 02386 SmallVector<SourceRange, 2> DynamicExceptionRanges; 02387 Expr *NoexceptExpr = 0; 02388 02389 if (FTI.getExceptionSpecType() == EST_Dynamic) { 02390 // FIXME: It's rather inefficient to have to split into two vectors 02391 // here. 02392 unsigned N = FTI.NumExceptions; 02393 DynamicExceptions.reserve(N); 02394 DynamicExceptionRanges.reserve(N); 02395 for (unsigned I = 0; I != N; ++I) { 02396 DynamicExceptions.push_back(FTI.Exceptions[I].Ty); 02397 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); 02398 } 02399 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) { 02400 NoexceptExpr = FTI.NoexceptExpr; 02401 } 02402 02403 S.checkExceptionSpecification(FTI.getExceptionSpecType(), 02404 DynamicExceptions, 02405 DynamicExceptionRanges, 02406 NoexceptExpr, 02407 Exceptions, 02408 EPI); 02409 02410 if (FTI.getExceptionSpecType() == EST_None && 02411 ImplicitlyNoexcept && chunkIndex == 0) { 02412 // Only the outermost chunk is marked noexcept, of course. 02413 EPI.ExceptionSpecType = EST_BasicNoexcept; 02414 } 02415 02416 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI); 02417 } 02418 02419 break; 02420 } 02421 case DeclaratorChunk::MemberPointer: 02422 // The scope spec must refer to a class, or be dependent. 02423 CXXScopeSpec &SS = DeclType.Mem.Scope(); 02424 QualType ClsType; 02425 if (SS.isInvalid()) { 02426 // Avoid emitting extra errors if we already errored on the scope. 02427 D.setInvalidType(true); 02428 } else if (S.isDependentScopeSpecifier(SS) || 02429 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) { 02430 NestedNameSpecifier *NNS 02431 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 02432 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 02433 switch (NNS->getKind()) { 02434 case NestedNameSpecifier::Identifier: 02435 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 02436 NNS->getAsIdentifier()); 02437 break; 02438 02439 case NestedNameSpecifier::Namespace: 02440 case NestedNameSpecifier::NamespaceAlias: 02441 case NestedNameSpecifier::Global: 02442 llvm_unreachable("Nested-name-specifier must name a type"); 02443 02444 case NestedNameSpecifier::TypeSpec: 02445 case NestedNameSpecifier::TypeSpecWithTemplate: 02446 ClsType = QualType(NNS->getAsType(), 0); 02447 // Note: if the NNS has a prefix and ClsType is a nondependent 02448 // TemplateSpecializationType, then the NNS prefix is NOT included 02449 // in ClsType; hence we wrap ClsType into an ElaboratedType. 02450 // NOTE: in particular, no wrap occurs if ClsType already is an 02451 // Elaborated, DependentName, or DependentTemplateSpecialization. 02452 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) 02453 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 02454 break; 02455 } 02456 } else { 02457 S.Diag(DeclType.Mem.Scope().getBeginLoc(), 02458 diag::err_illegal_decl_mempointer_in_nonclass) 02459 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 02460 << DeclType.Mem.Scope().getRange(); 02461 D.setInvalidType(true); 02462 } 02463 02464 if (!ClsType.isNull()) 02465 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier()); 02466 if (T.isNull()) { 02467 T = Context.IntTy; 02468 D.setInvalidType(true); 02469 } else if (DeclType.Mem.TypeQuals) { 02470 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); 02471 } 02472 break; 02473 } 02474 02475 if (T.isNull()) { 02476 D.setInvalidType(true); 02477 T = Context.IntTy; 02478 } 02479 02480 // See if there are any attributes on this declarator chunk. 02481 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs())) 02482 processTypeAttrs(state, T, false, attrs); 02483 } 02484 02485 if (LangOpts.CPlusPlus && T->isFunctionType()) { 02486 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 02487 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 02488 02489 // C++ 8.3.5p4: 02490 // A cv-qualifier-seq shall only be part of the function type 02491 // for a nonstatic member function, the function type to which a pointer 02492 // to member refers, or the top-level function type of a function typedef 02493 // declaration. 02494 // 02495 // Core issue 547 also allows cv-qualifiers on function types that are 02496 // top-level template type arguments. 02497 bool FreeFunction; 02498 if (!D.getCXXScopeSpec().isSet()) { 02499 FreeFunction = ((D.getContext() != Declarator::MemberContext && 02500 D.getContext() != Declarator::LambdaExprContext) || 02501 D.getDeclSpec().isFriendSpecified()); 02502 } else { 02503 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); 02504 FreeFunction = (DC && !DC->isRecord()); 02505 } 02506 02507 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member 02508 // function that is not a constructor declares that function to be const. 02509 if (D.getDeclSpec().isConstexprSpecified() && !FreeFunction && 02510 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static && 02511 D.getName().getKind() != UnqualifiedId::IK_ConstructorName && 02512 D.getName().getKind() != UnqualifiedId::IK_ConstructorTemplateId && 02513 !(FnTy->getTypeQuals() & DeclSpec::TQ_const)) { 02514 // Rebuild function type adding a 'const' qualifier. 02515 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 02516 EPI.TypeQuals |= DeclSpec::TQ_const; 02517 T = Context.getFunctionType(FnTy->getResultType(), 02518 FnTy->arg_type_begin(), 02519 FnTy->getNumArgs(), EPI); 02520 } 02521 02522 // C++11 [dcl.fct]p6 (w/DR1417): 02523 // An attempt to specify a function type with a cv-qualifier-seq or a 02524 // ref-qualifier (including by typedef-name) is ill-formed unless it is: 02525 // - the function type for a non-static member function, 02526 // - the function type to which a pointer to member refers, 02527 // - the top-level function type of a function typedef declaration or 02528 // alias-declaration, 02529 // - the type-id in the default argument of a type-parameter, or 02530 // - the type-id of a template-argument for a type-parameter 02531 if (IsQualifiedFunction && 02532 !(!FreeFunction && 02533 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && 02534 !IsTypedefName && 02535 D.getContext() != Declarator::TemplateTypeArgContext) { 02536 SourceLocation Loc = D.getLocStart(); 02537 SourceRange RemovalRange; 02538 unsigned I; 02539 if (D.isFunctionDeclarator(I)) { 02540 SmallVector<SourceLocation, 4> RemovalLocs; 02541 const DeclaratorChunk &Chunk = D.getTypeObject(I); 02542 assert(Chunk.Kind == DeclaratorChunk::Function); 02543 if (Chunk.Fun.hasRefQualifier()) 02544 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); 02545 if (Chunk.Fun.TypeQuals & Qualifiers::Const) 02546 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc()); 02547 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile) 02548 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc()); 02549 // FIXME: We do not track the location of the __restrict qualifier. 02550 //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict) 02551 // RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc()); 02552 if (!RemovalLocs.empty()) { 02553 std::sort(RemovalLocs.begin(), RemovalLocs.end(), 02554 SourceManager::LocBeforeThanCompare(S.getSourceManager())); 02555 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); 02556 Loc = RemovalLocs.front(); 02557 } 02558 } 02559 02560 S.Diag(Loc, diag::err_invalid_qualified_function_type) 02561 << FreeFunction << D.isFunctionDeclarator() << T 02562 << getFunctionQualifiersAsString(FnTy) 02563 << FixItHint::CreateRemoval(RemovalRange); 02564 02565 // Strip the cv-qualifiers and ref-qualifiers from the type. 02566 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); 02567 EPI.TypeQuals = 0; 02568 EPI.RefQualifier = RQ_None; 02569 02570 T = Context.getFunctionType(FnTy->getResultType(), 02571 FnTy->arg_type_begin(), 02572 FnTy->getNumArgs(), EPI); 02573 } 02574 } 02575 02576 // Apply any undistributed attributes from the declarator. 02577 if (!T.isNull()) 02578 if (AttributeList *attrs = D.getAttributes()) 02579 processTypeAttrs(state, T, false, attrs); 02580 02581 // Diagnose any ignored type attributes. 02582 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T); 02583 02584 // C++0x [dcl.constexpr]p9: 02585 // A constexpr specifier used in an object declaration declares the object 02586 // as const. 02587 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) { 02588 T.addConst(); 02589 } 02590 02591 // If there was an ellipsis in the declarator, the declaration declares a 02592 // parameter pack whose type may be a pack expansion type. 02593 if (D.hasEllipsis() && !T.isNull()) { 02594 // C++0x [dcl.fct]p13: 02595 // A declarator-id or abstract-declarator containing an ellipsis shall 02596 // only be used in a parameter-declaration. Such a parameter-declaration 02597 // is a parameter pack (14.5.3). [...] 02598 switch (D.getContext()) { 02599 case Declarator::PrototypeContext: 02600 // C++0x [dcl.fct]p13: 02601 // [...] When it is part of a parameter-declaration-clause, the 02602 // parameter pack is a function parameter pack (14.5.3). The type T 02603 // of the declarator-id of the function parameter pack shall contain 02604 // a template parameter pack; each template parameter pack in T is 02605 // expanded by the function parameter pack. 02606 // 02607 // We represent function parameter packs as function parameters whose 02608 // type is a pack expansion. 02609 if (!T->containsUnexpandedParameterPack()) { 02610 S.Diag(D.getEllipsisLoc(), 02611 diag::err_function_parameter_pack_without_parameter_packs) 02612 << T << D.getSourceRange(); 02613 D.setEllipsisLoc(SourceLocation()); 02614 } else { 02615 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>()); 02616 } 02617 break; 02618 02619 case Declarator::TemplateParamContext: 02620 // C++0x [temp.param]p15: 02621 // If a template-parameter is a [...] is a parameter-declaration that 02622 // declares a parameter pack (8.3.5), then the template-parameter is a 02623 // template parameter pack (14.5.3). 02624 // 02625 // Note: core issue 778 clarifies that, if there are any unexpanded 02626 // parameter packs in the type of the non-type template parameter, then 02627 // it expands those parameter packs. 02628 if (T->containsUnexpandedParameterPack()) 02629 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>()); 02630 else 02631 S.Diag(D.getEllipsisLoc(), 02632 LangOpts.CPlusPlus0x 02633 ? diag::warn_cxx98_compat_variadic_templates 02634 : diag::ext_variadic_templates); 02635 break; 02636 02637 case Declarator::FileContext: 02638 case Declarator::KNRTypeListContext: 02639 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here? 02640 case Declarator::ObjCResultContext: // FIXME: special diagnostic here? 02641 case Declarator::TypeNameContext: 02642 case Declarator::CXXNewContext: 02643 case Declarator::AliasDeclContext: 02644 case Declarator::AliasTemplateContext: 02645 case Declarator::MemberContext: 02646 case Declarator::BlockContext: 02647 case Declarator::ForContext: 02648 case Declarator::ConditionContext: 02649 case Declarator::CXXCatchContext: 02650 case Declarator::ObjCCatchContext: 02651 case Declarator::BlockLiteralContext: 02652 case Declarator::LambdaExprContext: 02653 case Declarator::TrailingReturnContext: 02654 case Declarator::TemplateTypeArgContext: 02655 // FIXME: We may want to allow parameter packs in block-literal contexts 02656 // in the future. 02657 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter); 02658 D.setEllipsisLoc(SourceLocation()); 02659 break; 02660 } 02661 } 02662 02663 if (T.isNull()) 02664 return Context.getNullTypeSourceInfo(); 02665 else if (D.isInvalidType()) 02666 return Context.getTrivialTypeSourceInfo(T); 02667 02668 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo); 02669 } 02670 02671 /// GetTypeForDeclarator - Convert the type for the specified 02672 /// declarator to Type instances. 02673 /// 02674 /// The result of this call will never be null, but the associated 02675 /// type may be a null type if there's an unrecoverable error. 02676 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { 02677 // Determine the type of the declarator. Not all forms of declarator 02678 // have a type. 02679 02680 TypeProcessingState state(*this, D); 02681 02682 TypeSourceInfo *ReturnTypeInfo = 0; 02683 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 02684 if (T.isNull()) 02685 return Context.getNullTypeSourceInfo(); 02686 02687 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) 02688 inferARCWriteback(state, T); 02689 02690 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); 02691 } 02692 02693 static void transferARCOwnershipToDeclSpec(Sema &S, 02694 QualType &declSpecTy, 02695 Qualifiers::ObjCLifetime ownership) { 02696 if (declSpecTy->isObjCRetainableType() && 02697 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { 02698 Qualifiers qs; 02699 qs.addObjCLifetime(ownership); 02700 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); 02701 } 02702 } 02703 02704 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, 02705 Qualifiers::ObjCLifetime ownership, 02706 unsigned chunkIndex) { 02707 Sema &S = state.getSema(); 02708 Declarator &D = state.getDeclarator(); 02709 02710 // Look for an explicit lifetime attribute. 02711 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); 02712 for (const AttributeList *attr = chunk.getAttrs(); attr; 02713 attr = attr->getNext()) 02714 if (attr->getKind() == AttributeList::AT_objc_ownership) 02715 return; 02716 02717 const char *attrStr = 0; 02718 switch (ownership) { 02719 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 02720 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; 02721 case Qualifiers::OCL_Strong: attrStr = "strong"; break; 02722 case Qualifiers::OCL_Weak: attrStr = "weak"; break; 02723 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; 02724 } 02725 02726 // If there wasn't one, add one (with an invalid source location 02727 // so that we don't make an AttributedType for it). 02728 AttributeList *attr = D.getAttributePool() 02729 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(), 02730 /*scope*/ 0, SourceLocation(), 02731 &S.Context.Idents.get(attrStr), SourceLocation(), 02732 /*args*/ 0, 0, 02733 /*declspec*/ false, /*C++0x*/ false); 02734 spliceAttrIntoList(*attr, chunk.getAttrListRef()); 02735 02736 // TODO: mark whether we did this inference? 02737 } 02738 02739 /// \brief Used for transfering ownership in casts resulting in l-values. 02740 static void transferARCOwnership(TypeProcessingState &state, 02741 QualType &declSpecTy, 02742 Qualifiers::ObjCLifetime ownership) { 02743 Sema &S = state.getSema(); 02744 Declarator &D = state.getDeclarator(); 02745 02746 int inner = -1; 02747 bool hasIndirection = false; 02748 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 02749 DeclaratorChunk &chunk = D.getTypeObject(i); 02750 switch (chunk.Kind) { 02751 case DeclaratorChunk::Paren: 02752 // Ignore parens. 02753 break; 02754 02755 case DeclaratorChunk::Array: 02756 case DeclaratorChunk::Reference: 02757 case DeclaratorChunk::Pointer: 02758 if (inner != -1) 02759 hasIndirection = true; 02760 inner = i; 02761 break; 02762 02763 case DeclaratorChunk::BlockPointer: 02764 if (inner != -1) 02765 transferARCOwnershipToDeclaratorChunk(state, ownership, i); 02766 return; 02767 02768 case DeclaratorChunk::Function: 02769 case DeclaratorChunk::MemberPointer: 02770 return; 02771 } 02772 } 02773 02774 if (inner == -1) 02775 return; 02776 02777 DeclaratorChunk &chunk = D.getTypeObject(inner); 02778 if (chunk.Kind == DeclaratorChunk::Pointer) { 02779 if (declSpecTy->isObjCRetainableType()) 02780 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 02781 if (declSpecTy->isObjCObjectType() && hasIndirection) 02782 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); 02783 } else { 02784 assert(chunk.Kind == DeclaratorChunk::Array || 02785 chunk.Kind == DeclaratorChunk::Reference); 02786 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); 02787 } 02788 } 02789 02790 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { 02791 TypeProcessingState state(*this, D); 02792 02793 TypeSourceInfo *ReturnTypeInfo = 0; 02794 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); 02795 if (declSpecTy.isNull()) 02796 return Context.getNullTypeSourceInfo(); 02797 02798 if (getLangOpts().ObjCAutoRefCount) { 02799 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); 02800 if (ownership != Qualifiers::OCL_None) 02801 transferARCOwnership(state, declSpecTy, ownership); 02802 } 02803 02804 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); 02805 } 02806 02807 /// Map an AttributedType::Kind to an AttributeList::Kind. 02808 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) { 02809 switch (kind) { 02810 case AttributedType::attr_address_space: 02811 return AttributeList::AT_address_space; 02812 case AttributedType::attr_regparm: 02813 return AttributeList::AT_regparm; 02814 case AttributedType::attr_vector_size: 02815 return AttributeList::AT_vector_size; 02816 case AttributedType::attr_neon_vector_type: 02817 return AttributeList::AT_neon_vector_type; 02818 case AttributedType::attr_neon_polyvector_type: 02819 return AttributeList::AT_neon_polyvector_type; 02820 case AttributedType::attr_objc_gc: 02821 return AttributeList::AT_objc_gc; 02822 case AttributedType::attr_objc_ownership: 02823 return AttributeList::AT_objc_ownership; 02824 case AttributedType::attr_noreturn: 02825 return AttributeList::AT_noreturn; 02826 case AttributedType::attr_cdecl: 02827 return AttributeList::AT_cdecl; 02828 case AttributedType::attr_fastcall: 02829 return AttributeList::AT_fastcall; 02830 case AttributedType::attr_stdcall: 02831 return AttributeList::AT_stdcall; 02832 case AttributedType::attr_thiscall: 02833 return AttributeList::AT_thiscall; 02834 case AttributedType::attr_pascal: 02835 return AttributeList::AT_pascal; 02836 case AttributedType::attr_pcs: 02837 return AttributeList::AT_pcs; 02838 } 02839 llvm_unreachable("unexpected attribute kind!"); 02840 } 02841 02842 static void fillAttributedTypeLoc(AttributedTypeLoc TL, 02843 const AttributeList *attrs) { 02844 AttributedType::Kind kind = TL.getAttrKind(); 02845 02846 assert(attrs && "no type attributes in the expected location!"); 02847 AttributeList::Kind parsedKind = getAttrListKind(kind); 02848 while (attrs->getKind() != parsedKind) { 02849 attrs = attrs->getNext(); 02850 assert(attrs && "no matching attribute in expected location!"); 02851 } 02852 02853 TL.setAttrNameLoc(attrs->getLoc()); 02854 if (TL.hasAttrExprOperand()) 02855 TL.setAttrExprOperand(attrs->getArg(0)); 02856 else if (TL.hasAttrEnumOperand()) 02857 TL.setAttrEnumOperandLoc(attrs->getParameterLoc()); 02858 02859 // FIXME: preserve this information to here. 02860 if (TL.hasAttrOperand()) 02861 TL.setAttrOperandParensRange(SourceRange()); 02862 } 02863 02864 namespace { 02865 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 02866 ASTContext &Context; 02867 const DeclSpec &DS; 02868 02869 public: 02870 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS) 02871 : Context(Context), DS(DS) {} 02872 02873 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 02874 fillAttributedTypeLoc(TL, DS.getAttributes().getList()); 02875 Visit(TL.getModifiedLoc()); 02876 } 02877 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 02878 Visit(TL.getUnqualifiedLoc()); 02879 } 02880 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 02881 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 02882 } 02883 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 02884 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 02885 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires 02886 // addition field. What we have is good enough for dispay of location 02887 // of 'fixit' on interface name. 02888 TL.setNameEndLoc(DS.getLocEnd()); 02889 } 02890 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 02891 // Handle the base type, which might not have been written explicitly. 02892 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { 02893 TL.setHasBaseTypeAsWritten(false); 02894 TL.getBaseLoc().initialize(Context, SourceLocation()); 02895 } else { 02896 TL.setHasBaseTypeAsWritten(true); 02897 Visit(TL.getBaseLoc()); 02898 } 02899 02900 // Protocol qualifiers. 02901 if (DS.getProtocolQualifiers()) { 02902 assert(TL.getNumProtocols() > 0); 02903 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers()); 02904 TL.setLAngleLoc(DS.getProtocolLAngleLoc()); 02905 TL.setRAngleLoc(DS.getSourceRange().getEnd()); 02906 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i) 02907 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]); 02908 } else { 02909 assert(TL.getNumProtocols() == 0); 02910 TL.setLAngleLoc(SourceLocation()); 02911 TL.setRAngleLoc(SourceLocation()); 02912 } 02913 } 02914 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 02915 TL.setStarLoc(SourceLocation()); 02916 Visit(TL.getPointeeLoc()); 02917 } 02918 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 02919 TypeSourceInfo *TInfo = 0; 02920 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 02921 02922 // If we got no declarator info from previous Sema routines, 02923 // just fill with the typespec loc. 02924 if (!TInfo) { 02925 TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); 02926 return; 02927 } 02928 02929 TypeLoc OldTL = TInfo->getTypeLoc(); 02930 if (TInfo->getType()->getAs<ElaboratedType>()) { 02931 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL); 02932 TemplateSpecializationTypeLoc NamedTL = 02933 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc()); 02934 TL.copy(NamedTL); 02935 } 02936 else 02937 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL)); 02938 } 02939 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 02940 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 02941 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 02942 TL.setParensRange(DS.getTypeofParensRange()); 02943 } 02944 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 02945 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 02946 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 02947 TL.setParensRange(DS.getTypeofParensRange()); 02948 assert(DS.getRepAsType()); 02949 TypeSourceInfo *TInfo = 0; 02950 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 02951 TL.setUnderlyingTInfo(TInfo); 02952 } 02953 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 02954 // FIXME: This holds only because we only have one unary transform. 02955 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType); 02956 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 02957 TL.setParensRange(DS.getTypeofParensRange()); 02958 assert(DS.getRepAsType()); 02959 TypeSourceInfo *TInfo = 0; 02960 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 02961 TL.setUnderlyingTInfo(TInfo); 02962 } 02963 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 02964 // By default, use the source location of the type specifier. 02965 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 02966 if (TL.needsExtraLocalData()) { 02967 // Set info for the written builtin specifiers. 02968 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 02969 // Try to have a meaningful source location. 02970 if (TL.getWrittenSignSpec() != TSS_unspecified) 02971 // Sign spec loc overrides the others (e.g., 'unsigned long'). 02972 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 02973 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 02974 // Width spec loc overrides type spec loc (e.g., 'short int'). 02975 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 02976 } 02977 } 02978 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 02979 ElaboratedTypeKeyword Keyword 02980 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 02981 if (DS.getTypeSpecType() == TST_typename) { 02982 TypeSourceInfo *TInfo = 0; 02983 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 02984 if (TInfo) { 02985 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc())); 02986 return; 02987 } 02988 } 02989 TL.setElaboratedKeywordLoc(Keyword != ETK_None 02990 ? DS.getTypeSpecTypeLoc() 02991 : SourceLocation()); 02992 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 02993 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 02994 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 02995 } 02996 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 02997 assert(DS.getTypeSpecType() == TST_typename); 02998 TypeSourceInfo *TInfo = 0; 02999 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 03000 assert(TInfo); 03001 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc())); 03002 } 03003 void VisitDependentTemplateSpecializationTypeLoc( 03004 DependentTemplateSpecializationTypeLoc TL) { 03005 assert(DS.getTypeSpecType() == TST_typename); 03006 TypeSourceInfo *TInfo = 0; 03007 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 03008 assert(TInfo); 03009 TL.copy(cast<DependentTemplateSpecializationTypeLoc>( 03010 TInfo->getTypeLoc())); 03011 } 03012 void VisitTagTypeLoc(TagTypeLoc TL) { 03013 TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); 03014 } 03015 void VisitAtomicTypeLoc(AtomicTypeLoc TL) { 03016 TL.setKWLoc(DS.getTypeSpecTypeLoc()); 03017 TL.setParensRange(DS.getTypeofParensRange()); 03018 03019 TypeSourceInfo *TInfo = 0; 03020 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); 03021 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); 03022 } 03023 03024 void VisitTypeLoc(TypeLoc TL) { 03025 // FIXME: add other typespec types and change this to an assert. 03026 TL.initialize(Context, DS.getTypeSpecTypeLoc()); 03027 } 03028 }; 03029 03030 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 03031 ASTContext &Context; 03032 const DeclaratorChunk &Chunk; 03033 03034 public: 03035 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk) 03036 : Context(Context), Chunk(Chunk) {} 03037 03038 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 03039 llvm_unreachable("qualified type locs not expected here!"); 03040 } 03041 03042 void VisitAttributedTypeLoc(AttributedTypeLoc TL) { 03043 fillAttributedTypeLoc(TL, Chunk.getAttrs()); 03044 } 03045 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 03046 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 03047 TL.setCaretLoc(Chunk.Loc); 03048 } 03049 void VisitPointerTypeLoc(PointerTypeLoc TL) { 03050 assert(Chunk.Kind == DeclaratorChunk::Pointer); 03051 TL.setStarLoc(Chunk.Loc); 03052 } 03053 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 03054 assert(Chunk.Kind == DeclaratorChunk::Pointer); 03055 TL.setStarLoc(Chunk.Loc); 03056 } 03057 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 03058 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 03059 const CXXScopeSpec& SS = Chunk.Mem.Scope(); 03060 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); 03061 03062 const Type* ClsTy = TL.getClass(); 03063 QualType ClsQT = QualType(ClsTy, 0); 03064 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); 03065 // Now copy source location info into the type loc component. 03066 TypeLoc ClsTL = ClsTInfo->getTypeLoc(); 03067 switch (NNSLoc.getNestedNameSpecifier()->getKind()) { 03068 case NestedNameSpecifier::Identifier: 03069 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc"); 03070 { 03071 DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL); 03072 DNTLoc.setElaboratedKeywordLoc(SourceLocation()); 03073 DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); 03074 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); 03075 } 03076 break; 03077 03078 case NestedNameSpecifier::TypeSpec: 03079 case NestedNameSpecifier::TypeSpecWithTemplate: 03080 if (isa<ElaboratedType>(ClsTy)) { 03081 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL); 03082 ETLoc.setElaboratedKeywordLoc(SourceLocation()); 03083 ETLoc.setQualifierLoc(NNSLoc.getPrefix()); 03084 TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); 03085 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); 03086 } else { 03087 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); 03088 } 03089 break; 03090 03091 case NestedNameSpecifier::Namespace: 03092 case NestedNameSpecifier::NamespaceAlias: 03093 case NestedNameSpecifier::Global: 03094 llvm_unreachable("Nested-name-specifier must name a type"); 03095 } 03096 03097 // Finally fill in MemberPointerLocInfo fields. 03098 TL.setStarLoc(Chunk.Loc); 03099 TL.setClassTInfo(ClsTInfo); 03100 } 03101 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 03102 assert(Chunk.Kind == DeclaratorChunk::Reference); 03103 // 'Amp' is misleading: this might have been originally 03104 /// spelled with AmpAmp. 03105 TL.setAmpLoc(Chunk.Loc); 03106 } 03107 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 03108 assert(Chunk.Kind == DeclaratorChunk::Reference); 03109 assert(!Chunk.Ref.LValueRef); 03110 TL.setAmpAmpLoc(Chunk.Loc); 03111 } 03112 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 03113 assert(Chunk.Kind == DeclaratorChunk::Array); 03114 TL.setLBracketLoc(Chunk.Loc); 03115 TL.setRBracketLoc(Chunk.EndLoc); 03116 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 03117 } 03118 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 03119 assert(Chunk.Kind == DeclaratorChunk::Function); 03120 TL.setLocalRangeBegin(Chunk.Loc); 03121 TL.setLocalRangeEnd(Chunk.EndLoc); 03122 TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType); 03123 03124 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 03125 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) { 03126 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 03127 TL.setArg(tpi++, Param); 03128 } 03129 // FIXME: exception specs 03130 } 03131 void VisitParenTypeLoc(ParenTypeLoc TL) { 03132 assert(Chunk.Kind == DeclaratorChunk::Paren); 03133 TL.setLParenLoc(Chunk.Loc); 03134 TL.setRParenLoc(Chunk.EndLoc); 03135 } 03136 03137 void VisitTypeLoc(TypeLoc TL) { 03138 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 03139 } 03140 }; 03141 } 03142 03143 /// \brief Create and instantiate a TypeSourceInfo with type source information. 03144 /// 03145 /// \param T QualType referring to the type as written in source code. 03146 /// 03147 /// \param ReturnTypeInfo For declarators whose return type does not show 03148 /// up in the normal place in the declaration specifiers (such as a C++ 03149 /// conversion function), this pointer will refer to a type source information 03150 /// for that return type. 03151 TypeSourceInfo * 03152 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 03153 TypeSourceInfo *ReturnTypeInfo) { 03154 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 03155 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 03156 03157 // Handle parameter packs whose type is a pack expansion. 03158 if (isa<PackExpansionType>(T)) { 03159 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc()); 03160 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 03161 } 03162 03163 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 03164 while (isa<AttributedTypeLoc>(CurrTL)) { 03165 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL); 03166 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs()); 03167 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); 03168 } 03169 03170 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL); 03171 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 03172 } 03173 03174 // If we have different source information for the return type, use 03175 // that. This really only applies to C++ conversion functions. 03176 if (ReturnTypeInfo) { 03177 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 03178 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 03179 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 03180 } else { 03181 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL); 03182 } 03183 03184 return TInfo; 03185 } 03186 03187 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 03188 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { 03189 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 03190 // and Sema during declaration parsing. Try deallocating/caching them when 03191 // it's appropriate, instead of allocating them and keeping them around. 03192 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 03193 TypeAlignment); 03194 new (LocT) LocInfoType(T, TInfo); 03195 assert(LocT->getTypeClass() != T->getTypeClass() && 03196 "LocInfoType's TypeClass conflicts with an existing Type class"); 03197 return ParsedType::make(QualType(LocT, 0)); 03198 } 03199 03200 void LocInfoType::getAsStringInternal(std::string &Str, 03201 const PrintingPolicy &Policy) const { 03202 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" 03203 " was used directly instead of getting the QualType through" 03204 " GetTypeFromParser"); 03205 } 03206 03207 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 03208 // C99 6.7.6: Type names have no identifier. This is already validated by 03209 // the parser. 03210 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 03211 03212 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 03213 QualType T = TInfo->getType(); 03214 if (D.isInvalidType()) 03215 return true; 03216 03217 // Make sure there are no unused decl attributes on the declarator. 03218 // We don't want to do this for ObjC parameters because we're going 03219 // to apply them to the actual parameter declaration. 03220 if (D.getContext() != Declarator::ObjCParameterContext) 03221 checkUnusedDeclAttributes(D); 03222 03223 if (getLangOpts().CPlusPlus) { 03224 // Check that there are no default arguments (C++ only). 03225 CheckExtraCXXDefaultArguments(D); 03226 } 03227 03228 return CreateParsedType(T, TInfo); 03229 } 03230 03231 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { 03232 QualType T = Context.getObjCInstanceType(); 03233 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 03234 return CreateParsedType(T, TInfo); 03235 } 03236 03237 03238 //===----------------------------------------------------------------------===// 03239 // Type Attribute Processing 03240 //===----------------------------------------------------------------------===// 03241 03242 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 03243 /// specified type. The attribute contains 1 argument, the id of the address 03244 /// space for the type. 03245 static void HandleAddressSpaceTypeAttribute(QualType &Type, 03246 const AttributeList &Attr, Sema &S){ 03247 03248 // If this type is already address space qualified, reject it. 03249 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by 03250 // qualifiers for two or more different address spaces." 03251 if (Type.getAddressSpace()) { 03252 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 03253 Attr.setInvalid(); 03254 return; 03255 } 03256 03257 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be 03258 // qualified by an address-space qualifier." 03259 if (Type->isFunctionType()) { 03260 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); 03261 Attr.setInvalid(); 03262 return; 03263 } 03264 03265 // Check the attribute arguments. 03266 if (Attr.getNumArgs() != 1) { 03267 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 03268 Attr.setInvalid(); 03269 return; 03270 } 03271 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 03272 llvm::APSInt addrSpace(32); 03273 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 03274 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 03275 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) 03276 << ASArgExpr->getSourceRange(); 03277 Attr.setInvalid(); 03278 return; 03279 } 03280 03281 // Bounds checking. 03282 if (addrSpace.isSigned()) { 03283 if (addrSpace.isNegative()) { 03284 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 03285 << ASArgExpr->getSourceRange(); 03286 Attr.setInvalid(); 03287 return; 03288 } 03289 addrSpace.setIsSigned(false); 03290 } 03291 llvm::APSInt max(addrSpace.getBitWidth()); 03292 max = Qualifiers::MaxAddressSpace; 03293 if (addrSpace > max) { 03294 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 03295 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange(); 03296 Attr.setInvalid(); 03297 return; 03298 } 03299 03300 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 03301 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 03302 } 03303 03304 /// Does this type have a "direct" ownership qualifier? That is, 03305 /// is it written like "__strong id", as opposed to something like 03306 /// "typeof(foo)", where that happens to be strong? 03307 static bool hasDirectOwnershipQualifier(QualType type) { 03308 // Fast path: no qualifier at all. 03309 assert(type.getQualifiers().hasObjCLifetime()); 03310 03311 while (true) { 03312 // __strong id 03313 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) { 03314 if (attr->getAttrKind() == AttributedType::attr_objc_ownership) 03315 return true; 03316 03317 type = attr->getModifiedType(); 03318 03319 // X *__strong (...) 03320 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) { 03321 type = paren->getInnerType(); 03322 03323 // That's it for things we want to complain about. In particular, 03324 // we do not want to look through typedefs, typeof(expr), 03325 // typeof(type), or any other way that the type is somehow 03326 // abstracted. 03327 } else { 03328 03329 return false; 03330 } 03331 } 03332 } 03333 03334 /// handleObjCOwnershipTypeAttr - Process an objc_ownership 03335 /// attribute on the specified type. 03336 /// 03337 /// Returns 'true' if the attribute was handled. 03338 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, 03339 AttributeList &attr, 03340 QualType &type) { 03341 bool NonObjCPointer = false; 03342 03343 if (!type->isDependentType()) { 03344 if (const PointerType *ptr = type->getAs<PointerType>()) { 03345 QualType pointee = ptr->getPointeeType(); 03346 if (pointee->isObjCRetainableType() || pointee->isPointerType()) 03347 return false; 03348 // It is important not to lose the source info that there was an attribute 03349 // applied to non-objc pointer. We will create an attributed type but 03350 // its type will be the same as the original type. 03351 NonObjCPointer = true; 03352 } else if (!type->isObjCRetainableType()) { 03353 return false; 03354 } 03355 } 03356 03357 Sema &S = state.getSema(); 03358 SourceLocation AttrLoc = attr.getLoc(); 03359 if (AttrLoc.isMacroID()) 03360 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first; 03361 03362 if (!attr.getParameterName()) { 03363 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string) 03364 << "objc_ownership" << 1; 03365 attr.setInvalid(); 03366 return true; 03367 } 03368 03369 // Consume lifetime attributes without further comment outside of 03370 // ARC mode. 03371 if (!S.getLangOpts().ObjCAutoRefCount) 03372 return true; 03373 03374 Qualifiers::ObjCLifetime lifetime; 03375 if (attr.getParameterName()->isStr("none")) 03376 lifetime = Qualifiers::OCL_ExplicitNone; 03377 else if (attr.getParameterName()->isStr("strong")) 03378 lifetime = Qualifiers::OCL_Strong; 03379 else if (attr.getParameterName()->isStr("weak")) 03380 lifetime = Qualifiers::OCL_Weak; 03381 else if (attr.getParameterName()->isStr("autoreleasing")) 03382 lifetime = Qualifiers::OCL_Autoreleasing; 03383 else { 03384 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) 03385 << "objc_ownership" << attr.getParameterName(); 03386 attr.setInvalid(); 03387 return true; 03388 } 03389 03390 SplitQualType underlyingType = type.split(); 03391 03392 // Check for redundant/conflicting ownership qualifiers. 03393 if (Qualifiers::ObjCLifetime previousLifetime 03394 = type.getQualifiers().getObjCLifetime()) { 03395 // If it's written directly, that's an error. 03396 if (hasDirectOwnershipQualifier(type)) { 03397 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) 03398 << type; 03399 return true; 03400 } 03401 03402 // Otherwise, if the qualifiers actually conflict, pull sugar off 03403 // until we reach a type that is directly qualified. 03404 if (previousLifetime != lifetime) { 03405 // This should always terminate: the canonical type is 03406 // qualified, so some bit of sugar must be hiding it. 03407 while (!underlyingType.Quals.hasObjCLifetime()) { 03408 underlyingType = underlyingType.getSingleStepDesugaredType(); 03409 } 03410 underlyingType.Quals.removeObjCLifetime(); 03411 } 03412 } 03413 03414 underlyingType.Quals.addObjCLifetime(lifetime); 03415 03416 if (NonObjCPointer) { 03417 StringRef name = attr.getName()->getName(); 03418 switch (lifetime) { 03419 case Qualifiers::OCL_None: 03420 case Qualifiers::OCL_ExplicitNone: 03421 break; 03422 case Qualifiers::OCL_Strong: name = "__strong"; break; 03423 case Qualifiers::OCL_Weak: name = "__weak"; break; 03424 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; 03425 } 03426 S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type) 03427 << name << type; 03428 } 03429 03430 QualType origType = type; 03431 if (!NonObjCPointer) 03432 type = S.Context.getQualifiedType(underlyingType); 03433 03434 // If we have a valid source location for the attribute, use an 03435 // AttributedType instead. 03436 if (AttrLoc.isValid()) 03437 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership, 03438 origType, type); 03439 03440 // Forbid __weak if the runtime doesn't support it. 03441 if (lifetime == Qualifiers::OCL_Weak && 03442 !S.getLangOpts().ObjCRuntimeHasWeak && !NonObjCPointer) { 03443 03444 // Actually, delay this until we know what we're parsing. 03445 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 03446 S.DelayedDiagnostics.add( 03447 sema::DelayedDiagnostic::makeForbiddenType( 03448 S.getSourceManager().getExpansionLoc(AttrLoc), 03449 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0)); 03450 } else { 03451 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime); 03452 } 03453 03454 attr.setInvalid(); 03455 return true; 03456 } 03457 03458 // Forbid __weak for class objects marked as 03459 // objc_arc_weak_reference_unavailable 03460 if (lifetime == Qualifiers::OCL_Weak) { 03461 QualType T = type; 03462 while (const PointerType *ptr = T->getAs<PointerType>()) 03463 T = ptr->getPointeeType(); 03464 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) { 03465 ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl(); 03466 if (Class->isArcWeakrefUnavailable()) { 03467 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); 03468 S.Diag(ObjT->getInterfaceDecl()->getLocation(), 03469 diag::note_class_declared); 03470 } 03471 } 03472 } 03473 03474 return true; 03475 } 03476 03477 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type 03478 /// attribute on the specified type. Returns true to indicate that 03479 /// the attribute was handled, false to indicate that the type does 03480 /// not permit the attribute. 03481 static bool handleObjCGCTypeAttr(TypeProcessingState &state, 03482 AttributeList &attr, 03483 QualType &type) { 03484 Sema &S = state.getSema(); 03485 03486 // Delay if this isn't some kind of pointer. 03487 if (!type->isPointerType() && 03488 !type->isObjCObjectPointerType() && 03489 !type->isBlockPointerType()) 03490 return false; 03491 03492 if (type.getObjCGCAttr() != Qualifiers::GCNone) { 03493 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); 03494 attr.setInvalid(); 03495 return true; 03496 } 03497 03498 // Check the attribute arguments. 03499 if (!attr.getParameterName()) { 03500 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string) 03501 << "objc_gc" << 1; 03502 attr.setInvalid(); 03503 return true; 03504 } 03505 Qualifiers::GC GCAttr; 03506 if (attr.getNumArgs() != 0) { 03507 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 03508 attr.setInvalid(); 03509 return true; 03510 } 03511 if (attr.getParameterName()->isStr("weak")) 03512 GCAttr = Qualifiers::Weak; 03513 else if (attr.getParameterName()->isStr("strong")) 03514 GCAttr = Qualifiers::Strong; 03515 else { 03516 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) 03517 << "objc_gc" << attr.getParameterName(); 03518 attr.setInvalid(); 03519 return true; 03520 } 03521 03522 QualType origType = type; 03523 type = S.Context.getObjCGCQualType(origType, GCAttr); 03524 03525 // Make an attributed type to preserve the source information. 03526 if (attr.getLoc().isValid()) 03527 type = S.Context.getAttributedType(AttributedType::attr_objc_gc, 03528 origType, type); 03529 03530 return true; 03531 } 03532 03533 namespace { 03534 /// A helper class to unwrap a type down to a function for the 03535 /// purposes of applying attributes there. 03536 /// 03537 /// Use: 03538 /// FunctionTypeUnwrapper unwrapped(SemaRef, T); 03539 /// if (unwrapped.isFunctionType()) { 03540 /// const FunctionType *fn = unwrapped.get(); 03541 /// // change fn somehow 03542 /// T = unwrapped.wrap(fn); 03543 /// } 03544 struct FunctionTypeUnwrapper { 03545 enum WrapKind { 03546 Desugar, 03547 Parens, 03548 Pointer, 03549 BlockPointer, 03550 Reference, 03551 MemberPointer 03552 }; 03553 03554 QualType Original; 03555 const FunctionType *Fn; 03556 SmallVector<unsigned char /*WrapKind*/, 8> Stack; 03557 03558 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { 03559 while (true) { 03560 const Type *Ty = T.getTypePtr(); 03561 if (isa<FunctionType>(Ty)) { 03562 Fn = cast<FunctionType>(Ty); 03563 return; 03564 } else if (isa<ParenType>(Ty)) { 03565 T = cast<ParenType>(Ty)->getInnerType(); 03566 Stack.push_back(Parens); 03567 } else if (isa<PointerType>(Ty)) { 03568 T = cast<PointerType>(Ty)->getPointeeType(); 03569 Stack.push_back(Pointer); 03570 } else if (isa<BlockPointerType>(Ty)) { 03571 T = cast<BlockPointerType>(Ty)->getPointeeType(); 03572 Stack.push_back(BlockPointer); 03573 } else if (isa<MemberPointerType>(Ty)) { 03574 T = cast<MemberPointerType>(Ty)->getPointeeType(); 03575 Stack.push_back(MemberPointer); 03576 } else if (isa<ReferenceType>(Ty)) { 03577 T = cast<ReferenceType>(Ty)->getPointeeType(); 03578 Stack.push_back(Reference); 03579 } else { 03580 const Type *DTy = Ty->getUnqualifiedDesugaredType(); 03581 if (Ty == DTy) { 03582 Fn = 0; 03583 return; 03584 } 03585 03586 T = QualType(DTy, 0); 03587 Stack.push_back(Desugar); 03588 } 03589 } 03590 } 03591 03592 bool isFunctionType() const { return (Fn != 0); } 03593 const FunctionType *get() const { return Fn; } 03594 03595 QualType wrap(Sema &S, const FunctionType *New) { 03596 // If T wasn't modified from the unwrapped type, do nothing. 03597 if (New == get()) return Original; 03598 03599 Fn = New; 03600 return wrap(S.Context, Original, 0); 03601 } 03602 03603 private: 03604 QualType wrap(ASTContext &C, QualType Old, unsigned I) { 03605 if (I == Stack.size()) 03606 return C.getQualifiedType(Fn, Old.getQualifiers()); 03607 03608 // Build up the inner type, applying the qualifiers from the old 03609 // type to the new type. 03610 SplitQualType SplitOld = Old.split(); 03611 03612 // As a special case, tail-recurse if there are no qualifiers. 03613 if (SplitOld.Quals.empty()) 03614 return wrap(C, SplitOld.Ty, I); 03615 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); 03616 } 03617 03618 QualType wrap(ASTContext &C, const Type *Old, unsigned I) { 03619 if (I == Stack.size()) return QualType(Fn, 0); 03620 03621 switch (static_cast<WrapKind>(Stack[I++])) { 03622 case Desugar: 03623 // This is the point at which we potentially lose source 03624 // information. 03625 return wrap(C, Old->getUnqualifiedDesugaredType(), I); 03626 03627 case Parens: { 03628 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); 03629 return C.getParenType(New); 03630 } 03631 03632 case Pointer: { 03633 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); 03634 return C.getPointerType(New); 03635 } 03636 03637 case BlockPointer: { 03638 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); 03639 return C.getBlockPointerType(New); 03640 } 03641 03642 case MemberPointer: { 03643 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); 03644 QualType New = wrap(C, OldMPT->getPointeeType(), I); 03645 return C.getMemberPointerType(New, OldMPT->getClass()); 03646 } 03647 03648 case Reference: { 03649 const ReferenceType *OldRef = cast<ReferenceType>(Old); 03650 QualType New = wrap(C, OldRef->getPointeeType(), I); 03651 if (isa<LValueReferenceType>(OldRef)) 03652 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); 03653 else 03654 return C.getRValueReferenceType(New); 03655 } 03656 } 03657 03658 llvm_unreachable("unknown wrapping kind"); 03659 } 03660 }; 03661 } 03662 03663 /// Process an individual function attribute. Returns true to 03664 /// indicate that the attribute was handled, false if it wasn't. 03665 static bool handleFunctionTypeAttr(TypeProcessingState &state, 03666 AttributeList &attr, 03667 QualType &type) { 03668 Sema &S = state.getSema(); 03669 03670 FunctionTypeUnwrapper unwrapped(S, type); 03671 03672 if (attr.getKind() == AttributeList::AT_noreturn) { 03673 if (S.CheckNoReturnAttr(attr)) 03674 return true; 03675 03676 // Delay if this is not a function type. 03677 if (!unwrapped.isFunctionType()) 03678 return false; 03679 03680 // Otherwise we can process right away. 03681 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); 03682 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 03683 return true; 03684 } 03685 03686 // ns_returns_retained is not always a type attribute, but if we got 03687 // here, we're treating it as one right now. 03688 if (attr.getKind() == AttributeList::AT_ns_returns_retained) { 03689 assert(S.getLangOpts().ObjCAutoRefCount && 03690 "ns_returns_retained treated as type attribute in non-ARC"); 03691 if (attr.getNumArgs()) return true; 03692 03693 // Delay if this is not a function type. 03694 if (!unwrapped.isFunctionType()) 03695 return false; 03696 03697 FunctionType::ExtInfo EI 03698 = unwrapped.get()->getExtInfo().withProducesResult(true); 03699 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 03700 return true; 03701 } 03702 03703 if (attr.getKind() == AttributeList::AT_regparm) { 03704 unsigned value; 03705 if (S.CheckRegparmAttr(attr, value)) 03706 return true; 03707 03708 // Delay if this is not a function type. 03709 if (!unwrapped.isFunctionType()) 03710 return false; 03711 03712 // Diagnose regparm with fastcall. 03713 const FunctionType *fn = unwrapped.get(); 03714 CallingConv CC = fn->getCallConv(); 03715 if (CC == CC_X86FastCall) { 03716 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 03717 << FunctionType::getNameForCallConv(CC) 03718 << "regparm"; 03719 attr.setInvalid(); 03720 return true; 03721 } 03722 03723 FunctionType::ExtInfo EI = 03724 unwrapped.get()->getExtInfo().withRegParm(value); 03725 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 03726 return true; 03727 } 03728 03729 // Otherwise, a calling convention. 03730 CallingConv CC; 03731 if (S.CheckCallingConvAttr(attr, CC)) 03732 return true; 03733 03734 // Delay if the type didn't work out to a function. 03735 if (!unwrapped.isFunctionType()) return false; 03736 03737 const FunctionType *fn = unwrapped.get(); 03738 CallingConv CCOld = fn->getCallConv(); 03739 if (S.Context.getCanonicalCallConv(CC) == 03740 S.Context.getCanonicalCallConv(CCOld)) { 03741 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC); 03742 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 03743 return true; 03744 } 03745 03746 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) { 03747 // Should we diagnose reapplications of the same convention? 03748 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 03749 << FunctionType::getNameForCallConv(CC) 03750 << FunctionType::getNameForCallConv(CCOld); 03751 attr.setInvalid(); 03752 return true; 03753 } 03754 03755 // Diagnose the use of X86 fastcall on varargs or unprototyped functions. 03756 if (CC == CC_X86FastCall) { 03757 if (isa<FunctionNoProtoType>(fn)) { 03758 S.Diag(attr.getLoc(), diag::err_cconv_knr) 03759 << FunctionType::getNameForCallConv(CC); 03760 attr.setInvalid(); 03761 return true; 03762 } 03763 03764 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn); 03765 if (FnP->isVariadic()) { 03766 S.Diag(attr.getLoc(), diag::err_cconv_varargs) 03767 << FunctionType::getNameForCallConv(CC); 03768 attr.setInvalid(); 03769 return true; 03770 } 03771 03772 // Also diagnose fastcall with regparm. 03773 if (fn->getHasRegParm()) { 03774 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) 03775 << "regparm" 03776 << FunctionType::getNameForCallConv(CC); 03777 attr.setInvalid(); 03778 return true; 03779 } 03780 } 03781 03782 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC); 03783 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); 03784 return true; 03785 } 03786 03787 /// Handle OpenCL image access qualifiers: read_only, write_only, read_write 03788 static void HandleOpenCLImageAccessAttribute(QualType& CurType, 03789 const AttributeList &Attr, 03790 Sema &S) { 03791 // Check the attribute arguments. 03792 if (Attr.getNumArgs() != 1) { 03793 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 03794 Attr.setInvalid(); 03795 return; 03796 } 03797 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 03798 llvm::APSInt arg(32); 03799 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 03800 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) { 03801 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 03802 << "opencl_image_access" << sizeExpr->getSourceRange(); 03803 Attr.setInvalid(); 03804 return; 03805 } 03806 unsigned iarg = static_cast<unsigned>(arg.getZExtValue()); 03807 switch (iarg) { 03808 case CLIA_read_only: 03809 case CLIA_write_only: 03810 case CLIA_read_write: 03811 // Implemented in a separate patch 03812 break; 03813 default: 03814 // Implemented in a separate patch 03815 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 03816 << sizeExpr->getSourceRange(); 03817 Attr.setInvalid(); 03818 break; 03819 } 03820 } 03821 03822 /// HandleVectorSizeAttribute - this attribute is only applicable to integral 03823 /// and float scalars, although arrays, pointers, and function return values are 03824 /// allowed in conjunction with this construct. Aggregates with this attribute 03825 /// are invalid, even if they are of the same size as a corresponding scalar. 03826 /// The raw attribute should contain precisely 1 argument, the vector size for 03827 /// the variable, measured in bytes. If curType and rawAttr are well formed, 03828 /// this routine will return a new vector type. 03829 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, 03830 Sema &S) { 03831 // Check the attribute arguments. 03832 if (Attr.getNumArgs() != 1) { 03833 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 03834 Attr.setInvalid(); 03835 return; 03836 } 03837 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 03838 llvm::APSInt vecSize(32); 03839 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 03840 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 03841 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 03842 << "vector_size" << sizeExpr->getSourceRange(); 03843 Attr.setInvalid(); 03844 return; 03845 } 03846 // the base type must be integer or float, and can't already be a vector. 03847 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) { 03848 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 03849 Attr.setInvalid(); 03850 return; 03851 } 03852 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 03853 // vecSize is specified in bytes - convert to bits. 03854 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 03855 03856 // the vector size needs to be an integral multiple of the type size. 03857 if (vectorSize % typeSize) { 03858 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 03859 << sizeExpr->getSourceRange(); 03860 Attr.setInvalid(); 03861 return; 03862 } 03863 if (vectorSize == 0) { 03864 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 03865 << sizeExpr->getSourceRange(); 03866 Attr.setInvalid(); 03867 return; 03868 } 03869 03870 // Success! Instantiate the vector type, the number of elements is > 0, and 03871 // not required to be a power of 2, unlike GCC. 03872 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, 03873 VectorType::GenericVector); 03874 } 03875 03876 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on 03877 /// a type. 03878 static void HandleExtVectorTypeAttr(QualType &CurType, 03879 const AttributeList &Attr, 03880 Sema &S) { 03881 Expr *sizeExpr; 03882 03883 // Special case where the argument is a template id. 03884 if (Attr.getParameterName()) { 03885 CXXScopeSpec SS; 03886 SourceLocation TemplateKWLoc; 03887 UnqualifiedId id; 03888 id.setIdentifier(Attr.getParameterName(), Attr.getLoc()); 03889 03890 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc, 03891 id, false, false); 03892 if (Size.isInvalid()) 03893 return; 03894 03895 sizeExpr = Size.get(); 03896 } else { 03897 // check the attribute arguments. 03898 if (Attr.getNumArgs() != 1) { 03899 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 03900 return; 03901 } 03902 sizeExpr = Attr.getArg(0); 03903 } 03904 03905 // Create the vector type. 03906 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc()); 03907 if (!T.isNull()) 03908 CurType = T; 03909 } 03910 03911 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and 03912 /// "neon_polyvector_type" attributes are used to create vector types that 03913 /// are mangled according to ARM's ABI. Otherwise, these types are identical 03914 /// to those created with the "vector_size" attribute. Unlike "vector_size" 03915 /// the argument to these Neon attributes is the number of vector elements, 03916 /// not the vector size in bytes. The vector width and element type must 03917 /// match one of the standard Neon vector types. 03918 static void HandleNeonVectorTypeAttr(QualType& CurType, 03919 const AttributeList &Attr, Sema &S, 03920 VectorType::VectorKind VecKind, 03921 const char *AttrName) { 03922 // Check the attribute arguments. 03923 if (Attr.getNumArgs() != 1) { 03924 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 03925 Attr.setInvalid(); 03926 return; 03927 } 03928 // The number of elements must be an ICE. 03929 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0)); 03930 llvm::APSInt numEltsInt(32); 03931 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() || 03932 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) { 03933 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 03934 << AttrName << numEltsExpr->getSourceRange(); 03935 Attr.setInvalid(); 03936 return; 03937 } 03938 // Only certain element types are supported for Neon vectors. 03939 const BuiltinType* BTy = CurType->getAs<BuiltinType>(); 03940 if (!BTy || 03941 (VecKind == VectorType::NeonPolyVector && 03942 BTy->getKind() != BuiltinType::SChar && 03943 BTy->getKind() != BuiltinType::Short) || 03944 (BTy->getKind() != BuiltinType::SChar && 03945 BTy->getKind() != BuiltinType::UChar && 03946 BTy->getKind() != BuiltinType::Short && 03947 BTy->getKind() != BuiltinType::UShort && 03948 BTy->getKind() != BuiltinType::Int && 03949 BTy->getKind() != BuiltinType::UInt && 03950 BTy->getKind() != BuiltinType::LongLong && 03951 BTy->getKind() != BuiltinType::ULongLong && 03952 BTy->getKind() != BuiltinType::Float)) { 03953 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType; 03954 Attr.setInvalid(); 03955 return; 03956 } 03957 // The total size of the vector must be 64 or 128 bits. 03958 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 03959 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); 03960 unsigned vecSize = typeSize * numElts; 03961 if (vecSize != 64 && vecSize != 128) { 03962 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; 03963 Attr.setInvalid(); 03964 return; 03965 } 03966 03967 CurType = S.Context.getVectorType(CurType, numElts, VecKind); 03968 } 03969 03970 static void processTypeAttrs(TypeProcessingState &state, QualType &type, 03971 bool isDeclSpec, AttributeList *attrs) { 03972 // Scan through and apply attributes to this type where it makes sense. Some 03973 // attributes (such as __address_space__, __vector_size__, etc) apply to the 03974 // type, but others can be present in the type specifiers even though they 03975 // apply to the decl. Here we apply type attributes and ignore the rest. 03976 03977 AttributeList *next; 03978 do { 03979 AttributeList &attr = *attrs; 03980 next = attr.getNext(); 03981 03982 // Skip attributes that were marked to be invalid. 03983 if (attr.isInvalid()) 03984 continue; 03985 03986 // If this is an attribute we can handle, do so now, 03987 // otherwise, add it to the FnAttrs list for rechaining. 03988 switch (attr.getKind()) { 03989 default: break; 03990 03991 case AttributeList::AT_may_alias: 03992 // FIXME: This attribute needs to actually be handled, but if we ignore 03993 // it it breaks large amounts of Linux software. 03994 attr.setUsedAsTypeAttr(); 03995 break; 03996 case AttributeList::AT_address_space: 03997 HandleAddressSpaceTypeAttribute(type, attr, state.getSema()); 03998 attr.setUsedAsTypeAttr(); 03999 break; 04000 OBJC_POINTER_TYPE_ATTRS_CASELIST: 04001 if (!handleObjCPointerTypeAttr(state, attr, type)) 04002 distributeObjCPointerTypeAttr(state, attr, type); 04003 attr.setUsedAsTypeAttr(); 04004 break; 04005 case AttributeList::AT_vector_size: 04006 HandleVectorSizeAttr(type, attr, state.getSema()); 04007 attr.setUsedAsTypeAttr(); 04008 break; 04009 case AttributeList::AT_ext_vector_type: 04010 if (state.getDeclarator().getDeclSpec().getStorageClassSpec() 04011 != DeclSpec::SCS_typedef) 04012 HandleExtVectorTypeAttr(type, attr, state.getSema()); 04013 attr.setUsedAsTypeAttr(); 04014 break; 04015 case AttributeList::AT_neon_vector_type: 04016 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 04017 VectorType::NeonVector, "neon_vector_type"); 04018 attr.setUsedAsTypeAttr(); 04019 break; 04020 case AttributeList::AT_neon_polyvector_type: 04021 HandleNeonVectorTypeAttr(type, attr, state.getSema(), 04022 VectorType::NeonPolyVector, 04023 "neon_polyvector_type"); 04024 attr.setUsedAsTypeAttr(); 04025 break; 04026 case AttributeList::AT_opencl_image_access: 04027 HandleOpenCLImageAccessAttribute(type, attr, state.getSema()); 04028 attr.setUsedAsTypeAttr(); 04029 break; 04030 04031 case AttributeList::AT_ns_returns_retained: 04032 if (!state.getSema().getLangOpts().ObjCAutoRefCount) 04033 break; 04034 // fallthrough into the function attrs 04035 04036 FUNCTION_TYPE_ATTRS_CASELIST: 04037 attr.setUsedAsTypeAttr(); 04038 04039 // Never process function type attributes as part of the 04040 // declaration-specifiers. 04041 if (isDeclSpec) 04042 distributeFunctionTypeAttrFromDeclSpec(state, attr, type); 04043 04044 // Otherwise, handle the possible delays. 04045 else if (!handleFunctionTypeAttr(state, attr, type)) 04046 distributeFunctionTypeAttr(state, attr, type); 04047 break; 04048 } 04049 } while ((attrs = next)); 04050 } 04051 04052 /// \brief Ensure that the type of the given expression is complete. 04053 /// 04054 /// This routine checks whether the expression \p E has a complete type. If the 04055 /// expression refers to an instantiable construct, that instantiation is 04056 /// performed as needed to complete its type. Furthermore 04057 /// Sema::RequireCompleteType is called for the expression's type (or in the 04058 /// case of a reference type, the referred-to type). 04059 /// 04060 /// \param E The expression whose type is required to be complete. 04061 /// \param Diagnoser The object that will emit a diagnostic if the type is 04062 /// incomplete. 04063 /// 04064 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 04065 /// otherwise. 04066 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){ 04067 QualType T = E->getType(); 04068 04069 // Fast path the case where the type is already complete. 04070 if (!T->isIncompleteType()) 04071 return false; 04072 04073 // Incomplete array types may be completed by the initializer attached to 04074 // their definitions. For static data members of class templates we need to 04075 // instantiate the definition to get this initializer and complete the type. 04076 if (T->isIncompleteArrayType()) { 04077 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 04078 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 04079 if (Var->isStaticDataMember() && 04080 Var->getInstantiatedFromStaticDataMember()) { 04081 04082 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 04083 assert(MSInfo && "Missing member specialization information?"); 04084 if (MSInfo->getTemplateSpecializationKind() 04085 != TSK_ExplicitSpecialization) { 04086 // If we don't already have a point of instantiation, this is it. 04087 if (MSInfo->getPointOfInstantiation().isInvalid()) { 04088 MSInfo->setPointOfInstantiation(E->getLocStart()); 04089 04090 // This is a modification of an existing AST node. Notify 04091 // listeners. 04092 if (ASTMutationListener *L = getASTMutationListener()) 04093 L->StaticDataMemberInstantiated(Var); 04094 } 04095 04096 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var); 04097 04098 // Update the type to the newly instantiated definition's type both 04099 // here and within the expression. 04100 if (VarDecl *Def = Var->getDefinition()) { 04101 DRE->setDecl(Def); 04102 T = Def->getType(); 04103 DRE->setType(T); 04104 E->setType(T); 04105 } 04106 } 04107 04108 // We still go on to try to complete the type independently, as it 04109 // may also require instantiations or diagnostics if it remains 04110 // incomplete. 04111 } 04112 } 04113 } 04114 } 04115 04116 // FIXME: Are there other cases which require instantiating something other 04117 // than the type to complete the type of an expression? 04118 04119 // Look through reference types and complete the referred type. 04120 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 04121 T = Ref->getPointeeType(); 04122 04123 return RequireCompleteType(E->getExprLoc(), T, Diagnoser); 04124 } 04125 04126 namespace { 04127 struct TypeDiagnoserDiag : Sema::TypeDiagnoser { 04128 unsigned DiagID; 04129 04130 TypeDiagnoserDiag(unsigned DiagID) 04131 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {} 04132 04133 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 04134 if (Suppressed) return; 04135 S.Diag(Loc, DiagID) << T; 04136 } 04137 }; 04138 } 04139 04140 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { 04141 TypeDiagnoserDiag Diagnoser(DiagID); 04142 return RequireCompleteExprType(E, Diagnoser); 04143 } 04144 04145 /// @brief Ensure that the type T is a complete type. 04146 /// 04147 /// This routine checks whether the type @p T is complete in any 04148 /// context where a complete type is required. If @p T is a complete 04149 /// type, returns false. If @p T is a class template specialization, 04150 /// this routine then attempts to perform class template 04151 /// instantiation. If instantiation fails, or if @p T is incomplete 04152 /// and cannot be completed, issues the diagnostic @p diag (giving it 04153 /// the type @p T) and returns true. 04154 /// 04155 /// @param Loc The location in the source that the incomplete type 04156 /// diagnostic should refer to. 04157 /// 04158 /// @param T The type that this routine is examining for completeness. 04159 /// 04160 /// @param PD The partial diagnostic that will be printed out if T is not a 04161 /// complete type. 04162 /// 04163 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 04164 /// @c false otherwise. 04165 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 04166 TypeDiagnoser &Diagnoser) { 04167 // FIXME: Add this assertion to make sure we always get instantiation points. 04168 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 04169 // FIXME: Add this assertion to help us flush out problems with 04170 // checking for dependent types and type-dependent expressions. 04171 // 04172 // assert(!T->isDependentType() && 04173 // "Can't ask whether a dependent type is complete"); 04174 04175 // If we have a complete type, we're done. 04176 NamedDecl *Def = 0; 04177 if (!T->isIncompleteType(&Def)) { 04178 // If we know about the definition but it is not visible, complain. 04179 if (!Diagnoser.Suppressed && Def && !LookupResult::isVisible(Def)) { 04180 // Suppress this error outside of a SFINAE context if we've already 04181 // emitted the error once for this type. There's no usefulness in 04182 // repeating the diagnostic. 04183 // FIXME: Add a Fix-It that imports the corresponding module or includes 04184 // the header. 04185 if (isSFINAEContext() || HiddenDefinitions.insert(Def)) { 04186 Diag(Loc, diag::err_module_private_definition) << T; 04187 Diag(Def->getLocation(), diag::note_previous_definition); 04188 } 04189 } 04190 04191 return false; 04192 } 04193 04194 const TagType *Tag = T->getAs<TagType>(); 04195 const ObjCInterfaceType *IFace = 0; 04196 04197 if (Tag) { 04198 // Avoid diagnosing invalid decls as incomplete. 04199 if (Tag->getDecl()->isInvalidDecl()) 04200 return true; 04201 04202 // Give the external AST source a chance to complete the type. 04203 if (Tag->getDecl()->hasExternalLexicalStorage()) { 04204 Context.getExternalSource()->CompleteType(Tag->getDecl()); 04205 if (!Tag->isIncompleteType()) 04206 return false; 04207 } 04208 } 04209 else if ((IFace = T->getAs<ObjCInterfaceType>())) { 04210 // Avoid diagnosing invalid decls as incomplete. 04211 if (IFace->getDecl()->isInvalidDecl()) 04212 return true; 04213 04214 // Give the external AST source a chance to complete the type. 04215 if (IFace->getDecl()->hasExternalLexicalStorage()) { 04216 Context.getExternalSource()->CompleteType(IFace->getDecl()); 04217 if (!IFace->isIncompleteType()) 04218 return false; 04219 } 04220 } 04221 04222 // If we have a class template specialization or a class member of a 04223 // class template specialization, or an array with known size of such, 04224 // try to instantiate it. 04225 QualType MaybeTemplate = T; 04226 while (const ConstantArrayType *Array 04227 = Context.getAsConstantArrayType(MaybeTemplate)) 04228 MaybeTemplate = Array->getElementType(); 04229 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 04230 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 04231 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 04232 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) 04233 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec, 04234 TSK_ImplicitInstantiation, 04235 /*Complain=*/!Diagnoser.Suppressed); 04236 } else if (CXXRecordDecl *Rec 04237 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 04238 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass(); 04239 if (!Rec->isBeingDefined() && Pattern) { 04240 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo(); 04241 assert(MSI && "Missing member specialization information?"); 04242 // This record was instantiated from a class within a template. 04243 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 04244 return InstantiateClass(Loc, Rec, Pattern, 04245 getTemplateInstantiationArgs(Rec), 04246 TSK_ImplicitInstantiation, 04247 /*Complain=*/!Diagnoser.Suppressed); 04248 } 04249 } 04250 } 04251 04252 if (Diagnoser.Suppressed) 04253 return true; 04254 04255 // We have an incomplete type. Produce a diagnostic. 04256 Diagnoser.diagnose(*this, Loc, T); 04257 04258 // If the type was a forward declaration of a class/struct/union 04259 // type, produce a note. 04260 if (Tag && !Tag->getDecl()->isInvalidDecl()) 04261 Diag(Tag->getDecl()->getLocation(), 04262 Tag->isBeingDefined() ? diag::note_type_being_defined 04263 : diag::note_forward_declaration) 04264 << QualType(Tag, 0); 04265 04266 // If the Objective-C class was a forward declaration, produce a note. 04267 if (IFace && !IFace->getDecl()->isInvalidDecl()) 04268 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class); 04269 04270 return true; 04271 } 04272 04273 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 04274 unsigned DiagID) { 04275 TypeDiagnoserDiag Diagnoser(DiagID); 04276 return RequireCompleteType(Loc, T, Diagnoser); 04277 } 04278 04279 /// @brief Ensure that the type T is a literal type. 04280 /// 04281 /// This routine checks whether the type @p T is a literal type. If @p T is an 04282 /// incomplete type, an attempt is made to complete it. If @p T is a literal 04283 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 04284 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 04285 /// it the type @p T), along with notes explaining why the type is not a 04286 /// literal type, and returns true. 04287 /// 04288 /// @param Loc The location in the source that the non-literal type 04289 /// diagnostic should refer to. 04290 /// 04291 /// @param T The type that this routine is examining for literalness. 04292 /// 04293 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 04294 /// 04295 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, 04296 /// @c false otherwise. 04297 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, 04298 TypeDiagnoser &Diagnoser) { 04299 assert(!T->isDependentType() && "type should not be dependent"); 04300 04301 QualType ElemType = Context.getBaseElementType(T); 04302 RequireCompleteType(Loc, ElemType, 0); 04303 04304 if (T->isLiteralType()) 04305 return false; 04306 04307 if (Diagnoser.Suppressed) 04308 return true; 04309 04310 Diagnoser.diagnose(*this, Loc, T); 04311 04312 if (T->isVariableArrayType()) 04313 return true; 04314 04315 const RecordType *RT = ElemType->getAs<RecordType>(); 04316 if (!RT) 04317 return true; 04318 04319 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 04320 04321 // A partially-defined class type can't be a literal type, because a literal 04322 // class type must have a trivial destructor (which can't be checked until 04323 // the class definition is complete). 04324 if (!RD->isCompleteDefinition()) { 04325 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T); 04326 return true; 04327 } 04328 04329 // If the class has virtual base classes, then it's not an aggregate, and 04330 // cannot have any constexpr constructors or a trivial default constructor, 04331 // so is non-literal. This is better to diagnose than the resulting absence 04332 // of constexpr constructors. 04333 if (RD->getNumVBases()) { 04334 Diag(RD->getLocation(), diag::note_non_literal_virtual_base) 04335 << RD->isStruct() << RD->getNumVBases(); 04336 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 04337 E = RD->vbases_end(); I != E; ++I) 04338 Diag(I->getLocStart(), 04339 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 04340 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && 04341 !RD->hasTrivialDefaultConstructor()) { 04342 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; 04343 } else if (RD->hasNonLiteralTypeFieldsOrBases()) { 04344 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 04345 E = RD->bases_end(); I != E; ++I) { 04346 if (!I->getType()->isLiteralType()) { 04347 Diag(I->getLocStart(), 04348 diag::note_non_literal_base_class) 04349 << RD << I->getType() << I->getSourceRange(); 04350 return true; 04351 } 04352 } 04353 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 04354 E = RD->field_end(); I != E; ++I) { 04355 if (!I->getType()->isLiteralType() || 04356 I->getType().isVolatileQualified()) { 04357 Diag(I->getLocation(), diag::note_non_literal_field) 04358 << RD << &*I << I->getType() 04359 << I->getType().isVolatileQualified(); 04360 return true; 04361 } 04362 } 04363 } else if (!RD->hasTrivialDestructor()) { 04364 // All fields and bases are of literal types, so have trivial destructors. 04365 // If this class's destructor is non-trivial it must be user-declared. 04366 CXXDestructorDecl *Dtor = RD->getDestructor(); 04367 assert(Dtor && "class has literal fields and bases but no dtor?"); 04368 if (!Dtor) 04369 return true; 04370 04371 Diag(Dtor->getLocation(), Dtor->isUserProvided() ? 04372 diag::note_non_literal_user_provided_dtor : 04373 diag::note_non_literal_nontrivial_dtor) << RD; 04374 } 04375 04376 return true; 04377 } 04378 04379 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { 04380 TypeDiagnoserDiag Diagnoser(DiagID); 04381 return RequireLiteralType(Loc, T, Diagnoser); 04382 } 04383 04384 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 04385 /// and qualified by the nested-name-specifier contained in SS. 04386 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 04387 const CXXScopeSpec &SS, QualType T) { 04388 if (T.isNull()) 04389 return T; 04390 NestedNameSpecifier *NNS; 04391 if (SS.isValid()) 04392 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 04393 else { 04394 if (Keyword == ETK_None) 04395 return T; 04396 NNS = 0; 04397 } 04398 return Context.getElaboratedType(Keyword, NNS, T); 04399 } 04400 04401 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) { 04402 ExprResult ER = CheckPlaceholderExpr(E); 04403 if (ER.isInvalid()) return QualType(); 04404 E = ER.take(); 04405 04406 if (!E->isTypeDependent()) { 04407 QualType T = E->getType(); 04408 if (const TagType *TT = T->getAs<TagType>()) 04409 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); 04410 } 04411 return Context.getTypeOfExprType(E); 04412 } 04413 04414 /// getDecltypeForExpr - Given an expr, will return the decltype for 04415 /// that expression, according to the rules in C++11 04416 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. 04417 static QualType getDecltypeForExpr(Sema &S, Expr *E) { 04418 if (E->isTypeDependent()) 04419 return S.Context.DependentTy; 04420 04421 // C++11 [dcl.type.simple]p4: 04422 // The type denoted by decltype(e) is defined as follows: 04423 // 04424 // - if e is an unparenthesized id-expression or an unparenthesized class 04425 // member access (5.2.5), decltype(e) is the type of the entity named 04426 // by e. If there is no such entity, or if e names a set of overloaded 04427 // functions, the program is ill-formed; 04428 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 04429 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 04430 return VD->getType(); 04431 } 04432 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 04433 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 04434 return FD->getType(); 04435 } 04436 04437 // C++11 [expr.lambda.prim]p18: 04438 // Every occurrence of decltype((x)) where x is a possibly 04439 // parenthesized id-expression that names an entity of automatic 04440 // storage duration is treated as if x were transformed into an 04441 // access to a corresponding data member of the closure type that 04442 // would have been declared if x were an odr-use of the denoted 04443 // entity. 04444 using namespace sema; 04445 if (S.getCurLambda()) { 04446 if (isa<ParenExpr>(E)) { 04447 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 04448 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 04449 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation()); 04450 if (!T.isNull()) 04451 return S.Context.getLValueReferenceType(T); 04452 } 04453 } 04454 } 04455 } 04456 04457 04458 // C++11 [dcl.type.simple]p4: 04459 // [...] 04460 QualType T = E->getType(); 04461 switch (E->getValueKind()) { 04462 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the 04463 // type of e; 04464 case VK_XValue: T = S.Context.getRValueReferenceType(T); break; 04465 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the 04466 // type of e; 04467 case VK_LValue: T = S.Context.getLValueReferenceType(T); break; 04468 // - otherwise, decltype(e) is the type of e. 04469 case VK_RValue: break; 04470 } 04471 04472 return T; 04473 } 04474 04475 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) { 04476 ExprResult ER = CheckPlaceholderExpr(E); 04477 if (ER.isInvalid()) return QualType(); 04478 E = ER.take(); 04479 04480 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E)); 04481 } 04482 04483 QualType Sema::BuildUnaryTransformType(QualType BaseType, 04484 UnaryTransformType::UTTKind UKind, 04485 SourceLocation Loc) { 04486 switch (UKind) { 04487 case UnaryTransformType::EnumUnderlyingType: 04488 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { 04489 Diag(Loc, diag::err_only_enums_have_underlying_types); 04490 return QualType(); 04491 } else { 04492 QualType Underlying = BaseType; 04493 if (!BaseType->isDependentType()) { 04494 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl(); 04495 assert(ED && "EnumType has no EnumDecl"); 04496 DiagnoseUseOfDecl(ED, Loc); 04497 Underlying = ED->getIntegerType(); 04498 } 04499 assert(!Underlying.isNull()); 04500 return Context.getUnaryTransformType(BaseType, Underlying, 04501 UnaryTransformType::EnumUnderlyingType); 04502 } 04503 } 04504 llvm_unreachable("unknown unary transform type"); 04505 } 04506 04507 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { 04508 if (!T->isDependentType()) { 04509 // FIXME: It isn't entirely clear whether incomplete atomic types 04510 // are allowed or not; for simplicity, ban them for the moment. 04511 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) 04512 return QualType(); 04513 04514 int DisallowedKind = -1; 04515 if (T->isArrayType()) 04516 DisallowedKind = 1; 04517 else if (T->isFunctionType()) 04518 DisallowedKind = 2; 04519 else if (T->isReferenceType()) 04520 DisallowedKind = 3; 04521 else if (T->isAtomicType()) 04522 DisallowedKind = 4; 04523 else if (T.hasQualifiers()) 04524 DisallowedKind = 5; 04525 else if (!T.isTriviallyCopyableType(Context)) 04526 // Some other non-trivially-copyable type (probably a C++ class) 04527 DisallowedKind = 6; 04528 04529 if (DisallowedKind != -1) { 04530 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; 04531 return QualType(); 04532 } 04533 04534 // FIXME: Do we need any handling for ARC here? 04535 } 04536 04537 // Build the pointer type. 04538 return Context.getAtomicType(T); 04539 }