File: | build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaType.cpp |
Warning: | line 968, column 13 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file implements type-related semantic analysis. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | ||||
13 | #include "TypeLocBuilder.h" | |||
14 | #include "clang/AST/ASTConsumer.h" | |||
15 | #include "clang/AST/ASTContext.h" | |||
16 | #include "clang/AST/ASTMutationListener.h" | |||
17 | #include "clang/AST/ASTStructuralEquivalence.h" | |||
18 | #include "clang/AST/CXXInheritance.h" | |||
19 | #include "clang/AST/DeclObjC.h" | |||
20 | #include "clang/AST/DeclTemplate.h" | |||
21 | #include "clang/AST/Expr.h" | |||
22 | #include "clang/AST/TypeLoc.h" | |||
23 | #include "clang/AST/TypeLocVisitor.h" | |||
24 | #include "clang/Basic/PartialDiagnostic.h" | |||
25 | #include "clang/Basic/Specifiers.h" | |||
26 | #include "clang/Basic/TargetInfo.h" | |||
27 | #include "clang/Lex/Preprocessor.h" | |||
28 | #include "clang/Sema/DeclSpec.h" | |||
29 | #include "clang/Sema/DelayedDiagnostic.h" | |||
30 | #include "clang/Sema/Lookup.h" | |||
31 | #include "clang/Sema/ParsedTemplate.h" | |||
32 | #include "clang/Sema/ScopeInfo.h" | |||
33 | #include "clang/Sema/SemaInternal.h" | |||
34 | #include "clang/Sema/Template.h" | |||
35 | #include "clang/Sema/TemplateInstCallback.h" | |||
36 | #include "llvm/ADT/SmallPtrSet.h" | |||
37 | #include "llvm/ADT/SmallString.h" | |||
38 | #include "llvm/ADT/StringSwitch.h" | |||
39 | #include "llvm/IR/DerivedTypes.h" | |||
40 | #include "llvm/Support/ErrorHandling.h" | |||
41 | #include <bitset> | |||
42 | ||||
43 | using namespace clang; | |||
44 | ||||
45 | enum TypeDiagSelector { | |||
46 | TDS_Function, | |||
47 | TDS_Pointer, | |||
48 | TDS_ObjCObjOrBlock | |||
49 | }; | |||
50 | ||||
51 | /// isOmittedBlockReturnType - Return true if this declarator is missing a | |||
52 | /// return type because this is a omitted return type on a block literal. | |||
53 | static bool isOmittedBlockReturnType(const Declarator &D) { | |||
54 | if (D.getContext() != DeclaratorContext::BlockLiteral || | |||
55 | D.getDeclSpec().hasTypeSpecifier()) | |||
56 | return false; | |||
57 | ||||
58 | if (D.getNumTypeObjects() == 0) | |||
59 | return true; // ^{ ... } | |||
60 | ||||
61 | if (D.getNumTypeObjects() == 1 && | |||
62 | D.getTypeObject(0).Kind == DeclaratorChunk::Function) | |||
63 | return true; // ^(int X, float Y) { ... } | |||
64 | ||||
65 | return false; | |||
66 | } | |||
67 | ||||
68 | /// diagnoseBadTypeAttribute - Diagnoses a type attribute which | |||
69 | /// doesn't apply to the given type. | |||
70 | static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr, | |||
71 | QualType type) { | |||
72 | TypeDiagSelector WhichType; | |||
73 | bool useExpansionLoc = true; | |||
74 | switch (attr.getKind()) { | |||
75 | case ParsedAttr::AT_ObjCGC: | |||
76 | WhichType = TDS_Pointer; | |||
77 | break; | |||
78 | case ParsedAttr::AT_ObjCOwnership: | |||
79 | WhichType = TDS_ObjCObjOrBlock; | |||
80 | break; | |||
81 | default: | |||
82 | // Assume everything else was a function attribute. | |||
83 | WhichType = TDS_Function; | |||
84 | useExpansionLoc = false; | |||
85 | break; | |||
86 | } | |||
87 | ||||
88 | SourceLocation loc = attr.getLoc(); | |||
89 | StringRef name = attr.getAttrName()->getName(); | |||
90 | ||||
91 | // The GC attributes are usually written with macros; special-case them. | |||
92 | IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident | |||
93 | : nullptr; | |||
94 | if (useExpansionLoc && loc.isMacroID() && II) { | |||
95 | if (II->isStr("strong")) { | |||
96 | if (S.findMacroSpelling(loc, "__strong")) name = "__strong"; | |||
97 | } else if (II->isStr("weak")) { | |||
98 | if (S.findMacroSpelling(loc, "__weak")) name = "__weak"; | |||
99 | } | |||
100 | } | |||
101 | ||||
102 | S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType | |||
103 | << type; | |||
104 | } | |||
105 | ||||
106 | // objc_gc applies to Objective-C pointers or, otherwise, to the | |||
107 | // smallest available pointer type (i.e. 'void*' in 'void**'). | |||
108 | #define OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership \ | |||
109 | case ParsedAttr::AT_ObjCGC: \ | |||
110 | case ParsedAttr::AT_ObjCOwnership | |||
111 | ||||
112 | // Calling convention attributes. | |||
113 | #define CALLING_CONV_ATTRS_CASELISTcase ParsedAttr::AT_CDecl: case ParsedAttr::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr::AT_ThisCall: case ParsedAttr ::AT_RegCall: case ParsedAttr::AT_Pascal: case ParsedAttr::AT_SwiftCall : case ParsedAttr::AT_SwiftAsyncCall: case ParsedAttr::AT_VectorCall : case ParsedAttr::AT_AArch64VectorPcs: case ParsedAttr::AT_MSABI : case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr ::AT_IntelOclBicc: case ParsedAttr::AT_PreserveMost: case ParsedAttr ::AT_PreserveAll \ | |||
114 | case ParsedAttr::AT_CDecl: \ | |||
115 | case ParsedAttr::AT_FastCall: \ | |||
116 | case ParsedAttr::AT_StdCall: \ | |||
117 | case ParsedAttr::AT_ThisCall: \ | |||
118 | case ParsedAttr::AT_RegCall: \ | |||
119 | case ParsedAttr::AT_Pascal: \ | |||
120 | case ParsedAttr::AT_SwiftCall: \ | |||
121 | case ParsedAttr::AT_SwiftAsyncCall: \ | |||
122 | case ParsedAttr::AT_VectorCall: \ | |||
123 | case ParsedAttr::AT_AArch64VectorPcs: \ | |||
124 | case ParsedAttr::AT_MSABI: \ | |||
125 | case ParsedAttr::AT_SysVABI: \ | |||
126 | case ParsedAttr::AT_Pcs: \ | |||
127 | case ParsedAttr::AT_IntelOclBicc: \ | |||
128 | case ParsedAttr::AT_PreserveMost: \ | |||
129 | case ParsedAttr::AT_PreserveAll | |||
130 | ||||
131 | // Function type attributes. | |||
132 | #define FUNCTION_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NoReturn : case ParsedAttr::AT_Regparm: case ParsedAttr::AT_CmseNSCall : case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: case ParsedAttr ::AT_AnyX86NoCfCheck: case ParsedAttr::AT_CDecl: case ParsedAttr ::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr:: AT_ThisCall: case ParsedAttr::AT_RegCall: case ParsedAttr::AT_Pascal : case ParsedAttr::AT_SwiftCall: case ParsedAttr::AT_SwiftAsyncCall : case ParsedAttr::AT_VectorCall: case ParsedAttr::AT_AArch64VectorPcs : case ParsedAttr::AT_MSABI: case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr::AT_IntelOclBicc: case ParsedAttr ::AT_PreserveMost: case ParsedAttr::AT_PreserveAll \ | |||
133 | case ParsedAttr::AT_NSReturnsRetained: \ | |||
134 | case ParsedAttr::AT_NoReturn: \ | |||
135 | case ParsedAttr::AT_Regparm: \ | |||
136 | case ParsedAttr::AT_CmseNSCall: \ | |||
137 | case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \ | |||
138 | case ParsedAttr::AT_AnyX86NoCfCheck: \ | |||
139 | CALLING_CONV_ATTRS_CASELISTcase ParsedAttr::AT_CDecl: case ParsedAttr::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr::AT_ThisCall: case ParsedAttr ::AT_RegCall: case ParsedAttr::AT_Pascal: case ParsedAttr::AT_SwiftCall : case ParsedAttr::AT_SwiftAsyncCall: case ParsedAttr::AT_VectorCall : case ParsedAttr::AT_AArch64VectorPcs: case ParsedAttr::AT_MSABI : case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr ::AT_IntelOclBicc: case ParsedAttr::AT_PreserveMost: case ParsedAttr ::AT_PreserveAll | |||
140 | ||||
141 | // Microsoft-specific type qualifiers. | |||
142 | #define MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr ::AT_SPtr: case ParsedAttr::AT_UPtr \ | |||
143 | case ParsedAttr::AT_Ptr32: \ | |||
144 | case ParsedAttr::AT_Ptr64: \ | |||
145 | case ParsedAttr::AT_SPtr: \ | |||
146 | case ParsedAttr::AT_UPtr | |||
147 | ||||
148 | // Nullability qualifiers. | |||
149 | #define NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable : case ParsedAttr::AT_TypeNullableResult: case ParsedAttr::AT_TypeNullUnspecified \ | |||
150 | case ParsedAttr::AT_TypeNonNull: \ | |||
151 | case ParsedAttr::AT_TypeNullable: \ | |||
152 | case ParsedAttr::AT_TypeNullableResult: \ | |||
153 | case ParsedAttr::AT_TypeNullUnspecified | |||
154 | ||||
155 | namespace { | |||
156 | /// An object which stores processing state for the entire | |||
157 | /// GetTypeForDeclarator process. | |||
158 | class TypeProcessingState { | |||
159 | Sema &sema; | |||
160 | ||||
161 | /// The declarator being processed. | |||
162 | Declarator &declarator; | |||
163 | ||||
164 | /// The index of the declarator chunk we're currently processing. | |||
165 | /// May be the total number of valid chunks, indicating the | |||
166 | /// DeclSpec. | |||
167 | unsigned chunkIndex; | |||
168 | ||||
169 | /// Whether there are non-trivial modifications to the decl spec. | |||
170 | bool trivial; | |||
171 | ||||
172 | /// Whether we saved the attributes in the decl spec. | |||
173 | bool hasSavedAttrs; | |||
174 | ||||
175 | /// The original set of attributes on the DeclSpec. | |||
176 | SmallVector<ParsedAttr *, 2> savedAttrs; | |||
177 | ||||
178 | /// A list of attributes to diagnose the uselessness of when the | |||
179 | /// processing is complete. | |||
180 | SmallVector<ParsedAttr *, 2> ignoredTypeAttrs; | |||
181 | ||||
182 | /// Attributes corresponding to AttributedTypeLocs that we have not yet | |||
183 | /// populated. | |||
184 | // FIXME: The two-phase mechanism by which we construct Types and fill | |||
185 | // their TypeLocs makes it hard to correctly assign these. We keep the | |||
186 | // attributes in creation order as an attempt to make them line up | |||
187 | // properly. | |||
188 | using TypeAttrPair = std::pair<const AttributedType*, const Attr*>; | |||
189 | SmallVector<TypeAttrPair, 8> AttrsForTypes; | |||
190 | bool AttrsForTypesSorted = true; | |||
191 | ||||
192 | /// MacroQualifiedTypes mapping to macro expansion locations that will be | |||
193 | /// stored in a MacroQualifiedTypeLoc. | |||
194 | llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros; | |||
195 | ||||
196 | /// Flag to indicate we parsed a noderef attribute. This is used for | |||
197 | /// validating that noderef was used on a pointer or array. | |||
198 | bool parsedNoDeref; | |||
199 | ||||
200 | public: | |||
201 | TypeProcessingState(Sema &sema, Declarator &declarator) | |||
202 | : sema(sema), declarator(declarator), | |||
203 | chunkIndex(declarator.getNumTypeObjects()), trivial(true), | |||
204 | hasSavedAttrs(false), parsedNoDeref(false) {} | |||
205 | ||||
206 | Sema &getSema() const { | |||
207 | return sema; | |||
208 | } | |||
209 | ||||
210 | Declarator &getDeclarator() const { | |||
211 | return declarator; | |||
212 | } | |||
213 | ||||
214 | bool isProcessingDeclSpec() const { | |||
215 | return chunkIndex == declarator.getNumTypeObjects(); | |||
216 | } | |||
217 | ||||
218 | unsigned getCurrentChunkIndex() const { | |||
219 | return chunkIndex; | |||
220 | } | |||
221 | ||||
222 | void setCurrentChunkIndex(unsigned idx) { | |||
223 | assert(idx <= declarator.getNumTypeObjects())(static_cast <bool> (idx <= declarator.getNumTypeObjects ()) ? void (0) : __assert_fail ("idx <= declarator.getNumTypeObjects()" , "clang/lib/Sema/SemaType.cpp", 223, __extension__ __PRETTY_FUNCTION__ )); | |||
224 | chunkIndex = idx; | |||
225 | } | |||
226 | ||||
227 | ParsedAttributesView &getCurrentAttributes() const { | |||
228 | if (isProcessingDeclSpec()) | |||
229 | return getMutableDeclSpec().getAttributes(); | |||
230 | return declarator.getTypeObject(chunkIndex).getAttrs(); | |||
231 | } | |||
232 | ||||
233 | /// Save the current set of attributes on the DeclSpec. | |||
234 | void saveDeclSpecAttrs() { | |||
235 | // Don't try to save them multiple times. | |||
236 | if (hasSavedAttrs) return; | |||
237 | ||||
238 | DeclSpec &spec = getMutableDeclSpec(); | |||
239 | llvm::append_range(savedAttrs, | |||
240 | llvm::make_pointer_range(spec.getAttributes())); | |||
241 | trivial &= savedAttrs.empty(); | |||
242 | hasSavedAttrs = true; | |||
243 | } | |||
244 | ||||
245 | /// Record that we had nowhere to put the given type attribute. | |||
246 | /// We will diagnose such attributes later. | |||
247 | void addIgnoredTypeAttr(ParsedAttr &attr) { | |||
248 | ignoredTypeAttrs.push_back(&attr); | |||
249 | } | |||
250 | ||||
251 | /// Diagnose all the ignored type attributes, given that the | |||
252 | /// declarator worked out to the given type. | |||
253 | void diagnoseIgnoredTypeAttrs(QualType type) const { | |||
254 | for (auto *Attr : ignoredTypeAttrs) | |||
255 | diagnoseBadTypeAttribute(getSema(), *Attr, type); | |||
256 | } | |||
257 | ||||
258 | /// Get an attributed type for the given attribute, and remember the Attr | |||
259 | /// object so that we can attach it to the AttributedTypeLoc. | |||
260 | QualType getAttributedType(Attr *A, QualType ModifiedType, | |||
261 | QualType EquivType) { | |||
262 | QualType T = | |||
263 | sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType); | |||
264 | AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A}); | |||
265 | AttrsForTypesSorted = false; | |||
266 | return T; | |||
267 | } | |||
268 | ||||
269 | /// Get a BTFTagAttributed type for the btf_type_tag attribute. | |||
270 | QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, | |||
271 | QualType WrappedType) { | |||
272 | return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType); | |||
273 | } | |||
274 | ||||
275 | /// Completely replace the \c auto in \p TypeWithAuto by | |||
276 | /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if | |||
277 | /// necessary. | |||
278 | QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) { | |||
279 | QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement); | |||
280 | if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) { | |||
281 | // Attributed type still should be an attributed type after replacement. | |||
282 | auto *NewAttrTy = cast<AttributedType>(T.getTypePtr()); | |||
283 | for (TypeAttrPair &A : AttrsForTypes) { | |||
284 | if (A.first == AttrTy) | |||
285 | A.first = NewAttrTy; | |||
286 | } | |||
287 | AttrsForTypesSorted = false; | |||
288 | } | |||
289 | return T; | |||
290 | } | |||
291 | ||||
292 | /// Extract and remove the Attr* for a given attributed type. | |||
293 | const Attr *takeAttrForAttributedType(const AttributedType *AT) { | |||
294 | if (!AttrsForTypesSorted) { | |||
295 | llvm::stable_sort(AttrsForTypes, llvm::less_first()); | |||
296 | AttrsForTypesSorted = true; | |||
297 | } | |||
298 | ||||
299 | // FIXME: This is quadratic if we have lots of reuses of the same | |||
300 | // attributed type. | |||
301 | for (auto It = std::partition_point( | |||
302 | AttrsForTypes.begin(), AttrsForTypes.end(), | |||
303 | [=](const TypeAttrPair &A) { return A.first < AT; }); | |||
304 | It != AttrsForTypes.end() && It->first == AT; ++It) { | |||
305 | if (It->second) { | |||
306 | const Attr *Result = It->second; | |||
307 | It->second = nullptr; | |||
308 | return Result; | |||
309 | } | |||
310 | } | |||
311 | ||||
312 | llvm_unreachable("no Attr* for AttributedType*")::llvm::llvm_unreachable_internal("no Attr* for AttributedType*" , "clang/lib/Sema/SemaType.cpp", 312); | |||
313 | } | |||
314 | ||||
315 | SourceLocation | |||
316 | getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const { | |||
317 | auto FoundLoc = LocsForMacros.find(MQT); | |||
318 | assert(FoundLoc != LocsForMacros.end() &&(static_cast <bool> (FoundLoc != LocsForMacros.end() && "Unable to find macro expansion location for MacroQualifedType" ) ? void (0) : __assert_fail ("FoundLoc != LocsForMacros.end() && \"Unable to find macro expansion location for MacroQualifedType\"" , "clang/lib/Sema/SemaType.cpp", 319, __extension__ __PRETTY_FUNCTION__ )) | |||
319 | "Unable to find macro expansion location for MacroQualifedType")(static_cast <bool> (FoundLoc != LocsForMacros.end() && "Unable to find macro expansion location for MacroQualifedType" ) ? void (0) : __assert_fail ("FoundLoc != LocsForMacros.end() && \"Unable to find macro expansion location for MacroQualifedType\"" , "clang/lib/Sema/SemaType.cpp", 319, __extension__ __PRETTY_FUNCTION__ )); | |||
320 | return FoundLoc->second; | |||
321 | } | |||
322 | ||||
323 | void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT, | |||
324 | SourceLocation Loc) { | |||
325 | LocsForMacros[MQT] = Loc; | |||
326 | } | |||
327 | ||||
328 | void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; } | |||
329 | ||||
330 | bool didParseNoDeref() const { return parsedNoDeref; } | |||
331 | ||||
332 | ~TypeProcessingState() { | |||
333 | if (trivial) return; | |||
334 | ||||
335 | restoreDeclSpecAttrs(); | |||
336 | } | |||
337 | ||||
338 | private: | |||
339 | DeclSpec &getMutableDeclSpec() const { | |||
340 | return const_cast<DeclSpec&>(declarator.getDeclSpec()); | |||
341 | } | |||
342 | ||||
343 | void restoreDeclSpecAttrs() { | |||
344 | assert(hasSavedAttrs)(static_cast <bool> (hasSavedAttrs) ? void (0) : __assert_fail ("hasSavedAttrs", "clang/lib/Sema/SemaType.cpp", 344, __extension__ __PRETTY_FUNCTION__)); | |||
345 | ||||
346 | getMutableDeclSpec().getAttributes().clearListOnly(); | |||
347 | for (ParsedAttr *AL : savedAttrs) | |||
348 | getMutableDeclSpec().getAttributes().addAtEnd(AL); | |||
349 | } | |||
350 | }; | |||
351 | } // end anonymous namespace | |||
352 | ||||
353 | static void moveAttrFromListToList(ParsedAttr &attr, | |||
354 | ParsedAttributesView &fromList, | |||
355 | ParsedAttributesView &toList) { | |||
356 | fromList.remove(&attr); | |||
357 | toList.addAtEnd(&attr); | |||
358 | } | |||
359 | ||||
360 | /// The location of a type attribute. | |||
361 | enum TypeAttrLocation { | |||
362 | /// The attribute is in the decl-specifier-seq. | |||
363 | TAL_DeclSpec, | |||
364 | /// The attribute is part of a DeclaratorChunk. | |||
365 | TAL_DeclChunk, | |||
366 | /// The attribute is immediately after the declaration's name. | |||
367 | TAL_DeclName | |||
368 | }; | |||
369 | ||||
370 | static void processTypeAttrs(TypeProcessingState &state, QualType &type, | |||
371 | TypeAttrLocation TAL, | |||
372 | const ParsedAttributesView &attrs); | |||
373 | ||||
374 | static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | |||
375 | QualType &type); | |||
376 | ||||
377 | static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, | |||
378 | ParsedAttr &attr, QualType &type); | |||
379 | ||||
380 | static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | |||
381 | QualType &type); | |||
382 | ||||
383 | static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, | |||
384 | ParsedAttr &attr, QualType &type); | |||
385 | ||||
386 | static bool handleObjCPointerTypeAttr(TypeProcessingState &state, | |||
387 | ParsedAttr &attr, QualType &type) { | |||
388 | if (attr.getKind() == ParsedAttr::AT_ObjCGC) | |||
389 | return handleObjCGCTypeAttr(state, attr, type); | |||
390 | assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership)(static_cast <bool> (attr.getKind() == ParsedAttr::AT_ObjCOwnership ) ? void (0) : __assert_fail ("attr.getKind() == ParsedAttr::AT_ObjCOwnership" , "clang/lib/Sema/SemaType.cpp", 390, __extension__ __PRETTY_FUNCTION__ )); | |||
391 | return handleObjCOwnershipTypeAttr(state, attr, type); | |||
392 | } | |||
393 | ||||
394 | /// Given the index of a declarator chunk, check whether that chunk | |||
395 | /// directly specifies the return type of a function and, if so, find | |||
396 | /// an appropriate place for it. | |||
397 | /// | |||
398 | /// \param i - a notional index which the search will start | |||
399 | /// immediately inside | |||
400 | /// | |||
401 | /// \param onlyBlockPointers Whether we should only look into block | |||
402 | /// pointer types (vs. all pointer types). | |||
403 | static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, | |||
404 | unsigned i, | |||
405 | bool onlyBlockPointers) { | |||
406 | assert(i <= declarator.getNumTypeObjects())(static_cast <bool> (i <= declarator.getNumTypeObjects ()) ? void (0) : __assert_fail ("i <= declarator.getNumTypeObjects()" , "clang/lib/Sema/SemaType.cpp", 406, __extension__ __PRETTY_FUNCTION__ )); | |||
407 | ||||
408 | DeclaratorChunk *result = nullptr; | |||
409 | ||||
410 | // First, look inwards past parens for a function declarator. | |||
411 | for (; i != 0; --i) { | |||
412 | DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1); | |||
413 | switch (fnChunk.Kind) { | |||
414 | case DeclaratorChunk::Paren: | |||
415 | continue; | |||
416 | ||||
417 | // If we find anything except a function, bail out. | |||
418 | case DeclaratorChunk::Pointer: | |||
419 | case DeclaratorChunk::BlockPointer: | |||
420 | case DeclaratorChunk::Array: | |||
421 | case DeclaratorChunk::Reference: | |||
422 | case DeclaratorChunk::MemberPointer: | |||
423 | case DeclaratorChunk::Pipe: | |||
424 | return result; | |||
425 | ||||
426 | // If we do find a function declarator, scan inwards from that, | |||
427 | // looking for a (block-)pointer declarator. | |||
428 | case DeclaratorChunk::Function: | |||
429 | for (--i; i != 0; --i) { | |||
430 | DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1); | |||
431 | switch (ptrChunk.Kind) { | |||
432 | case DeclaratorChunk::Paren: | |||
433 | case DeclaratorChunk::Array: | |||
434 | case DeclaratorChunk::Function: | |||
435 | case DeclaratorChunk::Reference: | |||
436 | case DeclaratorChunk::Pipe: | |||
437 | continue; | |||
438 | ||||
439 | case DeclaratorChunk::MemberPointer: | |||
440 | case DeclaratorChunk::Pointer: | |||
441 | if (onlyBlockPointers) | |||
442 | continue; | |||
443 | ||||
444 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
445 | ||||
446 | case DeclaratorChunk::BlockPointer: | |||
447 | result = &ptrChunk; | |||
448 | goto continue_outer; | |||
449 | } | |||
450 | llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind" , "clang/lib/Sema/SemaType.cpp", 450); | |||
451 | } | |||
452 | ||||
453 | // If we run out of declarators doing that, we're done. | |||
454 | return result; | |||
455 | } | |||
456 | llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind" , "clang/lib/Sema/SemaType.cpp", 456); | |||
457 | ||||
458 | // Okay, reconsider from our new point. | |||
459 | continue_outer: ; | |||
460 | } | |||
461 | ||||
462 | // Ran out of chunks, bail out. | |||
463 | return result; | |||
464 | } | |||
465 | ||||
466 | /// Given that an objc_gc attribute was written somewhere on a | |||
467 | /// declaration *other* than on the declarator itself (for which, use | |||
468 | /// distributeObjCPointerTypeAttrFromDeclarator), and given that it | |||
469 | /// didn't apply in whatever position it was written in, try to move | |||
470 | /// it to a more appropriate position. | |||
471 | static void distributeObjCPointerTypeAttr(TypeProcessingState &state, | |||
472 | ParsedAttr &attr, QualType type) { | |||
473 | Declarator &declarator = state.getDeclarator(); | |||
474 | ||||
475 | // Move it to the outermost normal or block pointer declarator. | |||
476 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | |||
477 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | |||
478 | switch (chunk.Kind) { | |||
479 | case DeclaratorChunk::Pointer: | |||
480 | case DeclaratorChunk::BlockPointer: { | |||
481 | // But don't move an ARC ownership attribute to the return type | |||
482 | // of a block. | |||
483 | DeclaratorChunk *destChunk = nullptr; | |||
484 | if (state.isProcessingDeclSpec() && | |||
485 | attr.getKind() == ParsedAttr::AT_ObjCOwnership) | |||
486 | destChunk = maybeMovePastReturnType(declarator, i - 1, | |||
487 | /*onlyBlockPointers=*/true); | |||
488 | if (!destChunk) destChunk = &chunk; | |||
489 | ||||
490 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | |||
491 | destChunk->getAttrs()); | |||
492 | return; | |||
493 | } | |||
494 | ||||
495 | case DeclaratorChunk::Paren: | |||
496 | case DeclaratorChunk::Array: | |||
497 | continue; | |||
498 | ||||
499 | // We may be starting at the return type of a block. | |||
500 | case DeclaratorChunk::Function: | |||
501 | if (state.isProcessingDeclSpec() && | |||
502 | attr.getKind() == ParsedAttr::AT_ObjCOwnership) { | |||
503 | if (DeclaratorChunk *dest = maybeMovePastReturnType( | |||
504 | declarator, i, | |||
505 | /*onlyBlockPointers=*/true)) { | |||
506 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | |||
507 | dest->getAttrs()); | |||
508 | return; | |||
509 | } | |||
510 | } | |||
511 | goto error; | |||
512 | ||||
513 | // Don't walk through these. | |||
514 | case DeclaratorChunk::Reference: | |||
515 | case DeclaratorChunk::MemberPointer: | |||
516 | case DeclaratorChunk::Pipe: | |||
517 | goto error; | |||
518 | } | |||
519 | } | |||
520 | error: | |||
521 | ||||
522 | diagnoseBadTypeAttribute(state.getSema(), attr, type); | |||
523 | } | |||
524 | ||||
525 | /// Distribute an objc_gc type attribute that was written on the | |||
526 | /// declarator. | |||
527 | static void distributeObjCPointerTypeAttrFromDeclarator( | |||
528 | TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) { | |||
529 | Declarator &declarator = state.getDeclarator(); | |||
530 | ||||
531 | // objc_gc goes on the innermost pointer to something that's not a | |||
532 | // pointer. | |||
533 | unsigned innermost = -1U; | |||
534 | bool considerDeclSpec = true; | |||
535 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | |||
536 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | |||
537 | switch (chunk.Kind) { | |||
538 | case DeclaratorChunk::Pointer: | |||
539 | case DeclaratorChunk::BlockPointer: | |||
540 | innermost = i; | |||
541 | continue; | |||
542 | ||||
543 | case DeclaratorChunk::Reference: | |||
544 | case DeclaratorChunk::MemberPointer: | |||
545 | case DeclaratorChunk::Paren: | |||
546 | case DeclaratorChunk::Array: | |||
547 | case DeclaratorChunk::Pipe: | |||
548 | continue; | |||
549 | ||||
550 | case DeclaratorChunk::Function: | |||
551 | considerDeclSpec = false; | |||
552 | goto done; | |||
553 | } | |||
554 | } | |||
555 | done: | |||
556 | ||||
557 | // That might actually be the decl spec if we weren't blocked by | |||
558 | // anything in the declarator. | |||
559 | if (considerDeclSpec) { | |||
560 | if (handleObjCPointerTypeAttr(state, attr, declSpecType)) { | |||
561 | // Splice the attribute into the decl spec. Prevents the | |||
562 | // attribute from being applied multiple times and gives | |||
563 | // the source-location-filler something to work with. | |||
564 | state.saveDeclSpecAttrs(); | |||
565 | declarator.getMutableDeclSpec().getAttributes().takeOneFrom( | |||
566 | declarator.getAttributes(), &attr); | |||
567 | return; | |||
568 | } | |||
569 | } | |||
570 | ||||
571 | // Otherwise, if we found an appropriate chunk, splice the attribute | |||
572 | // into it. | |||
573 | if (innermost != -1U) { | |||
574 | moveAttrFromListToList(attr, declarator.getAttributes(), | |||
575 | declarator.getTypeObject(innermost).getAttrs()); | |||
576 | return; | |||
577 | } | |||
578 | ||||
579 | // Otherwise, diagnose when we're done building the type. | |||
580 | declarator.getAttributes().remove(&attr); | |||
581 | state.addIgnoredTypeAttr(attr); | |||
582 | } | |||
583 | ||||
584 | /// A function type attribute was written somewhere in a declaration | |||
585 | /// *other* than on the declarator itself or in the decl spec. Given | |||
586 | /// that it didn't apply in whatever position it was written in, try | |||
587 | /// to move it to a more appropriate position. | |||
588 | static void distributeFunctionTypeAttr(TypeProcessingState &state, | |||
589 | ParsedAttr &attr, QualType type) { | |||
590 | Declarator &declarator = state.getDeclarator(); | |||
591 | ||||
592 | // Try to push the attribute from the return type of a function to | |||
593 | // the function itself. | |||
594 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | |||
595 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | |||
596 | switch (chunk.Kind) { | |||
597 | case DeclaratorChunk::Function: | |||
598 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | |||
599 | chunk.getAttrs()); | |||
600 | return; | |||
601 | ||||
602 | case DeclaratorChunk::Paren: | |||
603 | case DeclaratorChunk::Pointer: | |||
604 | case DeclaratorChunk::BlockPointer: | |||
605 | case DeclaratorChunk::Array: | |||
606 | case DeclaratorChunk::Reference: | |||
607 | case DeclaratorChunk::MemberPointer: | |||
608 | case DeclaratorChunk::Pipe: | |||
609 | continue; | |||
610 | } | |||
611 | } | |||
612 | ||||
613 | diagnoseBadTypeAttribute(state.getSema(), attr, type); | |||
614 | } | |||
615 | ||||
616 | /// Try to distribute a function type attribute to the innermost | |||
617 | /// function chunk or type. Returns true if the attribute was | |||
618 | /// distributed, false if no location was found. | |||
619 | static bool distributeFunctionTypeAttrToInnermost( | |||
620 | TypeProcessingState &state, ParsedAttr &attr, | |||
621 | ParsedAttributesView &attrList, QualType &declSpecType) { | |||
622 | Declarator &declarator = state.getDeclarator(); | |||
623 | ||||
624 | // Put it on the innermost function chunk, if there is one. | |||
625 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | |||
626 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | |||
627 | if (chunk.Kind != DeclaratorChunk::Function) continue; | |||
628 | ||||
629 | moveAttrFromListToList(attr, attrList, chunk.getAttrs()); | |||
630 | return true; | |||
631 | } | |||
632 | ||||
633 | return handleFunctionTypeAttr(state, attr, declSpecType); | |||
634 | } | |||
635 | ||||
636 | /// A function type attribute was written in the decl spec. Try to | |||
637 | /// apply it somewhere. | |||
638 | static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, | |||
639 | ParsedAttr &attr, | |||
640 | QualType &declSpecType) { | |||
641 | state.saveDeclSpecAttrs(); | |||
642 | ||||
643 | // C++11 attributes before the decl specifiers actually appertain to | |||
644 | // the declarators. Move them straight there. We don't support the | |||
645 | // 'put them wherever you like' semantics we allow for GNU attributes. | |||
646 | if (attr.isStandardAttributeSyntax()) { | |||
647 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | |||
648 | state.getDeclarator().getAttributes()); | |||
649 | return; | |||
650 | } | |||
651 | ||||
652 | // Try to distribute to the innermost. | |||
653 | if (distributeFunctionTypeAttrToInnermost( | |||
654 | state, attr, state.getCurrentAttributes(), declSpecType)) | |||
655 | return; | |||
656 | ||||
657 | // If that failed, diagnose the bad attribute when the declarator is | |||
658 | // fully built. | |||
659 | state.addIgnoredTypeAttr(attr); | |||
660 | } | |||
661 | ||||
662 | /// A function type attribute was written on the declarator. Try to | |||
663 | /// apply it somewhere. | |||
664 | static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, | |||
665 | ParsedAttr &attr, | |||
666 | QualType &declSpecType) { | |||
667 | Declarator &declarator = state.getDeclarator(); | |||
668 | ||||
669 | // Try to distribute to the innermost. | |||
670 | if (distributeFunctionTypeAttrToInnermost( | |||
671 | state, attr, declarator.getAttributes(), declSpecType)) | |||
672 | return; | |||
673 | ||||
674 | // If that failed, diagnose the bad attribute when the declarator is | |||
675 | // fully built. | |||
676 | declarator.getAttributes().remove(&attr); | |||
677 | state.addIgnoredTypeAttr(attr); | |||
678 | } | |||
679 | ||||
680 | /// Given that there are attributes written on the declarator | |||
681 | /// itself, try to distribute any type attributes to the appropriate | |||
682 | /// declarator chunk. | |||
683 | /// | |||
684 | /// These are attributes like the following: | |||
685 | /// int f ATTR; | |||
686 | /// int (f ATTR)(); | |||
687 | /// but not necessarily this: | |||
688 | /// int f() ATTR; | |||
689 | static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, | |||
690 | QualType &declSpecType) { | |||
691 | // Collect all the type attributes from the declarator itself. | |||
692 | assert(!state.getDeclarator().getAttributes().empty() &&(static_cast <bool> (!state.getDeclarator().getAttributes ().empty() && "declarator has no attrs!") ? void (0) : __assert_fail ("!state.getDeclarator().getAttributes().empty() && \"declarator has no attrs!\"" , "clang/lib/Sema/SemaType.cpp", 693, __extension__ __PRETTY_FUNCTION__ )) | |||
693 | "declarator has no attrs!")(static_cast <bool> (!state.getDeclarator().getAttributes ().empty() && "declarator has no attrs!") ? void (0) : __assert_fail ("!state.getDeclarator().getAttributes().empty() && \"declarator has no attrs!\"" , "clang/lib/Sema/SemaType.cpp", 693, __extension__ __PRETTY_FUNCTION__ )); | |||
694 | // The called functions in this loop actually remove things from the current | |||
695 | // list, so iterating over the existing list isn't possible. Instead, make a | |||
696 | // non-owning copy and iterate over that. | |||
697 | ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()}; | |||
698 | for (ParsedAttr &attr : AttrsCopy) { | |||
699 | // Do not distribute [[]] attributes. They have strict rules for what | |||
700 | // they appertain to. | |||
701 | if (attr.isStandardAttributeSyntax()) | |||
702 | continue; | |||
703 | ||||
704 | switch (attr.getKind()) { | |||
705 | OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership: | |||
706 | distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType); | |||
707 | break; | |||
708 | ||||
709 | FUNCTION_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NoReturn : case ParsedAttr::AT_Regparm: case ParsedAttr::AT_CmseNSCall : case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: case ParsedAttr ::AT_AnyX86NoCfCheck: case ParsedAttr::AT_CDecl: case ParsedAttr ::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr:: AT_ThisCall: case ParsedAttr::AT_RegCall: case ParsedAttr::AT_Pascal : case ParsedAttr::AT_SwiftCall: case ParsedAttr::AT_SwiftAsyncCall : case ParsedAttr::AT_VectorCall: case ParsedAttr::AT_AArch64VectorPcs : case ParsedAttr::AT_MSABI: case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr::AT_IntelOclBicc: case ParsedAttr ::AT_PreserveMost: case ParsedAttr::AT_PreserveAll: | |||
710 | distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType); | |||
711 | break; | |||
712 | ||||
713 | MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr ::AT_SPtr: case ParsedAttr::AT_UPtr: | |||
714 | // Microsoft type attributes cannot go after the declarator-id. | |||
715 | continue; | |||
716 | ||||
717 | NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable : case ParsedAttr::AT_TypeNullableResult: case ParsedAttr::AT_TypeNullUnspecified: | |||
718 | // Nullability specifiers cannot go after the declarator-id. | |||
719 | ||||
720 | // Objective-C __kindof does not get distributed. | |||
721 | case ParsedAttr::AT_ObjCKindOf: | |||
722 | continue; | |||
723 | ||||
724 | default: | |||
725 | break; | |||
726 | } | |||
727 | } | |||
728 | } | |||
729 | ||||
730 | /// Add a synthetic '()' to a block-literal declarator if it is | |||
731 | /// required, given the return type. | |||
732 | static void maybeSynthesizeBlockSignature(TypeProcessingState &state, | |||
733 | QualType declSpecType) { | |||
734 | Declarator &declarator = state.getDeclarator(); | |||
735 | ||||
736 | // First, check whether the declarator would produce a function, | |||
737 | // i.e. whether the innermost semantic chunk is a function. | |||
738 | if (declarator.isFunctionDeclarator()) { | |||
739 | // If so, make that declarator a prototyped declarator. | |||
740 | declarator.getFunctionTypeInfo().hasPrototype = true; | |||
741 | return; | |||
742 | } | |||
743 | ||||
744 | // If there are any type objects, the type as written won't name a | |||
745 | // function, regardless of the decl spec type. This is because a | |||
746 | // block signature declarator is always an abstract-declarator, and | |||
747 | // abstract-declarators can't just be parentheses chunks. Therefore | |||
748 | // we need to build a function chunk unless there are no type | |||
749 | // objects and the decl spec type is a function. | |||
750 | if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) | |||
751 | return; | |||
752 | ||||
753 | // Note that there *are* cases with invalid declarators where | |||
754 | // declarators consist solely of parentheses. In general, these | |||
755 | // occur only in failed efforts to make function declarators, so | |||
756 | // faking up the function chunk is still the right thing to do. | |||
757 | ||||
758 | // Otherwise, we need to fake up a function declarator. | |||
759 | SourceLocation loc = declarator.getBeginLoc(); | |||
760 | ||||
761 | // ...and *prepend* it to the declarator. | |||
762 | SourceLocation NoLoc; | |||
763 | declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction( | |||
764 | /*HasProto=*/true, | |||
765 | /*IsAmbiguous=*/false, | |||
766 | /*LParenLoc=*/NoLoc, | |||
767 | /*ArgInfo=*/nullptr, | |||
768 | /*NumParams=*/0, | |||
769 | /*EllipsisLoc=*/NoLoc, | |||
770 | /*RParenLoc=*/NoLoc, | |||
771 | /*RefQualifierIsLvalueRef=*/true, | |||
772 | /*RefQualifierLoc=*/NoLoc, | |||
773 | /*MutableLoc=*/NoLoc, EST_None, | |||
774 | /*ESpecRange=*/SourceRange(), | |||
775 | /*Exceptions=*/nullptr, | |||
776 | /*ExceptionRanges=*/nullptr, | |||
777 | /*NumExceptions=*/0, | |||
778 | /*NoexceptExpr=*/nullptr, | |||
779 | /*ExceptionSpecTokens=*/nullptr, | |||
780 | /*DeclsInPrototype=*/None, loc, loc, declarator)); | |||
781 | ||||
782 | // For consistency, make sure the state still has us as processing | |||
783 | // the decl spec. | |||
784 | assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1)(static_cast <bool> (state.getCurrentChunkIndex() == declarator .getNumTypeObjects() - 1) ? void (0) : __assert_fail ("state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1" , "clang/lib/Sema/SemaType.cpp", 784, __extension__ __PRETTY_FUNCTION__ )); | |||
785 | state.setCurrentChunkIndex(declarator.getNumTypeObjects()); | |||
786 | } | |||
787 | ||||
788 | static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, | |||
789 | unsigned &TypeQuals, | |||
790 | QualType TypeSoFar, | |||
791 | unsigned RemoveTQs, | |||
792 | unsigned DiagID) { | |||
793 | // If this occurs outside a template instantiation, warn the user about | |||
794 | // it; they probably didn't mean to specify a redundant qualifier. | |||
795 | typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc; | |||
796 | for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()), | |||
797 | QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()), | |||
798 | QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()), | |||
799 | QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) { | |||
800 | if (!(RemoveTQs & Qual.first)) | |||
801 | continue; | |||
802 | ||||
803 | if (!S.inTemplateInstantiation()) { | |||
804 | if (TypeQuals & Qual.first) | |||
805 | S.Diag(Qual.second, DiagID) | |||
806 | << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar | |||
807 | << FixItHint::CreateRemoval(Qual.second); | |||
808 | } | |||
809 | ||||
810 | TypeQuals &= ~Qual.first; | |||
811 | } | |||
812 | } | |||
813 | ||||
814 | /// Return true if this is omitted block return type. Also check type | |||
815 | /// attributes and type qualifiers when returning true. | |||
816 | static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, | |||
817 | QualType Result) { | |||
818 | if (!isOmittedBlockReturnType(declarator)) | |||
819 | return false; | |||
820 | ||||
821 | // Warn if we see type attributes for omitted return type on a block literal. | |||
822 | SmallVector<ParsedAttr *, 2> ToBeRemoved; | |||
823 | for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) { | |||
824 | if (AL.isInvalid() || !AL.isTypeAttr()) | |||
825 | continue; | |||
826 | S.Diag(AL.getLoc(), | |||
827 | diag::warn_block_literal_attributes_on_omitted_return_type) | |||
828 | << AL; | |||
829 | ToBeRemoved.push_back(&AL); | |||
830 | } | |||
831 | // Remove bad attributes from the list. | |||
832 | for (ParsedAttr *AL : ToBeRemoved) | |||
833 | declarator.getMutableDeclSpec().getAttributes().remove(AL); | |||
834 | ||||
835 | // Warn if we see type qualifiers for omitted return type on a block literal. | |||
836 | const DeclSpec &DS = declarator.getDeclSpec(); | |||
837 | unsigned TypeQuals = DS.getTypeQualifiers(); | |||
838 | diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1, | |||
839 | diag::warn_block_literal_qualifiers_on_omitted_return_type); | |||
840 | declarator.getMutableDeclSpec().ClearTypeQualifiers(); | |||
841 | ||||
842 | return true; | |||
843 | } | |||
844 | ||||
845 | /// Apply Objective-C type arguments to the given type. | |||
846 | static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type, | |||
847 | ArrayRef<TypeSourceInfo *> typeArgs, | |||
848 | SourceRange typeArgsRange, | |||
849 | bool failOnError = false) { | |||
850 | // We can only apply type arguments to an Objective-C class type. | |||
851 | const auto *objcObjectType = type->getAs<ObjCObjectType>(); | |||
852 | if (!objcObjectType || !objcObjectType->getInterface()) { | |||
853 | S.Diag(loc, diag::err_objc_type_args_non_class) | |||
854 | << type | |||
855 | << typeArgsRange; | |||
856 | ||||
857 | if (failOnError) | |||
858 | return QualType(); | |||
859 | return type; | |||
860 | } | |||
861 | ||||
862 | // The class type must be parameterized. | |||
863 | ObjCInterfaceDecl *objcClass = objcObjectType->getInterface(); | |||
864 | ObjCTypeParamList *typeParams = objcClass->getTypeParamList(); | |||
865 | if (!typeParams) { | |||
866 | S.Diag(loc, diag::err_objc_type_args_non_parameterized_class) | |||
867 | << objcClass->getDeclName() | |||
868 | << FixItHint::CreateRemoval(typeArgsRange); | |||
869 | ||||
870 | if (failOnError) | |||
871 | return QualType(); | |||
872 | ||||
873 | return type; | |||
874 | } | |||
875 | ||||
876 | // The type must not already be specialized. | |||
877 | if (objcObjectType->isSpecialized()) { | |||
878 | S.Diag(loc, diag::err_objc_type_args_specialized_class) | |||
879 | << type | |||
880 | << FixItHint::CreateRemoval(typeArgsRange); | |||
881 | ||||
882 | if (failOnError) | |||
883 | return QualType(); | |||
884 | ||||
885 | return type; | |||
886 | } | |||
887 | ||||
888 | // Check the type arguments. | |||
889 | SmallVector<QualType, 4> finalTypeArgs; | |||
890 | unsigned numTypeParams = typeParams->size(); | |||
891 | bool anyPackExpansions = false; | |||
892 | for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) { | |||
893 | TypeSourceInfo *typeArgInfo = typeArgs[i]; | |||
894 | QualType typeArg = typeArgInfo->getType(); | |||
895 | ||||
896 | // Type arguments cannot have explicit qualifiers or nullability. | |||
897 | // We ignore indirect sources of these, e.g. behind typedefs or | |||
898 | // template arguments. | |||
899 | if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) { | |||
900 | bool diagnosed = false; | |||
901 | SourceRange rangeToRemove; | |||
902 | if (auto attr = qual.getAs<AttributedTypeLoc>()) { | |||
903 | rangeToRemove = attr.getLocalSourceRange(); | |||
904 | if (attr.getTypePtr()->getImmediateNullability()) { | |||
905 | typeArg = attr.getTypePtr()->getModifiedType(); | |||
906 | S.Diag(attr.getBeginLoc(), | |||
907 | diag::err_objc_type_arg_explicit_nullability) | |||
908 | << typeArg << FixItHint::CreateRemoval(rangeToRemove); | |||
909 | diagnosed = true; | |||
910 | } | |||
911 | } | |||
912 | ||||
913 | if (!diagnosed) { | |||
914 | S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified) | |||
915 | << typeArg << typeArg.getQualifiers().getAsString() | |||
916 | << FixItHint::CreateRemoval(rangeToRemove); | |||
917 | } | |||
918 | } | |||
919 | ||||
920 | // Remove qualifiers even if they're non-local. | |||
921 | typeArg = typeArg.getUnqualifiedType(); | |||
922 | ||||
923 | finalTypeArgs.push_back(typeArg); | |||
924 | ||||
925 | if (typeArg->getAs<PackExpansionType>()) | |||
926 | anyPackExpansions = true; | |||
927 | ||||
928 | // Find the corresponding type parameter, if there is one. | |||
929 | ObjCTypeParamDecl *typeParam = nullptr; | |||
930 | if (!anyPackExpansions
| |||
931 | if (i < numTypeParams) { | |||
932 | typeParam = typeParams->begin()[i]; | |||
933 | } else { | |||
934 | // Too many arguments. | |||
935 | S.Diag(loc, diag::err_objc_type_args_wrong_arity) | |||
936 | << false | |||
937 | << objcClass->getDeclName() | |||
938 | << (unsigned)typeArgs.size() | |||
939 | << numTypeParams; | |||
940 | S.Diag(objcClass->getLocation(), diag::note_previous_decl) | |||
941 | << objcClass; | |||
942 | ||||
943 | if (failOnError) | |||
944 | return QualType(); | |||
945 | ||||
946 | return type; | |||
947 | } | |||
948 | } | |||
949 | ||||
950 | // Objective-C object pointer types must be substitutable for the bounds. | |||
951 | if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) { | |||
952 | // If we don't have a type parameter to match against, assume | |||
953 | // everything is fine. There was a prior pack expansion that | |||
954 | // means we won't be able to match anything. | |||
955 | if (!typeParam) { | |||
956 | assert(anyPackExpansions && "Too many arguments?")(static_cast <bool> (anyPackExpansions && "Too many arguments?" ) ? void (0) : __assert_fail ("anyPackExpansions && \"Too many arguments?\"" , "clang/lib/Sema/SemaType.cpp", 956, __extension__ __PRETTY_FUNCTION__ )); | |||
957 | continue; | |||
958 | } | |||
959 | ||||
960 | // Retrieve the bound. | |||
961 | QualType bound = typeParam->getUnderlyingType(); | |||
962 | const auto *boundObjC = bound->getAs<ObjCObjectPointerType>(); | |||
963 | ||||
964 | // Determine whether the type argument is substitutable for the bound. | |||
965 | if (typeArgObjC->isObjCIdType()) { | |||
966 | // When the type argument is 'id', the only acceptable type | |||
967 | // parameter bound is 'id'. | |||
968 | if (boundObjC->isObjCIdType()) | |||
| ||||
969 | continue; | |||
970 | } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) { | |||
971 | // Otherwise, we follow the assignability rules. | |||
972 | continue; | |||
973 | } | |||
974 | ||||
975 | // Diagnose the mismatch. | |||
976 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), | |||
977 | diag::err_objc_type_arg_does_not_match_bound) | |||
978 | << typeArg << bound << typeParam->getDeclName(); | |||
979 | S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) | |||
980 | << typeParam->getDeclName(); | |||
981 | ||||
982 | if (failOnError) | |||
983 | return QualType(); | |||
984 | ||||
985 | return type; | |||
986 | } | |||
987 | ||||
988 | // Block pointer types are permitted for unqualified 'id' bounds. | |||
989 | if (typeArg->isBlockPointerType()) { | |||
990 | // If we don't have a type parameter to match against, assume | |||
991 | // everything is fine. There was a prior pack expansion that | |||
992 | // means we won't be able to match anything. | |||
993 | if (!typeParam) { | |||
994 | assert(anyPackExpansions && "Too many arguments?")(static_cast <bool> (anyPackExpansions && "Too many arguments?" ) ? void (0) : __assert_fail ("anyPackExpansions && \"Too many arguments?\"" , "clang/lib/Sema/SemaType.cpp", 994, __extension__ __PRETTY_FUNCTION__ )); | |||
995 | continue; | |||
996 | } | |||
997 | ||||
998 | // Retrieve the bound. | |||
999 | QualType bound = typeParam->getUnderlyingType(); | |||
1000 | if (bound->isBlockCompatibleObjCPointerType(S.Context)) | |||
1001 | continue; | |||
1002 | ||||
1003 | // Diagnose the mismatch. | |||
1004 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), | |||
1005 | diag::err_objc_type_arg_does_not_match_bound) | |||
1006 | << typeArg << bound << typeParam->getDeclName(); | |||
1007 | S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) | |||
1008 | << typeParam->getDeclName(); | |||
1009 | ||||
1010 | if (failOnError) | |||
1011 | return QualType(); | |||
1012 | ||||
1013 | return type; | |||
1014 | } | |||
1015 | ||||
1016 | // Dependent types will be checked at instantiation time. | |||
1017 | if (typeArg->isDependentType()) { | |||
1018 | continue; | |||
1019 | } | |||
1020 | ||||
1021 | // Diagnose non-id-compatible type arguments. | |||
1022 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), | |||
1023 | diag::err_objc_type_arg_not_id_compatible) | |||
1024 | << typeArg << typeArgInfo->getTypeLoc().getSourceRange(); | |||
1025 | ||||
1026 | if (failOnError) | |||
1027 | return QualType(); | |||
1028 | ||||
1029 | return type; | |||
1030 | } | |||
1031 | ||||
1032 | // Make sure we didn't have the wrong number of arguments. | |||
1033 | if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) { | |||
1034 | S.Diag(loc, diag::err_objc_type_args_wrong_arity) | |||
1035 | << (typeArgs.size() < typeParams->size()) | |||
1036 | << objcClass->getDeclName() | |||
1037 | << (unsigned)finalTypeArgs.size() | |||
1038 | << (unsigned)numTypeParams; | |||
1039 | S.Diag(objcClass->getLocation(), diag::note_previous_decl) | |||
1040 | << objcClass; | |||
1041 | ||||
1042 | if (failOnError) | |||
1043 | return QualType(); | |||
1044 | ||||
1045 | return type; | |||
1046 | } | |||
1047 | ||||
1048 | // Success. Form the specialized type. | |||
1049 | return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false); | |||
1050 | } | |||
1051 | ||||
1052 | QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, | |||
1053 | SourceLocation ProtocolLAngleLoc, | |||
1054 | ArrayRef<ObjCProtocolDecl *> Protocols, | |||
1055 | ArrayRef<SourceLocation> ProtocolLocs, | |||
1056 | SourceLocation ProtocolRAngleLoc, | |||
1057 | bool FailOnError) { | |||
1058 | QualType Result = QualType(Decl->getTypeForDecl(), 0); | |||
1059 | if (!Protocols.empty()) { | |||
1060 | bool HasError; | |||
1061 | Result = Context.applyObjCProtocolQualifiers(Result, Protocols, | |||
1062 | HasError); | |||
1063 | if (HasError) { | |||
1064 | Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers) | |||
1065 | << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); | |||
1066 | if (FailOnError) Result = QualType(); | |||
1067 | } | |||
1068 | if (FailOnError && Result.isNull()) | |||
1069 | return QualType(); | |||
1070 | } | |||
1071 | ||||
1072 | return Result; | |||
1073 | } | |||
1074 | ||||
1075 | QualType Sema::BuildObjCObjectType(QualType BaseType, | |||
1076 | SourceLocation Loc, | |||
1077 | SourceLocation TypeArgsLAngleLoc, | |||
1078 | ArrayRef<TypeSourceInfo *> TypeArgs, | |||
1079 | SourceLocation TypeArgsRAngleLoc, | |||
1080 | SourceLocation ProtocolLAngleLoc, | |||
1081 | ArrayRef<ObjCProtocolDecl *> Protocols, | |||
1082 | ArrayRef<SourceLocation> ProtocolLocs, | |||
1083 | SourceLocation ProtocolRAngleLoc, | |||
1084 | bool FailOnError) { | |||
1085 | QualType Result = BaseType; | |||
1086 | if (!TypeArgs.empty()) { | |||
1087 | Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs, | |||
1088 | SourceRange(TypeArgsLAngleLoc, | |||
1089 | TypeArgsRAngleLoc), | |||
1090 | FailOnError); | |||
1091 | if (FailOnError && Result.isNull()) | |||
1092 | return QualType(); | |||
1093 | } | |||
1094 | ||||
1095 | if (!Protocols.empty()) { | |||
1096 | bool HasError; | |||
1097 | Result = Context.applyObjCProtocolQualifiers(Result, Protocols, | |||
1098 | HasError); | |||
1099 | if (HasError) { | |||
1100 | Diag(Loc, diag::err_invalid_protocol_qualifiers) | |||
1101 | << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); | |||
1102 | if (FailOnError) Result = QualType(); | |||
1103 | } | |||
1104 | if (FailOnError && Result.isNull()) | |||
1105 | return QualType(); | |||
1106 | } | |||
1107 | ||||
1108 | return Result; | |||
1109 | } | |||
1110 | ||||
1111 | TypeResult Sema::actOnObjCProtocolQualifierType( | |||
1112 | SourceLocation lAngleLoc, | |||
1113 | ArrayRef<Decl *> protocols, | |||
1114 | ArrayRef<SourceLocation> protocolLocs, | |||
1115 | SourceLocation rAngleLoc) { | |||
1116 | // Form id<protocol-list>. | |||
1117 | QualType Result = Context.getObjCObjectType( | |||
1118 | Context.ObjCBuiltinIdTy, { }, | |||
1119 | llvm::makeArrayRef( | |||
1120 | (ObjCProtocolDecl * const *)protocols.data(), | |||
1121 | protocols.size()), | |||
1122 | false); | |||
1123 | Result = Context.getObjCObjectPointerType(Result); | |||
1124 | ||||
1125 | TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); | |||
1126 | TypeLoc ResultTL = ResultTInfo->getTypeLoc(); | |||
1127 | ||||
1128 | auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>(); | |||
1129 | ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit | |||
1130 | ||||
1131 | auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc() | |||
1132 | .castAs<ObjCObjectTypeLoc>(); | |||
1133 | ObjCObjectTL.setHasBaseTypeAsWritten(false); | |||
1134 | ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation()); | |||
1135 | ||||
1136 | // No type arguments. | |||
1137 | ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); | |||
1138 | ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); | |||
1139 | ||||
1140 | // Fill in protocol qualifiers. | |||
1141 | ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc); | |||
1142 | ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc); | |||
1143 | for (unsigned i = 0, n = protocols.size(); i != n; ++i) | |||
1144 | ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]); | |||
1145 | ||||
1146 | // We're done. Return the completed type to the parser. | |||
1147 | return CreateParsedType(Result, ResultTInfo); | |||
1148 | } | |||
1149 | ||||
1150 | TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers( | |||
1151 | Scope *S, | |||
1152 | SourceLocation Loc, | |||
1153 | ParsedType BaseType, | |||
1154 | SourceLocation TypeArgsLAngleLoc, | |||
1155 | ArrayRef<ParsedType> TypeArgs, | |||
1156 | SourceLocation TypeArgsRAngleLoc, | |||
1157 | SourceLocation ProtocolLAngleLoc, | |||
1158 | ArrayRef<Decl *> Protocols, | |||
1159 | ArrayRef<SourceLocation> ProtocolLocs, | |||
1160 | SourceLocation ProtocolRAngleLoc) { | |||
1161 | TypeSourceInfo *BaseTypeInfo = nullptr; | |||
1162 | QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo); | |||
1163 | if (T.isNull()) | |||
| ||||
1164 | return true; | |||
1165 | ||||
1166 | // Handle missing type-source info. | |||
1167 | if (!BaseTypeInfo
| |||
1168 | BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc); | |||
1169 | ||||
1170 | // Extract type arguments. | |||
1171 | SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos; | |||
1172 | for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) { | |||
1173 | TypeSourceInfo *TypeArgInfo = nullptr; | |||
1174 | QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo); | |||
1175 | if (TypeArg.isNull()) { | |||
1176 | ActualTypeArgInfos.clear(); | |||
1177 | break; | |||
1178 | } | |||
1179 | ||||
1180 | assert(TypeArgInfo && "No type source info?")(static_cast <bool> (TypeArgInfo && "No type source info?" ) ? void (0) : __assert_fail ("TypeArgInfo && \"No type source info?\"" , "clang/lib/Sema/SemaType.cpp", 1180, __extension__ __PRETTY_FUNCTION__ )); | |||
1181 | ActualTypeArgInfos.push_back(TypeArgInfo); | |||
1182 | } | |||
1183 | ||||
1184 | // Build the object type. | |||
1185 | QualType Result = BuildObjCObjectType( | |||
1186 | T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(), | |||
1187 | TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc, | |||
1188 | ProtocolLAngleLoc, | |||
1189 | llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(), | |||
1190 | Protocols.size()), | |||
1191 | ProtocolLocs, ProtocolRAngleLoc, | |||
1192 | /*FailOnError=*/false); | |||
1193 | ||||
1194 | if (Result == T) | |||
1195 | return BaseType; | |||
1196 | ||||
1197 | // Create source information for this type. | |||
1198 | TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result); | |||
1199 | TypeLoc ResultTL = ResultTInfo->getTypeLoc(); | |||
1200 | ||||
1201 | // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an | |||
1202 | // object pointer type. Fill in source information for it. | |||
1203 | if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) { | |||
1204 | // The '*' is implicit. | |||
1205 | ObjCObjectPointerTL.setStarLoc(SourceLocation()); | |||
1206 | ResultTL = ObjCObjectPointerTL.getPointeeLoc(); | |||
1207 | } | |||
1208 | ||||
1209 | if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) { | |||
1210 | // Protocol qualifier information. | |||
1211 | if (OTPTL.getNumProtocols() > 0) { | |||
1212 | assert(OTPTL.getNumProtocols() == Protocols.size())(static_cast <bool> (OTPTL.getNumProtocols() == Protocols .size()) ? void (0) : __assert_fail ("OTPTL.getNumProtocols() == Protocols.size()" , "clang/lib/Sema/SemaType.cpp", 1212, __extension__ __PRETTY_FUNCTION__ )); | |||
1213 | OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc); | |||
1214 | OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc); | |||
1215 | for (unsigned i = 0, n = Protocols.size(); i != n; ++i) | |||
1216 | OTPTL.setProtocolLoc(i, ProtocolLocs[i]); | |||
1217 | } | |||
1218 | ||||
1219 | // We're done. Return the completed type to the parser. | |||
1220 | return CreateParsedType(Result, ResultTInfo); | |||
1221 | } | |||
1222 | ||||
1223 | auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>(); | |||
1224 | ||||
1225 | // Type argument information. | |||
1226 | if (ObjCObjectTL.getNumTypeArgs() > 0) { | |||
1227 | assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size())(static_cast <bool> (ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos .size()) ? void (0) : __assert_fail ("ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()" , "clang/lib/Sema/SemaType.cpp", 1227, __extension__ __PRETTY_FUNCTION__ )); | |||
1228 | ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc); | |||
1229 | ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc); | |||
1230 | for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i) | |||
1231 | ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]); | |||
1232 | } else { | |||
1233 | ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); | |||
1234 | ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); | |||
1235 | } | |||
1236 | ||||
1237 | // Protocol qualifier information. | |||
1238 | if (ObjCObjectTL.getNumProtocols() > 0) { | |||
1239 | assert(ObjCObjectTL.getNumProtocols() == Protocols.size())(static_cast <bool> (ObjCObjectTL.getNumProtocols() == Protocols .size()) ? void (0) : __assert_fail ("ObjCObjectTL.getNumProtocols() == Protocols.size()" , "clang/lib/Sema/SemaType.cpp", 1239, __extension__ __PRETTY_FUNCTION__ )); | |||
1240 | ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc); | |||
1241 | ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc); | |||
1242 | for (unsigned i = 0, n = Protocols.size(); i != n; ++i) | |||
1243 | ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]); | |||
1244 | } else { | |||
1245 | ObjCObjectTL.setProtocolLAngleLoc(SourceLocation()); | |||
1246 | ObjCObjectTL.setProtocolRAngleLoc(SourceLocation()); | |||
1247 | } | |||
1248 | ||||
1249 | // Base type. | |||
1250 | ObjCObjectTL.setHasBaseTypeAsWritten(true); | |||
1251 | if (ObjCObjectTL.getType() == T) | |||
1252 | ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc()); | |||
1253 | else | |||
1254 | ObjCObjectTL.getBaseLoc().initialize(Context, Loc); | |||
1255 | ||||
1256 | // We're done. Return the completed type to the parser. | |||
1257 | return CreateParsedType(Result, ResultTInfo); | |||
1258 | } | |||
1259 | ||||
1260 | static OpenCLAccessAttr::Spelling | |||
1261 | getImageAccess(const ParsedAttributesView &Attrs) { | |||
1262 | for (const ParsedAttr &AL : Attrs) | |||
1263 | if (AL.getKind() == ParsedAttr::AT_OpenCLAccess) | |||
1264 | return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling()); | |||
1265 | return OpenCLAccessAttr::Keyword_read_only; | |||
1266 | } | |||
1267 | ||||
1268 | /// Convert the specified declspec to the appropriate type | |||
1269 | /// object. | |||
1270 | /// \param state Specifies the declarator containing the declaration specifier | |||
1271 | /// to be converted, along with other associated processing state. | |||
1272 | /// \returns The type described by the declaration specifiers. This function | |||
1273 | /// never returns null. | |||
1274 | static QualType ConvertDeclSpecToType(TypeProcessingState &state) { | |||
1275 | // FIXME: Should move the logic from DeclSpec::Finish to here for validity | |||
1276 | // checking. | |||
1277 | ||||
1278 | Sema &S = state.getSema(); | |||
1279 | Declarator &declarator = state.getDeclarator(); | |||
1280 | DeclSpec &DS = declarator.getMutableDeclSpec(); | |||
1281 | SourceLocation DeclLoc = declarator.getIdentifierLoc(); | |||
1282 | if (DeclLoc.isInvalid()) | |||
1283 | DeclLoc = DS.getBeginLoc(); | |||
1284 | ||||
1285 | ASTContext &Context = S.Context; | |||
1286 | ||||
1287 | QualType Result; | |||
1288 | switch (DS.getTypeSpecType()) { | |||
1289 | case DeclSpec::TST_void: | |||
1290 | Result = Context.VoidTy; | |||
1291 | break; | |||
1292 | case DeclSpec::TST_char: | |||
1293 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified) | |||
1294 | Result = Context.CharTy; | |||
1295 | else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) | |||
1296 | Result = Context.SignedCharTy; | |||
1297 | else { | |||
1298 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unsigned && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1299, __extension__ __PRETTY_FUNCTION__ )) | |||
1299 | "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unsigned && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1299, __extension__ __PRETTY_FUNCTION__ )); | |||
1300 | Result = Context.UnsignedCharTy; | |||
1301 | } | |||
1302 | break; | |||
1303 | case DeclSpec::TST_wchar: | |||
1304 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified) | |||
1305 | Result = Context.WCharTy; | |||
1306 | else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) { | |||
1307 | S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec) | |||
1308 | << DS.getSpecifierName(DS.getTypeSpecType(), | |||
1309 | Context.getPrintingPolicy()); | |||
1310 | Result = Context.getSignedWCharType(); | |||
1311 | } else { | |||
1312 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unsigned && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1313, __extension__ __PRETTY_FUNCTION__ )) | |||
1313 | "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unsigned && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1313, __extension__ __PRETTY_FUNCTION__ )); | |||
1314 | S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec) | |||
1315 | << DS.getSpecifierName(DS.getTypeSpecType(), | |||
1316 | Context.getPrintingPolicy()); | |||
1317 | Result = Context.getUnsignedWCharType(); | |||
1318 | } | |||
1319 | break; | |||
1320 | case DeclSpec::TST_char8: | |||
1321 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1322, __extension__ __PRETTY_FUNCTION__ )) | |||
1322 | "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1322, __extension__ __PRETTY_FUNCTION__ )); | |||
1323 | Result = Context.Char8Ty; | |||
1324 | break; | |||
1325 | case DeclSpec::TST_char16: | |||
1326 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1327, __extension__ __PRETTY_FUNCTION__ )) | |||
1327 | "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1327, __extension__ __PRETTY_FUNCTION__ )); | |||
1328 | Result = Context.Char16Ty; | |||
1329 | break; | |||
1330 | case DeclSpec::TST_char32: | |||
1331 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1332, __extension__ __PRETTY_FUNCTION__ )) | |||
1332 | "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == TypeSpecifierSign ::Unspecified && "Unknown TSS value") ? void (0) : __assert_fail ("DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Unknown TSS value\"" , "clang/lib/Sema/SemaType.cpp", 1332, __extension__ __PRETTY_FUNCTION__ )); | |||
1333 | Result = Context.Char32Ty; | |||
1334 | break; | |||
1335 | case DeclSpec::TST_unspecified: | |||
1336 | // If this is a missing declspec in a block literal return context, then it | |||
1337 | // is inferred from the return statements inside the block. | |||
1338 | // The declspec is always missing in a lambda expr context; it is either | |||
1339 | // specified with a trailing return type or inferred. | |||
1340 | if (S.getLangOpts().CPlusPlus14 && | |||
1341 | declarator.getContext() == DeclaratorContext::LambdaExpr) { | |||
1342 | // In C++1y, a lambda's implicit return type is 'auto'. | |||
1343 | Result = Context.getAutoDeductType(); | |||
1344 | break; | |||
1345 | } else if (declarator.getContext() == DeclaratorContext::LambdaExpr || | |||
1346 | checkOmittedBlockReturnType(S, declarator, | |||
1347 | Context.DependentTy)) { | |||
1348 | Result = Context.DependentTy; | |||
1349 | break; | |||
1350 | } | |||
1351 | ||||
1352 | // Unspecified typespec defaults to int in C90. However, the C90 grammar | |||
1353 | // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, | |||
1354 | // type-qualifier, or storage-class-specifier. If not, emit an extwarn. | |||
1355 | // Note that the one exception to this is function definitions, which are | |||
1356 | // allowed to be completely missing a declspec. This is handled in the | |||
1357 | // parser already though by it pretending to have seen an 'int' in this | |||
1358 | // case. | |||
1359 | if (S.getLangOpts().ImplicitInt) { | |||
1360 | // In C89 mode, we only warn if there is a completely missing declspec | |||
1361 | // when one is not allowed. | |||
1362 | if (DS.isEmpty()) { | |||
1363 | S.Diag(DeclLoc, diag::ext_missing_declspec) | |||
1364 | << DS.getSourceRange() | |||
1365 | << FixItHint::CreateInsertion(DS.getBeginLoc(), "int"); | |||
1366 | } | |||
1367 | } else if (!DS.hasTypeSpecifier()) { | |||
1368 | // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: | |||
1369 | // "At least one type specifier shall be given in the declaration | |||
1370 | // specifiers in each declaration, and in the specifier-qualifier list in | |||
1371 | // each struct declaration and type name." | |||
1372 | if (S.getLangOpts().CPlusPlus && !DS.isTypeSpecPipe()) { | |||
1373 | S.Diag(DeclLoc, diag::err_missing_type_specifier) | |||
1374 | << DS.getSourceRange(); | |||
1375 | ||||
1376 | // When this occurs in C++ code, often something is very broken with the | |||
1377 | // value being declared, poison it as invalid so we don't get chains of | |||
1378 | // errors. | |||
1379 | declarator.setInvalidType(true); | |||
1380 | } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 && | |||
1381 | DS.isTypeSpecPipe()) { | |||
1382 | S.Diag(DeclLoc, diag::err_missing_actual_pipe_type) | |||
1383 | << DS.getSourceRange(); | |||
1384 | declarator.setInvalidType(true); | |||
1385 | } else { | |||
1386 | S.Diag(DeclLoc, diag::ext_missing_type_specifier) | |||
1387 | << DS.getSourceRange(); | |||
1388 | } | |||
1389 | } | |||
1390 | ||||
1391 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
1392 | case DeclSpec::TST_int: { | |||
1393 | if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) { | |||
1394 | switch (DS.getTypeSpecWidth()) { | |||
1395 | case TypeSpecifierWidth::Unspecified: | |||
1396 | Result = Context.IntTy; | |||
1397 | break; | |||
1398 | case TypeSpecifierWidth::Short: | |||
1399 | Result = Context.ShortTy; | |||
1400 | break; | |||
1401 | case TypeSpecifierWidth::Long: | |||
1402 | Result = Context.LongTy; | |||
1403 | break; | |||
1404 | case TypeSpecifierWidth::LongLong: | |||
1405 | Result = Context.LongLongTy; | |||
1406 | ||||
1407 | // 'long long' is a C99 or C++11 feature. | |||
1408 | if (!S.getLangOpts().C99) { | |||
1409 | if (S.getLangOpts().CPlusPlus) | |||
1410 | S.Diag(DS.getTypeSpecWidthLoc(), | |||
1411 | S.getLangOpts().CPlusPlus11 ? | |||
1412 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | |||
1413 | else | |||
1414 | S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); | |||
1415 | } | |||
1416 | break; | |||
1417 | } | |||
1418 | } else { | |||
1419 | switch (DS.getTypeSpecWidth()) { | |||
1420 | case TypeSpecifierWidth::Unspecified: | |||
1421 | Result = Context.UnsignedIntTy; | |||
1422 | break; | |||
1423 | case TypeSpecifierWidth::Short: | |||
1424 | Result = Context.UnsignedShortTy; | |||
1425 | break; | |||
1426 | case TypeSpecifierWidth::Long: | |||
1427 | Result = Context.UnsignedLongTy; | |||
1428 | break; | |||
1429 | case TypeSpecifierWidth::LongLong: | |||
1430 | Result = Context.UnsignedLongLongTy; | |||
1431 | ||||
1432 | // 'long long' is a C99 or C++11 feature. | |||
1433 | if (!S.getLangOpts().C99) { | |||
1434 | if (S.getLangOpts().CPlusPlus) | |||
1435 | S.Diag(DS.getTypeSpecWidthLoc(), | |||
1436 | S.getLangOpts().CPlusPlus11 ? | |||
1437 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); | |||
1438 | else | |||
1439 | S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); | |||
1440 | } | |||
1441 | break; | |||
1442 | } | |||
1443 | } | |||
1444 | break; | |||
1445 | } | |||
1446 | case DeclSpec::TST_bitint: { | |||
1447 | if (!S.Context.getTargetInfo().hasBitIntType()) | |||
1448 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt"; | |||
1449 | Result = | |||
1450 | S.BuildBitIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned, | |||
1451 | DS.getRepAsExpr(), DS.getBeginLoc()); | |||
1452 | if (Result.isNull()) { | |||
1453 | Result = Context.IntTy; | |||
1454 | declarator.setInvalidType(true); | |||
1455 | } | |||
1456 | break; | |||
1457 | } | |||
1458 | case DeclSpec::TST_accum: { | |||
1459 | switch (DS.getTypeSpecWidth()) { | |||
1460 | case TypeSpecifierWidth::Short: | |||
1461 | Result = Context.ShortAccumTy; | |||
1462 | break; | |||
1463 | case TypeSpecifierWidth::Unspecified: | |||
1464 | Result = Context.AccumTy; | |||
1465 | break; | |||
1466 | case TypeSpecifierWidth::Long: | |||
1467 | Result = Context.LongAccumTy; | |||
1468 | break; | |||
1469 | case TypeSpecifierWidth::LongLong: | |||
1470 | llvm_unreachable("Unable to specify long long as _Accum width")::llvm::llvm_unreachable_internal("Unable to specify long long as _Accum width" , "clang/lib/Sema/SemaType.cpp", 1470); | |||
1471 | } | |||
1472 | ||||
1473 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) | |||
1474 | Result = Context.getCorrespondingUnsignedType(Result); | |||
1475 | ||||
1476 | if (DS.isTypeSpecSat()) | |||
1477 | Result = Context.getCorrespondingSaturatedType(Result); | |||
1478 | ||||
1479 | break; | |||
1480 | } | |||
1481 | case DeclSpec::TST_fract: { | |||
1482 | switch (DS.getTypeSpecWidth()) { | |||
1483 | case TypeSpecifierWidth::Short: | |||
1484 | Result = Context.ShortFractTy; | |||
1485 | break; | |||
1486 | case TypeSpecifierWidth::Unspecified: | |||
1487 | Result = Context.FractTy; | |||
1488 | break; | |||
1489 | case TypeSpecifierWidth::Long: | |||
1490 | Result = Context.LongFractTy; | |||
1491 | break; | |||
1492 | case TypeSpecifierWidth::LongLong: | |||
1493 | llvm_unreachable("Unable to specify long long as _Fract width")::llvm::llvm_unreachable_internal("Unable to specify long long as _Fract width" , "clang/lib/Sema/SemaType.cpp", 1493); | |||
1494 | } | |||
1495 | ||||
1496 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) | |||
1497 | Result = Context.getCorrespondingUnsignedType(Result); | |||
1498 | ||||
1499 | if (DS.isTypeSpecSat()) | |||
1500 | Result = Context.getCorrespondingSaturatedType(Result); | |||
1501 | ||||
1502 | break; | |||
1503 | } | |||
1504 | case DeclSpec::TST_int128: | |||
1505 | if (!S.Context.getTargetInfo().hasInt128Type() && | |||
1506 | !(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice || | |||
1507 | (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))) | |||
1508 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | |||
1509 | << "__int128"; | |||
1510 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) | |||
1511 | Result = Context.UnsignedInt128Ty; | |||
1512 | else | |||
1513 | Result = Context.Int128Ty; | |||
1514 | break; | |||
1515 | case DeclSpec::TST_float16: | |||
1516 | // CUDA host and device may have different _Float16 support, therefore | |||
1517 | // do not diagnose _Float16 usage to avoid false alarm. | |||
1518 | // ToDo: more precise diagnostics for CUDA. | |||
1519 | if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA && | |||
1520 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) | |||
1521 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | |||
1522 | << "_Float16"; | |||
1523 | Result = Context.Float16Ty; | |||
1524 | break; | |||
1525 | case DeclSpec::TST_half: Result = Context.HalfTy; break; | |||
1526 | case DeclSpec::TST_BFloat16: | |||
1527 | if (!S.Context.getTargetInfo().hasBFloat16Type()) | |||
1528 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | |||
1529 | << "__bf16"; | |||
1530 | Result = Context.BFloat16Ty; | |||
1531 | break; | |||
1532 | case DeclSpec::TST_float: Result = Context.FloatTy; break; | |||
1533 | case DeclSpec::TST_double: | |||
1534 | if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long) | |||
1535 | Result = Context.LongDoubleTy; | |||
1536 | else | |||
1537 | Result = Context.DoubleTy; | |||
1538 | if (S.getLangOpts().OpenCL) { | |||
1539 | if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts())) | |||
1540 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension) | |||
1541 | << 0 << Result | |||
1542 | << (S.getLangOpts().getOpenCLCompatibleVersion() == 300 | |||
1543 | ? "cl_khr_fp64 and __opencl_c_fp64" | |||
1544 | : "cl_khr_fp64"); | |||
1545 | else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts())) | |||
1546 | S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma); | |||
1547 | } | |||
1548 | break; | |||
1549 | case DeclSpec::TST_float128: | |||
1550 | if (!S.Context.getTargetInfo().hasFloat128Type() && | |||
1551 | !S.getLangOpts().SYCLIsDevice && | |||
1552 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) | |||
1553 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) | |||
1554 | << "__float128"; | |||
1555 | Result = Context.Float128Ty; | |||
1556 | break; | |||
1557 | case DeclSpec::TST_ibm128: | |||
1558 | if (!S.Context.getTargetInfo().hasIbm128Type() && | |||
1559 | !S.getLangOpts().SYCLIsDevice && | |||
1560 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)) | |||
1561 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128"; | |||
1562 | Result = Context.Ibm128Ty; | |||
1563 | break; | |||
1564 | case DeclSpec::TST_bool: | |||
1565 | Result = Context.BoolTy; // _Bool or bool | |||
1566 | break; | |||
1567 | case DeclSpec::TST_decimal32: // _Decimal32 | |||
1568 | case DeclSpec::TST_decimal64: // _Decimal64 | |||
1569 | case DeclSpec::TST_decimal128: // _Decimal128 | |||
1570 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); | |||
1571 | Result = Context.IntTy; | |||
1572 | declarator.setInvalidType(true); | |||
1573 | break; | |||
1574 | case DeclSpec::TST_class: | |||
1575 | case DeclSpec::TST_enum: | |||
1576 | case DeclSpec::TST_union: | |||
1577 | case DeclSpec::TST_struct: | |||
1578 | case DeclSpec::TST_interface: { | |||
1579 | TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl()); | |||
1580 | if (!D) { | |||
1581 | // This can happen in C++ with ambiguous lookups. | |||
1582 | Result = Context.IntTy; | |||
1583 | declarator.setInvalidType(true); | |||
1584 | break; | |||
1585 | } | |||
1586 | ||||
1587 | // If the type is deprecated or unavailable, diagnose it. | |||
1588 | S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); | |||
1589 | ||||
1590 | assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "No qualifiers on tag names!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"No qualifiers on tag names!\"" , "clang/lib/Sema/SemaType.cpp", 1593, __extension__ __PRETTY_FUNCTION__ )) | |||
1591 | DS.getTypeSpecComplex() == 0 &&(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "No qualifiers on tag names!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"No qualifiers on tag names!\"" , "clang/lib/Sema/SemaType.cpp", 1593, __extension__ __PRETTY_FUNCTION__ )) | |||
1592 | DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "No qualifiers on tag names!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"No qualifiers on tag names!\"" , "clang/lib/Sema/SemaType.cpp", 1593, __extension__ __PRETTY_FUNCTION__ )) | |||
1593 | "No qualifiers on tag names!")(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "No qualifiers on tag names!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"No qualifiers on tag names!\"" , "clang/lib/Sema/SemaType.cpp", 1593, __extension__ __PRETTY_FUNCTION__ )); | |||
1594 | ||||
1595 | // TypeQuals handled by caller. | |||
1596 | Result = Context.getTypeDeclType(D); | |||
1597 | ||||
1598 | // In both C and C++, make an ElaboratedType. | |||
1599 | ElaboratedTypeKeyword Keyword | |||
1600 | = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType()); | |||
1601 | Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result, | |||
1602 | DS.isTypeSpecOwned() ? D : nullptr); | |||
1603 | break; | |||
1604 | } | |||
1605 | case DeclSpec::TST_typename: { | |||
1606 | assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Can't handle qualifiers on typedef names yet!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Can't handle qualifiers on typedef names yet!\"" , "clang/lib/Sema/SemaType.cpp", 1609, __extension__ __PRETTY_FUNCTION__ )) | |||
1607 | DS.getTypeSpecComplex() == 0 &&(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Can't handle qualifiers on typedef names yet!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Can't handle qualifiers on typedef names yet!\"" , "clang/lib/Sema/SemaType.cpp", 1609, __extension__ __PRETTY_FUNCTION__ )) | |||
1608 | DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Can't handle qualifiers on typedef names yet!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Can't handle qualifiers on typedef names yet!\"" , "clang/lib/Sema/SemaType.cpp", 1609, __extension__ __PRETTY_FUNCTION__ )) | |||
1609 | "Can't handle qualifiers on typedef names yet!")(static_cast <bool> (DS.getTypeSpecWidth() == TypeSpecifierWidth ::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && "Can't handle qualifiers on typedef names yet!") ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && \"Can't handle qualifiers on typedef names yet!\"" , "clang/lib/Sema/SemaType.cpp", 1609, __extension__ __PRETTY_FUNCTION__ )); | |||
1610 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1611 | if (Result.isNull()) { | |||
1612 | declarator.setInvalidType(true); | |||
1613 | } | |||
1614 | ||||
1615 | // TypeQuals handled by caller. | |||
1616 | break; | |||
1617 | } | |||
1618 | case DeclSpec::TST_typeofType: | |||
1619 | // FIXME: Preserve type source info. | |||
1620 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1621 | assert(!Result.isNull() && "Didn't get a type for typeof?")(static_cast <bool> (!Result.isNull() && "Didn't get a type for typeof?" ) ? void (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for typeof?\"" , "clang/lib/Sema/SemaType.cpp", 1621, __extension__ __PRETTY_FUNCTION__ )); | |||
1622 | if (!Result->isDependentType()) | |||
1623 | if (const TagType *TT = Result->getAs<TagType>()) | |||
1624 | S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); | |||
1625 | // TypeQuals handled by caller. | |||
1626 | Result = Context.getTypeOfType(Result); | |||
1627 | break; | |||
1628 | case DeclSpec::TST_typeofExpr: { | |||
1629 | Expr *E = DS.getRepAsExpr(); | |||
1630 | assert(E && "Didn't get an expression for typeof?")(static_cast <bool> (E && "Didn't get an expression for typeof?" ) ? void (0) : __assert_fail ("E && \"Didn't get an expression for typeof?\"" , "clang/lib/Sema/SemaType.cpp", 1630, __extension__ __PRETTY_FUNCTION__ )); | |||
1631 | // TypeQuals handled by caller. | |||
1632 | Result = S.BuildTypeofExprType(E); | |||
1633 | if (Result.isNull()) { | |||
1634 | Result = Context.IntTy; | |||
1635 | declarator.setInvalidType(true); | |||
1636 | } | |||
1637 | break; | |||
1638 | } | |||
1639 | case DeclSpec::TST_decltype: { | |||
1640 | Expr *E = DS.getRepAsExpr(); | |||
1641 | assert(E && "Didn't get an expression for decltype?")(static_cast <bool> (E && "Didn't get an expression for decltype?" ) ? void (0) : __assert_fail ("E && \"Didn't get an expression for decltype?\"" , "clang/lib/Sema/SemaType.cpp", 1641, __extension__ __PRETTY_FUNCTION__ )); | |||
1642 | // TypeQuals handled by caller. | |||
1643 | Result = S.BuildDecltypeType(E); | |||
1644 | if (Result.isNull()) { | |||
1645 | Result = Context.IntTy; | |||
1646 | declarator.setInvalidType(true); | |||
1647 | } | |||
1648 | break; | |||
1649 | } | |||
1650 | case DeclSpec::TST_underlyingType: | |||
1651 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1652 | assert(!Result.isNull() && "Didn't get a type for __underlying_type?")(static_cast <bool> (!Result.isNull() && "Didn't get a type for __underlying_type?" ) ? void (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for __underlying_type?\"" , "clang/lib/Sema/SemaType.cpp", 1652, __extension__ __PRETTY_FUNCTION__ )); | |||
1653 | Result = S.BuildUnaryTransformType(Result, | |||
1654 | UnaryTransformType::EnumUnderlyingType, | |||
1655 | DS.getTypeSpecTypeLoc()); | |||
1656 | if (Result.isNull()) { | |||
1657 | Result = Context.IntTy; | |||
1658 | declarator.setInvalidType(true); | |||
1659 | } | |||
1660 | break; | |||
1661 | ||||
1662 | case DeclSpec::TST_auto: | |||
1663 | case DeclSpec::TST_decltype_auto: { | |||
1664 | auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto | |||
1665 | ? AutoTypeKeyword::DecltypeAuto | |||
1666 | : AutoTypeKeyword::Auto; | |||
1667 | ||||
1668 | ConceptDecl *TypeConstraintConcept = nullptr; | |||
1669 | llvm::SmallVector<TemplateArgument, 8> TemplateArgs; | |||
1670 | if (DS.isConstrainedAuto()) { | |||
1671 | if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) { | |||
1672 | TypeConstraintConcept = | |||
1673 | cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()); | |||
1674 | TemplateArgumentListInfo TemplateArgsInfo; | |||
1675 | TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc); | |||
1676 | TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc); | |||
1677 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
1678 | TemplateId->NumArgs); | |||
1679 | S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); | |||
1680 | for (const auto &ArgLoc : TemplateArgsInfo.arguments()) | |||
1681 | TemplateArgs.push_back(ArgLoc.getArgument()); | |||
1682 | } else { | |||
1683 | declarator.setInvalidType(true); | |||
1684 | } | |||
1685 | } | |||
1686 | Result = S.Context.getAutoType(QualType(), AutoKW, | |||
1687 | /*IsDependent*/ false, /*IsPack=*/false, | |||
1688 | TypeConstraintConcept, TemplateArgs); | |||
1689 | break; | |||
1690 | } | |||
1691 | ||||
1692 | case DeclSpec::TST_auto_type: | |||
1693 | Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false); | |||
1694 | break; | |||
1695 | ||||
1696 | case DeclSpec::TST_unknown_anytype: | |||
1697 | Result = Context.UnknownAnyTy; | |||
1698 | break; | |||
1699 | ||||
1700 | case DeclSpec::TST_atomic: | |||
1701 | Result = S.GetTypeFromParser(DS.getRepAsType()); | |||
1702 | assert(!Result.isNull() && "Didn't get a type for _Atomic?")(static_cast <bool> (!Result.isNull() && "Didn't get a type for _Atomic?" ) ? void (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for _Atomic?\"" , "clang/lib/Sema/SemaType.cpp", 1702, __extension__ __PRETTY_FUNCTION__ )); | |||
1703 | Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc()); | |||
1704 | if (Result.isNull()) { | |||
1705 | Result = Context.IntTy; | |||
1706 | declarator.setInvalidType(true); | |||
1707 | } | |||
1708 | break; | |||
1709 | ||||
1710 | #define GENERIC_IMAGE_TYPE(ImgType, Id) \ | |||
1711 | case DeclSpec::TST_##ImgType##_t: \ | |||
1712 | switch (getImageAccess(DS.getAttributes())) { \ | |||
1713 | case OpenCLAccessAttr::Keyword_write_only: \ | |||
1714 | Result = Context.Id##WOTy; \ | |||
1715 | break; \ | |||
1716 | case OpenCLAccessAttr::Keyword_read_write: \ | |||
1717 | Result = Context.Id##RWTy; \ | |||
1718 | break; \ | |||
1719 | case OpenCLAccessAttr::Keyword_read_only: \ | |||
1720 | Result = Context.Id##ROTy; \ | |||
1721 | break; \ | |||
1722 | case OpenCLAccessAttr::SpellingNotCalculated: \ | |||
1723 | llvm_unreachable("Spelling not yet calculated")::llvm::llvm_unreachable_internal("Spelling not yet calculated" , "clang/lib/Sema/SemaType.cpp", 1723); \ | |||
1724 | } \ | |||
1725 | break; | |||
1726 | #include "clang/Basic/OpenCLImageTypes.def" | |||
1727 | ||||
1728 | case DeclSpec::TST_error: | |||
1729 | Result = Context.IntTy; | |||
1730 | declarator.setInvalidType(true); | |||
1731 | break; | |||
1732 | } | |||
1733 | ||||
1734 | // FIXME: we want resulting declarations to be marked invalid, but claiming | |||
1735 | // the type is invalid is too strong - e.g. it causes ActOnTypeName to return | |||
1736 | // a null type. | |||
1737 | if (Result->containsErrors()) | |||
1738 | declarator.setInvalidType(); | |||
1739 | ||||
1740 | if (S.getLangOpts().OpenCL) { | |||
1741 | const auto &OpenCLOptions = S.getOpenCLOptions(); | |||
1742 | bool IsOpenCLC30Compatible = | |||
1743 | S.getLangOpts().getOpenCLCompatibleVersion() == 300; | |||
1744 | // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images | |||
1745 | // support. | |||
1746 | // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support | |||
1747 | // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the | |||
1748 | // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices | |||
1749 | // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and | |||
1750 | // only when the optional feature is supported | |||
1751 | if ((Result->isImageType() || Result->isSamplerT()) && | |||
1752 | (IsOpenCLC30Compatible && | |||
1753 | !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) { | |||
1754 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension) | |||
1755 | << 0 << Result << "__opencl_c_images"; | |||
1756 | declarator.setInvalidType(); | |||
1757 | } else if (Result->isOCLImage3dWOType() && | |||
1758 | !OpenCLOptions.isSupported("cl_khr_3d_image_writes", | |||
1759 | S.getLangOpts())) { | |||
1760 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension) | |||
1761 | << 0 << Result | |||
1762 | << (IsOpenCLC30Compatible | |||
1763 | ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes" | |||
1764 | : "cl_khr_3d_image_writes"); | |||
1765 | declarator.setInvalidType(); | |||
1766 | } | |||
1767 | } | |||
1768 | ||||
1769 | bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum || | |||
1770 | DS.getTypeSpecType() == DeclSpec::TST_fract; | |||
1771 | ||||
1772 | // Only fixed point types can be saturated | |||
1773 | if (DS.isTypeSpecSat() && !IsFixedPointType) | |||
1774 | S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec) | |||
1775 | << DS.getSpecifierName(DS.getTypeSpecType(), | |||
1776 | Context.getPrintingPolicy()); | |||
1777 | ||||
1778 | // Handle complex types. | |||
1779 | if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { | |||
1780 | if (S.getLangOpts().Freestanding) | |||
1781 | S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); | |||
1782 | Result = Context.getComplexType(Result); | |||
1783 | } else if (DS.isTypeAltiVecVector()) { | |||
1784 | unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); | |||
1785 | assert(typeSize > 0 && "type size for vector must be greater than 0 bits")(static_cast <bool> (typeSize > 0 && "type size for vector must be greater than 0 bits" ) ? void (0) : __assert_fail ("typeSize > 0 && \"type size for vector must be greater than 0 bits\"" , "clang/lib/Sema/SemaType.cpp", 1785, __extension__ __PRETTY_FUNCTION__ )); | |||
1786 | VectorType::VectorKind VecKind = VectorType::AltiVecVector; | |||
1787 | if (DS.isTypeAltiVecPixel()) | |||
1788 | VecKind = VectorType::AltiVecPixel; | |||
1789 | else if (DS.isTypeAltiVecBool()) | |||
1790 | VecKind = VectorType::AltiVecBool; | |||
1791 | Result = Context.getVectorType(Result, 128/typeSize, VecKind); | |||
1792 | } | |||
1793 | ||||
1794 | // FIXME: Imaginary. | |||
1795 | if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) | |||
1796 | S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); | |||
1797 | ||||
1798 | // Before we process any type attributes, synthesize a block literal | |||
1799 | // function declarator if necessary. | |||
1800 | if (declarator.getContext() == DeclaratorContext::BlockLiteral) | |||
1801 | maybeSynthesizeBlockSignature(state, Result); | |||
1802 | ||||
1803 | // Apply any type attributes from the decl spec. This may cause the | |||
1804 | // list of type attributes to be temporarily saved while the type | |||
1805 | // attributes are pushed around. | |||
1806 | // pipe attributes will be handled later ( at GetFullTypeForDeclarator ) | |||
1807 | if (!DS.isTypeSpecPipe()) | |||
1808 | processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes()); | |||
1809 | ||||
1810 | // Apply const/volatile/restrict qualifiers to T. | |||
1811 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { | |||
1812 | // Warn about CV qualifiers on function types. | |||
1813 | // C99 6.7.3p8: | |||
1814 | // If the specification of a function type includes any type qualifiers, | |||
1815 | // the behavior is undefined. | |||
1816 | // C++11 [dcl.fct]p7: | |||
1817 | // The effect of a cv-qualifier-seq in a function declarator is not the | |||
1818 | // same as adding cv-qualification on top of the function type. In the | |||
1819 | // latter case, the cv-qualifiers are ignored. | |||
1820 | if (Result->isFunctionType()) { | |||
1821 | diagnoseAndRemoveTypeQualifiers( | |||
1822 | S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile, | |||
1823 | S.getLangOpts().CPlusPlus | |||
1824 | ? diag::warn_typecheck_function_qualifiers_ignored | |||
1825 | : diag::warn_typecheck_function_qualifiers_unspecified); | |||
1826 | // No diagnostic for 'restrict' or '_Atomic' applied to a | |||
1827 | // function type; we'll diagnose those later, in BuildQualifiedType. | |||
1828 | } | |||
1829 | ||||
1830 | // C++11 [dcl.ref]p1: | |||
1831 | // Cv-qualified references are ill-formed except when the | |||
1832 | // cv-qualifiers are introduced through the use of a typedef-name | |||
1833 | // or decltype-specifier, in which case the cv-qualifiers are ignored. | |||
1834 | // | |||
1835 | // There don't appear to be any other contexts in which a cv-qualified | |||
1836 | // reference type could be formed, so the 'ill-formed' clause here appears | |||
1837 | // to never happen. | |||
1838 | if (TypeQuals && Result->isReferenceType()) { | |||
1839 | diagnoseAndRemoveTypeQualifiers( | |||
1840 | S, DS, TypeQuals, Result, | |||
1841 | DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic, | |||
1842 | diag::warn_typecheck_reference_qualifiers); | |||
1843 | } | |||
1844 | ||||
1845 | // C90 6.5.3 constraints: "The same type qualifier shall not appear more | |||
1846 | // than once in the same specifier-list or qualifier-list, either directly | |||
1847 | // or via one or more typedefs." | |||
1848 | if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus | |||
1849 | && TypeQuals & Result.getCVRQualifiers()) { | |||
1850 | if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { | |||
1851 | S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) | |||
1852 | << "const"; | |||
1853 | } | |||
1854 | ||||
1855 | if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { | |||
1856 | S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) | |||
1857 | << "volatile"; | |||
1858 | } | |||
1859 | ||||
1860 | // C90 doesn't have restrict nor _Atomic, so it doesn't force us to | |||
1861 | // produce a warning in this case. | |||
1862 | } | |||
1863 | ||||
1864 | QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS); | |||
1865 | ||||
1866 | // If adding qualifiers fails, just use the unqualified type. | |||
1867 | if (Qualified.isNull()) | |||
1868 | declarator.setInvalidType(true); | |||
1869 | else | |||
1870 | Result = Qualified; | |||
1871 | } | |||
1872 | ||||
1873 | assert(!Result.isNull() && "This function should not return a null type")(static_cast <bool> (!Result.isNull() && "This function should not return a null type" ) ? void (0) : __assert_fail ("!Result.isNull() && \"This function should not return a null type\"" , "clang/lib/Sema/SemaType.cpp", 1873, __extension__ __PRETTY_FUNCTION__ )); | |||
1874 | return Result; | |||
1875 | } | |||
1876 | ||||
1877 | static std::string getPrintableNameForEntity(DeclarationName Entity) { | |||
1878 | if (Entity) | |||
1879 | return Entity.getAsString(); | |||
1880 | ||||
1881 | return "type name"; | |||
1882 | } | |||
1883 | ||||
1884 | static bool isDependentOrGNUAutoType(QualType T) { | |||
1885 | if (T->isDependentType()) | |||
1886 | return true; | |||
1887 | ||||
1888 | const auto *AT = dyn_cast<AutoType>(T); | |||
1889 | return AT && AT->isGNUAutoType(); | |||
1890 | } | |||
1891 | ||||
1892 | QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, | |||
1893 | Qualifiers Qs, const DeclSpec *DS) { | |||
1894 | if (T.isNull()) | |||
1895 | return QualType(); | |||
1896 | ||||
1897 | // Ignore any attempt to form a cv-qualified reference. | |||
1898 | if (T->isReferenceType()) { | |||
1899 | Qs.removeConst(); | |||
1900 | Qs.removeVolatile(); | |||
1901 | } | |||
1902 | ||||
1903 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from | |||
1904 | // object or incomplete types shall not be restrict-qualified." | |||
1905 | if (Qs.hasRestrict()) { | |||
1906 | unsigned DiagID = 0; | |||
1907 | QualType ProblemTy; | |||
1908 | ||||
1909 | if (T->isAnyPointerType() || T->isReferenceType() || | |||
1910 | T->isMemberPointerType()) { | |||
1911 | QualType EltTy; | |||
1912 | if (T->isObjCObjectPointerType()) | |||
1913 | EltTy = T; | |||
1914 | else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) | |||
1915 | EltTy = PTy->getPointeeType(); | |||
1916 | else | |||
1917 | EltTy = T->getPointeeType(); | |||
1918 | ||||
1919 | // If we have a pointer or reference, the pointee must have an object | |||
1920 | // incomplete type. | |||
1921 | if (!EltTy->isIncompleteOrObjectType()) { | |||
1922 | DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; | |||
1923 | ProblemTy = EltTy; | |||
1924 | } | |||
1925 | } else if (!isDependentOrGNUAutoType(T)) { | |||
1926 | // For an __auto_type variable, we may not have seen the initializer yet | |||
1927 | // and so have no idea whether the underlying type is a pointer type or | |||
1928 | // not. | |||
1929 | DiagID = diag::err_typecheck_invalid_restrict_not_pointer; | |||
1930 | ProblemTy = T; | |||
1931 | } | |||
1932 | ||||
1933 | if (DiagID) { | |||
1934 | Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; | |||
1935 | Qs.removeRestrict(); | |||
1936 | } | |||
1937 | } | |||
1938 | ||||
1939 | return Context.getQualifiedType(T, Qs); | |||
1940 | } | |||
1941 | ||||
1942 | QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, | |||
1943 | unsigned CVRAU, const DeclSpec *DS) { | |||
1944 | if (T.isNull()) | |||
1945 | return QualType(); | |||
1946 | ||||
1947 | // Ignore any attempt to form a cv-qualified reference. | |||
1948 | if (T->isReferenceType()) | |||
1949 | CVRAU &= | |||
1950 | ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic); | |||
1951 | ||||
1952 | // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and | |||
1953 | // TQ_unaligned; | |||
1954 | unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned); | |||
1955 | ||||
1956 | // C11 6.7.3/5: | |||
1957 | // If the same qualifier appears more than once in the same | |||
1958 | // specifier-qualifier-list, either directly or via one or more typedefs, | |||
1959 | // the behavior is the same as if it appeared only once. | |||
1960 | // | |||
1961 | // It's not specified what happens when the _Atomic qualifier is applied to | |||
1962 | // a type specified with the _Atomic specifier, but we assume that this | |||
1963 | // should be treated as if the _Atomic qualifier appeared multiple times. | |||
1964 | if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) { | |||
1965 | // C11 6.7.3/5: | |||
1966 | // If other qualifiers appear along with the _Atomic qualifier in a | |||
1967 | // specifier-qualifier-list, the resulting type is the so-qualified | |||
1968 | // atomic type. | |||
1969 | // | |||
1970 | // Don't need to worry about array types here, since _Atomic can't be | |||
1971 | // applied to such types. | |||
1972 | SplitQualType Split = T.getSplitUnqualifiedType(); | |||
1973 | T = BuildAtomicType(QualType(Split.Ty, 0), | |||
1974 | DS ? DS->getAtomicSpecLoc() : Loc); | |||
1975 | if (T.isNull()) | |||
1976 | return T; | |||
1977 | Split.Quals.addCVRQualifiers(CVR); | |||
1978 | return BuildQualifiedType(T, Loc, Split.Quals); | |||
1979 | } | |||
1980 | ||||
1981 | Qualifiers Q = Qualifiers::fromCVRMask(CVR); | |||
1982 | Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned); | |||
1983 | return BuildQualifiedType(T, Loc, Q, DS); | |||
1984 | } | |||
1985 | ||||
1986 | /// Build a paren type including \p T. | |||
1987 | QualType Sema::BuildParenType(QualType T) { | |||
1988 | return Context.getParenType(T); | |||
1989 | } | |||
1990 | ||||
1991 | /// Given that we're building a pointer or reference to the given | |||
1992 | static QualType inferARCLifetimeForPointee(Sema &S, QualType type, | |||
1993 | SourceLocation loc, | |||
1994 | bool isReference) { | |||
1995 | // Bail out if retention is unrequired or already specified. | |||
1996 | if (!type->isObjCLifetimeType() || | |||
1997 | type.getObjCLifetime() != Qualifiers::OCL_None) | |||
1998 | return type; | |||
1999 | ||||
2000 | Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; | |||
2001 | ||||
2002 | // If the object type is const-qualified, we can safely use | |||
2003 | // __unsafe_unretained. This is safe (because there are no read | |||
2004 | // barriers), and it'll be safe to coerce anything but __weak* to | |||
2005 | // the resulting type. | |||
2006 | if (type.isConstQualified()) { | |||
2007 | implicitLifetime = Qualifiers::OCL_ExplicitNone; | |||
2008 | ||||
2009 | // Otherwise, check whether the static type does not require | |||
2010 | // retaining. This currently only triggers for Class (possibly | |||
2011 | // protocol-qualifed, and arrays thereof). | |||
2012 | } else if (type->isObjCARCImplicitlyUnretainedType()) { | |||
2013 | implicitLifetime = Qualifiers::OCL_ExplicitNone; | |||
2014 | ||||
2015 | // If we are in an unevaluated context, like sizeof, skip adding a | |||
2016 | // qualification. | |||
2017 | } else if (S.isUnevaluatedContext()) { | |||
2018 | return type; | |||
2019 | ||||
2020 | // If that failed, give an error and recover using __strong. __strong | |||
2021 | // is the option most likely to prevent spurious second-order diagnostics, | |||
2022 | // like when binding a reference to a field. | |||
2023 | } else { | |||
2024 | // These types can show up in private ivars in system headers, so | |||
2025 | // we need this to not be an error in those cases. Instead we | |||
2026 | // want to delay. | |||
2027 | if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { | |||
2028 | S.DelayedDiagnostics.add( | |||
2029 | sema::DelayedDiagnostic::makeForbiddenType(loc, | |||
2030 | diag::err_arc_indirect_no_ownership, type, isReference)); | |||
2031 | } else { | |||
2032 | S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; | |||
2033 | } | |||
2034 | implicitLifetime = Qualifiers::OCL_Strong; | |||
2035 | } | |||
2036 | assert(implicitLifetime && "didn't infer any lifetime!")(static_cast <bool> (implicitLifetime && "didn't infer any lifetime!" ) ? void (0) : __assert_fail ("implicitLifetime && \"didn't infer any lifetime!\"" , "clang/lib/Sema/SemaType.cpp", 2036, __extension__ __PRETTY_FUNCTION__ )); | |||
2037 | ||||
2038 | Qualifiers qs; | |||
2039 | qs.addObjCLifetime(implicitLifetime); | |||
2040 | return S.Context.getQualifiedType(type, qs); | |||
2041 | } | |||
2042 | ||||
2043 | static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ | |||
2044 | std::string Quals = FnTy->getMethodQuals().getAsString(); | |||
2045 | ||||
2046 | switch (FnTy->getRefQualifier()) { | |||
2047 | case RQ_None: | |||
2048 | break; | |||
2049 | ||||
2050 | case RQ_LValue: | |||
2051 | if (!Quals.empty()) | |||
2052 | Quals += ' '; | |||
2053 | Quals += '&'; | |||
2054 | break; | |||
2055 | ||||
2056 | case RQ_RValue: | |||
2057 | if (!Quals.empty()) | |||
2058 | Quals += ' '; | |||
2059 | Quals += "&&"; | |||
2060 | break; | |||
2061 | } | |||
2062 | ||||
2063 | return Quals; | |||
2064 | } | |||
2065 | ||||
2066 | namespace { | |||
2067 | /// Kinds of declarator that cannot contain a qualified function type. | |||
2068 | /// | |||
2069 | /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: | |||
2070 | /// a function type with a cv-qualifier or a ref-qualifier can only appear | |||
2071 | /// at the topmost level of a type. | |||
2072 | /// | |||
2073 | /// Parens and member pointers are permitted. We don't diagnose array and | |||
2074 | /// function declarators, because they don't allow function types at all. | |||
2075 | /// | |||
2076 | /// The values of this enum are used in diagnostics. | |||
2077 | enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference }; | |||
2078 | } // end anonymous namespace | |||
2079 | ||||
2080 | /// Check whether the type T is a qualified function type, and if it is, | |||
2081 | /// diagnose that it cannot be contained within the given kind of declarator. | |||
2082 | static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, | |||
2083 | QualifiedFunctionKind QFK) { | |||
2084 | // Does T refer to a function type with a cv-qualifier or a ref-qualifier? | |||
2085 | const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); | |||
2086 | if (!FPT || | |||
2087 | (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None)) | |||
2088 | return false; | |||
2089 | ||||
2090 | S.Diag(Loc, diag::err_compound_qualified_function_type) | |||
2091 | << QFK << isa<FunctionType>(T.IgnoreParens()) << T | |||
2092 | << getFunctionQualifiersAsString(FPT); | |||
2093 | return true; | |||
2094 | } | |||
2095 | ||||
2096 | bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) { | |||
2097 | const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); | |||
2098 | if (!FPT || | |||
2099 | (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None)) | |||
2100 | return false; | |||
2101 | ||||
2102 | Diag(Loc, diag::err_qualified_function_typeid) | |||
2103 | << T << getFunctionQualifiersAsString(FPT); | |||
2104 | return true; | |||
2105 | } | |||
2106 | ||||
2107 | // Helper to deduce addr space of a pointee type in OpenCL mode. | |||
2108 | static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) { | |||
2109 | if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() && | |||
2110 | !PointeeType->isSamplerT() && | |||
2111 | !PointeeType.hasAddressSpace()) | |||
2112 | PointeeType = S.getASTContext().getAddrSpaceQualType( | |||
2113 | PointeeType, S.getASTContext().getDefaultOpenCLPointeeAddrSpace()); | |||
2114 | return PointeeType; | |||
2115 | } | |||
2116 | ||||
2117 | /// Build a pointer type. | |||
2118 | /// | |||
2119 | /// \param T The type to which we'll be building a pointer. | |||
2120 | /// | |||
2121 | /// \param Loc The location of the entity whose type involves this | |||
2122 | /// pointer type or, if there is no such entity, the location of the | |||
2123 | /// type that will have pointer type. | |||
2124 | /// | |||
2125 | /// \param Entity The name of the entity that involves the pointer | |||
2126 | /// type, if known. | |||
2127 | /// | |||
2128 | /// \returns A suitable pointer type, if there are no | |||
2129 | /// errors. Otherwise, returns a NULL type. | |||
2130 | QualType Sema::BuildPointerType(QualType T, | |||
2131 | SourceLocation Loc, DeclarationName Entity) { | |||
2132 | if (T->isReferenceType()) { | |||
2133 | // C++ 8.3.2p4: There shall be no ... pointers to references ... | |||
2134 | Diag(Loc, diag::err_illegal_decl_pointer_to_reference) | |||
2135 | << getPrintableNameForEntity(Entity) << T; | |||
2136 | return QualType(); | |||
2137 | } | |||
2138 | ||||
2139 | if (T->isFunctionType() && getLangOpts().OpenCL && | |||
2140 | !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", | |||
2141 | getLangOpts())) { | |||
2142 | Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0; | |||
2143 | return QualType(); | |||
2144 | } | |||
2145 | ||||
2146 | if (getLangOpts().HLSL) { | |||
2147 | Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0; | |||
2148 | return QualType(); | |||
2149 | } | |||
2150 | ||||
2151 | if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer)) | |||
2152 | return QualType(); | |||
2153 | ||||
2154 | assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType")(static_cast <bool> (!T->isObjCObjectType() && "Should build ObjCObjectPointerType") ? void (0) : __assert_fail ("!T->isObjCObjectType() && \"Should build ObjCObjectPointerType\"" , "clang/lib/Sema/SemaType.cpp", 2154, __extension__ __PRETTY_FUNCTION__ )); | |||
2155 | ||||
2156 | // In ARC, it is forbidden to build pointers to unqualified pointers. | |||
2157 | if (getLangOpts().ObjCAutoRefCount) | |||
2158 | T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false); | |||
2159 | ||||
2160 | if (getLangOpts().OpenCL) | |||
2161 | T = deduceOpenCLPointeeAddrSpace(*this, T); | |||
2162 | ||||
2163 | // Build the pointer type. | |||
2164 | return Context.getPointerType(T); | |||
2165 | } | |||
2166 | ||||
2167 | /// Build a reference type. | |||
2168 | /// | |||
2169 | /// \param T The type to which we'll be building a reference. | |||
2170 | /// | |||
2171 | /// \param Loc The location of the entity whose type involves this | |||
2172 | /// reference type or, if there is no such entity, the location of the | |||
2173 | /// type that will have reference type. | |||
2174 | /// | |||
2175 | /// \param Entity The name of the entity that involves the reference | |||
2176 | /// type, if known. | |||
2177 | /// | |||
2178 | /// \returns A suitable reference type, if there are no | |||
2179 | /// errors. Otherwise, returns a NULL type. | |||
2180 | QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, | |||
2181 | SourceLocation Loc, | |||
2182 | DeclarationName Entity) { | |||
2183 | assert(Context.getCanonicalType(T) != Context.OverloadTy &&(static_cast <bool> (Context.getCanonicalType(T) != Context .OverloadTy && "Unresolved overloaded function type") ? void (0) : __assert_fail ("Context.getCanonicalType(T) != Context.OverloadTy && \"Unresolved overloaded function type\"" , "clang/lib/Sema/SemaType.cpp", 2184, __extension__ __PRETTY_FUNCTION__ )) | |||
2184 | "Unresolved overloaded function type")(static_cast <bool> (Context.getCanonicalType(T) != Context .OverloadTy && "Unresolved overloaded function type") ? void (0) : __assert_fail ("Context.getCanonicalType(T) != Context.OverloadTy && \"Unresolved overloaded function type\"" , "clang/lib/Sema/SemaType.cpp", 2184, __extension__ __PRETTY_FUNCTION__ )); | |||
2185 | ||||
2186 | // C++0x [dcl.ref]p6: | |||
2187 | // If a typedef (7.1.3), a type template-parameter (14.3.1), or a | |||
2188 | // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a | |||
2189 | // type T, an attempt to create the type "lvalue reference to cv TR" creates | |||
2190 | // the type "lvalue reference to T", while an attempt to create the type | |||
2191 | // "rvalue reference to cv TR" creates the type TR. | |||
2192 | bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); | |||
2193 | ||||
2194 | // C++ [dcl.ref]p4: There shall be no references to references. | |||
2195 | // | |||
2196 | // According to C++ DR 106, references to references are only | |||
2197 | // diagnosed when they are written directly (e.g., "int & &"), | |||
2198 | // but not when they happen via a typedef: | |||
2199 | // | |||
2200 | // typedef int& intref; | |||
2201 | // typedef intref& intref2; | |||
2202 | // | |||
2203 | // Parser::ParseDeclaratorInternal diagnoses the case where | |||
2204 | // references are written directly; here, we handle the | |||
2205 | // collapsing of references-to-references as described in C++0x. | |||
2206 | // DR 106 and 540 introduce reference-collapsing into C++98/03. | |||
2207 | ||||
2208 | // C++ [dcl.ref]p1: | |||
2209 | // A declarator that specifies the type "reference to cv void" | |||
2210 | // is ill-formed. | |||
2211 | if (T->isVoidType()) { | |||
2212 | Diag(Loc, diag::err_reference_to_void); | |||
2213 | return QualType(); | |||
2214 | } | |||
2215 | ||||
2216 | if (getLangOpts().HLSL) { | |||
2217 | Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1; | |||
2218 | return QualType(); | |||
2219 | } | |||
2220 | ||||
2221 | if (checkQualifiedFunction(*this, T, Loc, QFK_Reference)) | |||
2222 | return QualType(); | |||
2223 | ||||
2224 | if (T->isFunctionType() && getLangOpts().OpenCL && | |||
2225 | !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", | |||
2226 | getLangOpts())) { | |||
2227 | Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1; | |||
2228 | return QualType(); | |||
2229 | } | |||
2230 | ||||
2231 | // In ARC, it is forbidden to build references to unqualified pointers. | |||
2232 | if (getLangOpts().ObjCAutoRefCount) | |||
2233 | T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true); | |||
2234 | ||||
2235 | if (getLangOpts().OpenCL) | |||
2236 | T = deduceOpenCLPointeeAddrSpace(*this, T); | |||
2237 | ||||
2238 | // Handle restrict on references. | |||
2239 | if (LValueRef) | |||
2240 | return Context.getLValueReferenceType(T, SpelledAsLValue); | |||
2241 | return Context.getRValueReferenceType(T); | |||
2242 | } | |||
2243 | ||||
2244 | /// Build a Read-only Pipe type. | |||
2245 | /// | |||
2246 | /// \param T The type to which we'll be building a Pipe. | |||
2247 | /// | |||
2248 | /// \param Loc We do not use it for now. | |||
2249 | /// | |||
2250 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a | |||
2251 | /// NULL type. | |||
2252 | QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) { | |||
2253 | return Context.getReadPipeType(T); | |||
2254 | } | |||
2255 | ||||
2256 | /// Build a Write-only Pipe type. | |||
2257 | /// | |||
2258 | /// \param T The type to which we'll be building a Pipe. | |||
2259 | /// | |||
2260 | /// \param Loc We do not use it for now. | |||
2261 | /// | |||
2262 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a | |||
2263 | /// NULL type. | |||
2264 | QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) { | |||
2265 | return Context.getWritePipeType(T); | |||
2266 | } | |||
2267 | ||||
2268 | /// Build a bit-precise integer type. | |||
2269 | /// | |||
2270 | /// \param IsUnsigned Boolean representing the signedness of the type. | |||
2271 | /// | |||
2272 | /// \param BitWidth Size of this int type in bits, or an expression representing | |||
2273 | /// that. | |||
2274 | /// | |||
2275 | /// \param Loc Location of the keyword. | |||
2276 | QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth, | |||
2277 | SourceLocation Loc) { | |||
2278 | if (BitWidth->isInstantiationDependent()) | |||
2279 | return Context.getDependentBitIntType(IsUnsigned, BitWidth); | |||
2280 | ||||
2281 | llvm::APSInt Bits(32); | |||
2282 | ExprResult ICE = | |||
2283 | VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold); | |||
2284 | ||||
2285 | if (ICE.isInvalid()) | |||
2286 | return QualType(); | |||
2287 | ||||
2288 | size_t NumBits = Bits.getZExtValue(); | |||
2289 | if (!IsUnsigned && NumBits < 2) { | |||
2290 | Diag(Loc, diag::err_bit_int_bad_size) << 0; | |||
2291 | return QualType(); | |||
2292 | } | |||
2293 | ||||
2294 | if (IsUnsigned && NumBits < 1) { | |||
2295 | Diag(Loc, diag::err_bit_int_bad_size) << 1; | |||
2296 | return QualType(); | |||
2297 | } | |||
2298 | ||||
2299 | const TargetInfo &TI = getASTContext().getTargetInfo(); | |||
2300 | if (NumBits > TI.getMaxBitIntWidth()) { | |||
2301 | Diag(Loc, diag::err_bit_int_max_size) | |||
2302 | << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth()); | |||
2303 | return QualType(); | |||
2304 | } | |||
2305 | ||||
2306 | return Context.getBitIntType(IsUnsigned, NumBits); | |||
2307 | } | |||
2308 | ||||
2309 | /// Check whether the specified array bound can be evaluated using the relevant | |||
2310 | /// language rules. If so, returns the possibly-converted expression and sets | |||
2311 | /// SizeVal to the size. If not, but the expression might be a VLA bound, | |||
2312 | /// returns ExprResult(). Otherwise, produces a diagnostic and returns | |||
2313 | /// ExprError(). | |||
2314 | static ExprResult checkArraySize(Sema &S, Expr *&ArraySize, | |||
2315 | llvm::APSInt &SizeVal, unsigned VLADiag, | |||
2316 | bool VLAIsError) { | |||
2317 | if (S.getLangOpts().CPlusPlus14 && | |||
2318 | (VLAIsError || | |||
2319 | !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) { | |||
2320 | // C++14 [dcl.array]p1: | |||
2321 | // The constant-expression shall be a converted constant expression of | |||
2322 | // type std::size_t. | |||
2323 | // | |||
2324 | // Don't apply this rule if we might be forming a VLA: in that case, we | |||
2325 | // allow non-constant expressions and constant-folding. We only need to use | |||
2326 | // the converted constant expression rules (to properly convert the source) | |||
2327 | // when the source expression is of class type. | |||
2328 | return S.CheckConvertedConstantExpression( | |||
2329 | ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound); | |||
2330 | } | |||
2331 | ||||
2332 | // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode | |||
2333 | // (like gnu99, but not c99) accept any evaluatable value as an extension. | |||
2334 | class VLADiagnoser : public Sema::VerifyICEDiagnoser { | |||
2335 | public: | |||
2336 | unsigned VLADiag; | |||
2337 | bool VLAIsError; | |||
2338 | bool IsVLA = false; | |||
2339 | ||||
2340 | VLADiagnoser(unsigned VLADiag, bool VLAIsError) | |||
2341 | : VLADiag(VLADiag), VLAIsError(VLAIsError) {} | |||
2342 | ||||
2343 | Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, | |||
2344 | QualType T) override { | |||
2345 | return S.Diag(Loc, diag::err_array_size_non_int) << T; | |||
2346 | } | |||
2347 | ||||
2348 | Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, | |||
2349 | SourceLocation Loc) override { | |||
2350 | IsVLA = !VLAIsError; | |||
2351 | return S.Diag(Loc, VLADiag); | |||
2352 | } | |||
2353 | ||||
2354 | Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S, | |||
2355 | SourceLocation Loc) override { | |||
2356 | return S.Diag(Loc, diag::ext_vla_folded_to_constant); | |||
2357 | } | |||
2358 | } Diagnoser(VLADiag, VLAIsError); | |||
2359 | ||||
2360 | ExprResult R = | |||
2361 | S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser); | |||
2362 | if (Diagnoser.IsVLA) | |||
2363 | return ExprResult(); | |||
2364 | return R; | |||
2365 | } | |||
2366 | ||||
2367 | /// Build an array type. | |||
2368 | /// | |||
2369 | /// \param T The type of each element in the array. | |||
2370 | /// | |||
2371 | /// \param ASM C99 array size modifier (e.g., '*', 'static'). | |||
2372 | /// | |||
2373 | /// \param ArraySize Expression describing the size of the array. | |||
2374 | /// | |||
2375 | /// \param Brackets The range from the opening '[' to the closing ']'. | |||
2376 | /// | |||
2377 | /// \param Entity The name of the entity that involves the array | |||
2378 | /// type, if known. | |||
2379 | /// | |||
2380 | /// \returns A suitable array type, if there are no errors. Otherwise, | |||
2381 | /// returns a NULL type. | |||
2382 | QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, | |||
2383 | Expr *ArraySize, unsigned Quals, | |||
2384 | SourceRange Brackets, DeclarationName Entity) { | |||
2385 | ||||
2386 | SourceLocation Loc = Brackets.getBegin(); | |||
2387 | if (getLangOpts().CPlusPlus) { | |||
2388 | // C++ [dcl.array]p1: | |||
2389 | // T is called the array element type; this type shall not be a reference | |||
2390 | // type, the (possibly cv-qualified) type void, a function type or an | |||
2391 | // abstract class type. | |||
2392 | // | |||
2393 | // C++ [dcl.array]p3: | |||
2394 | // When several "array of" specifications are adjacent, [...] only the | |||
2395 | // first of the constant expressions that specify the bounds of the arrays | |||
2396 | // may be omitted. | |||
2397 | // | |||
2398 | // Note: function types are handled in the common path with C. | |||
2399 | if (T->isReferenceType()) { | |||
2400 | Diag(Loc, diag::err_illegal_decl_array_of_references) | |||
2401 | << getPrintableNameForEntity(Entity) << T; | |||
2402 | return QualType(); | |||
2403 | } | |||
2404 | ||||
2405 | if (T->isVoidType() || T->isIncompleteArrayType()) { | |||
2406 | Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T; | |||
2407 | return QualType(); | |||
2408 | } | |||
2409 | ||||
2410 | if (RequireNonAbstractType(Brackets.getBegin(), T, | |||
2411 | diag::err_array_of_abstract_type)) | |||
2412 | return QualType(); | |||
2413 | ||||
2414 | // Mentioning a member pointer type for an array type causes us to lock in | |||
2415 | // an inheritance model, even if it's inside an unused typedef. | |||
2416 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
2417 | if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) | |||
2418 | if (!MPTy->getClass()->isDependentType()) | |||
2419 | (void)isCompleteType(Loc, T); | |||
2420 | ||||
2421 | } else { | |||
2422 | // C99 6.7.5.2p1: If the element type is an incomplete or function type, | |||
2423 | // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) | |||
2424 | if (RequireCompleteSizedType(Loc, T, | |||
2425 | diag::err_array_incomplete_or_sizeless_type)) | |||
2426 | return QualType(); | |||
2427 | } | |||
2428 | ||||
2429 | if (T->isSizelessType()) { | |||
2430 | Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T; | |||
2431 | return QualType(); | |||
2432 | } | |||
2433 | ||||
2434 | if (T->isFunctionType()) { | |||
2435 | Diag(Loc, diag::err_illegal_decl_array_of_functions) | |||
2436 | << getPrintableNameForEntity(Entity) << T; | |||
2437 | return QualType(); | |||
2438 | } | |||
2439 | ||||
2440 | if (const RecordType *EltTy = T->getAs<RecordType>()) { | |||
2441 | // If the element type is a struct or union that contains a variadic | |||
2442 | // array, accept it as a GNU extension: C99 6.7.2.1p2. | |||
2443 | if (EltTy->getDecl()->hasFlexibleArrayMember()) | |||
2444 | Diag(Loc, diag::ext_flexible_array_in_array) << T; | |||
2445 | } else if (T->isObjCObjectType()) { | |||
2446 | Diag(Loc, diag::err_objc_array_of_interfaces) << T; | |||
2447 | return QualType(); | |||
2448 | } | |||
2449 | ||||
2450 | // Do placeholder conversions on the array size expression. | |||
2451 | if (ArraySize && ArraySize->hasPlaceholderType()) { | |||
2452 | ExprResult Result = CheckPlaceholderExpr(ArraySize); | |||
2453 | if (Result.isInvalid()) return QualType(); | |||
2454 | ArraySize = Result.get(); | |||
2455 | } | |||
2456 | ||||
2457 | // Do lvalue-to-rvalue conversions on the array size expression. | |||
2458 | if (ArraySize && !ArraySize->isPRValue()) { | |||
2459 | ExprResult Result = DefaultLvalueConversion(ArraySize); | |||
2460 | if (Result.isInvalid()) | |||
2461 | return QualType(); | |||
2462 | ||||
2463 | ArraySize = Result.get(); | |||
2464 | } | |||
2465 | ||||
2466 | // C99 6.7.5.2p1: The size expression shall have integer type. | |||
2467 | // C++11 allows contextual conversions to such types. | |||
2468 | if (!getLangOpts().CPlusPlus11 && | |||
2469 | ArraySize && !ArraySize->isTypeDependent() && | |||
2470 | !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { | |||
2471 | Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int) | |||
2472 | << ArraySize->getType() << ArraySize->getSourceRange(); | |||
2473 | return QualType(); | |||
2474 | } | |||
2475 | ||||
2476 | // VLAs always produce at least a -Wvla diagnostic, sometimes an error. | |||
2477 | unsigned VLADiag; | |||
2478 | bool VLAIsError; | |||
2479 | if (getLangOpts().OpenCL) { | |||
2480 | // OpenCL v1.2 s6.9.d: variable length arrays are not supported. | |||
2481 | VLADiag = diag::err_opencl_vla; | |||
2482 | VLAIsError = true; | |||
2483 | } else if (getLangOpts().C99) { | |||
2484 | VLADiag = diag::warn_vla_used; | |||
2485 | VLAIsError = false; | |||
2486 | } else if (isSFINAEContext()) { | |||
2487 | VLADiag = diag::err_vla_in_sfinae; | |||
2488 | VLAIsError = true; | |||
2489 | } else if (getLangOpts().OpenMP && isInOpenMPTaskUntiedContext()) { | |||
2490 | VLADiag = diag::err_openmp_vla_in_task_untied; | |||
2491 | VLAIsError = true; | |||
2492 | } else { | |||
2493 | VLADiag = diag::ext_vla; | |||
2494 | VLAIsError = false; | |||
2495 | } | |||
2496 | ||||
2497 | llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType())); | |||
2498 | if (!ArraySize) { | |||
2499 | if (ASM == ArrayType::Star) { | |||
2500 | Diag(Loc, VLADiag); | |||
2501 | if (VLAIsError) | |||
2502 | return QualType(); | |||
2503 | ||||
2504 | T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets); | |||
2505 | } else { | |||
2506 | T = Context.getIncompleteArrayType(T, ASM, Quals); | |||
2507 | } | |||
2508 | } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { | |||
2509 | T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); | |||
2510 | } else { | |||
2511 | ExprResult R = | |||
2512 | checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError); | |||
2513 | if (R.isInvalid()) | |||
2514 | return QualType(); | |||
2515 | ||||
2516 | if (!R.isUsable()) { | |||
2517 | // C99: an array with a non-ICE size is a VLA. We accept any expression | |||
2518 | // that we can fold to a non-zero positive value as a non-VLA as an | |||
2519 | // extension. | |||
2520 | T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); | |||
2521 | } else if (!T->isDependentType() && !T->isIncompleteType() && | |||
2522 | !T->isConstantSizeType()) { | |||
2523 | // C99: an array with an element type that has a non-constant-size is a | |||
2524 | // VLA. | |||
2525 | // FIXME: Add a note to explain why this isn't a VLA. | |||
2526 | Diag(Loc, VLADiag); | |||
2527 | if (VLAIsError) | |||
2528 | return QualType(); | |||
2529 | T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); | |||
2530 | } else { | |||
2531 | // C99 6.7.5.2p1: If the expression is a constant expression, it shall | |||
2532 | // have a value greater than zero. | |||
2533 | // In C++, this follows from narrowing conversions being disallowed. | |||
2534 | if (ConstVal.isSigned() && ConstVal.isNegative()) { | |||
2535 | if (Entity) | |||
2536 | Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size) | |||
2537 | << getPrintableNameForEntity(Entity) | |||
2538 | << ArraySize->getSourceRange(); | |||
2539 | else | |||
2540 | Diag(ArraySize->getBeginLoc(), | |||
2541 | diag::err_typecheck_negative_array_size) | |||
2542 | << ArraySize->getSourceRange(); | |||
2543 | return QualType(); | |||
2544 | } | |||
2545 | if (ConstVal == 0) { | |||
2546 | // GCC accepts zero sized static arrays. We allow them when | |||
2547 | // we're not in a SFINAE context. | |||
2548 | Diag(ArraySize->getBeginLoc(), | |||
2549 | isSFINAEContext() ? diag::err_typecheck_zero_array_size | |||
2550 | : diag::ext_typecheck_zero_array_size) | |||
2551 | << 0 << ArraySize->getSourceRange(); | |||
2552 | } | |||
2553 | ||||
2554 | // Is the array too large? | |||
2555 | unsigned ActiveSizeBits = | |||
2556 | (!T->isDependentType() && !T->isVariablyModifiedType() && | |||
2557 | !T->isIncompleteType() && !T->isUndeducedType()) | |||
2558 | ? ConstantArrayType::getNumAddressingBits(Context, T, ConstVal) | |||
2559 | : ConstVal.getActiveBits(); | |||
2560 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { | |||
2561 | Diag(ArraySize->getBeginLoc(), diag::err_array_too_large) | |||
2562 | << toString(ConstVal, 10) << ArraySize->getSourceRange(); | |||
2563 | return QualType(); | |||
2564 | } | |||
2565 | ||||
2566 | T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals); | |||
2567 | } | |||
2568 | } | |||
2569 | ||||
2570 | if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) { | |||
2571 | // CUDA device code and some other targets don't support VLAs. | |||
2572 | targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) | |||
2573 | ? diag::err_cuda_vla | |||
2574 | : diag::err_vla_unsupported) | |||
2575 | << ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice) | |||
2576 | ? CurrentCUDATarget() | |||
2577 | : CFT_InvalidTarget); | |||
2578 | } | |||
2579 | ||||
2580 | // If this is not C99, diagnose array size modifiers on non-VLAs. | |||
2581 | if (!getLangOpts().C99 && !T->isVariableArrayType() && | |||
2582 | (ASM != ArrayType::Normal || Quals != 0)) { | |||
2583 | Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx | |||
2584 | : diag::ext_c99_array_usage) | |||
2585 | << ASM; | |||
2586 | } | |||
2587 | ||||
2588 | // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported. | |||
2589 | // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported. | |||
2590 | // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported. | |||
2591 | if (getLangOpts().OpenCL) { | |||
2592 | const QualType ArrType = Context.getBaseElementType(T); | |||
2593 | if (ArrType->isBlockPointerType() || ArrType->isPipeType() || | |||
2594 | ArrType->isSamplerT() || ArrType->isImageType()) { | |||
2595 | Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType; | |||
2596 | return QualType(); | |||
2597 | } | |||
2598 | } | |||
2599 | ||||
2600 | return T; | |||
2601 | } | |||
2602 | ||||
2603 | QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr, | |||
2604 | SourceLocation AttrLoc) { | |||
2605 | // The base type must be integer (not Boolean or enumeration) or float, and | |||
2606 | // can't already be a vector. | |||
2607 | if ((!CurType->isDependentType() && | |||
2608 | (!CurType->isBuiltinType() || CurType->isBooleanType() || | |||
2609 | (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) || | |||
2610 | CurType->isArrayType()) { | |||
2611 | Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType; | |||
2612 | return QualType(); | |||
2613 | } | |||
2614 | ||||
2615 | if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent()) | |||
2616 | return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, | |||
2617 | VectorType::GenericVector); | |||
2618 | ||||
2619 | Optional<llvm::APSInt> VecSize = SizeExpr->getIntegerConstantExpr(Context); | |||
2620 | if (!VecSize) { | |||
2621 | Diag(AttrLoc, diag::err_attribute_argument_type) | |||
2622 | << "vector_size" << AANT_ArgumentIntegerConstant | |||
2623 | << SizeExpr->getSourceRange(); | |||
2624 | return QualType(); | |||
2625 | } | |||
2626 | ||||
2627 | if (CurType->isDependentType()) | |||
2628 | return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc, | |||
2629 | VectorType::GenericVector); | |||
2630 | ||||
2631 | // vecSize is specified in bytes - convert to bits. | |||
2632 | if (!VecSize->isIntN(61)) { | |||
2633 | // Bit size will overflow uint64. | |||
2634 | Diag(AttrLoc, diag::err_attribute_size_too_large) | |||
2635 | << SizeExpr->getSourceRange() << "vector"; | |||
2636 | return QualType(); | |||
2637 | } | |||
2638 | uint64_t VectorSizeBits = VecSize->getZExtValue() * 8; | |||
2639 | unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType)); | |||
2640 | ||||
2641 | if (VectorSizeBits == 0) { | |||
2642 | Diag(AttrLoc, diag::err_attribute_zero_size) | |||
2643 | << SizeExpr->getSourceRange() << "vector"; | |||
2644 | return QualType(); | |||
2645 | } | |||
2646 | ||||
2647 | if (VectorSizeBits % TypeSize) { | |||
2648 | Diag(AttrLoc, diag::err_attribute_invalid_size) | |||
2649 | << SizeExpr->getSourceRange(); | |||
2650 | return QualType(); | |||
2651 | } | |||
2652 | ||||
2653 | if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) { | |||
2654 | Diag(AttrLoc, diag::err_attribute_size_too_large) | |||
2655 | << SizeExpr->getSourceRange() << "vector"; | |||
2656 | return QualType(); | |||
2657 | } | |||
2658 | ||||
2659 | return Context.getVectorType(CurType, VectorSizeBits / TypeSize, | |||
2660 | VectorType::GenericVector); | |||
2661 | } | |||
2662 | ||||
2663 | /// Build an ext-vector type. | |||
2664 | /// | |||
2665 | /// Run the required checks for the extended vector type. | |||
2666 | QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, | |||
2667 | SourceLocation AttrLoc) { | |||
2668 | // Unlike gcc's vector_size attribute, we do not allow vectors to be defined | |||
2669 | // in conjunction with complex types (pointers, arrays, functions, etc.). | |||
2670 | // | |||
2671 | // Additionally, OpenCL prohibits vectors of booleans (they're considered a | |||
2672 | // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects | |||
2673 | // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors | |||
2674 | // of bool aren't allowed. | |||
2675 | // | |||
2676 | // We explictly allow bool elements in ext_vector_type for C/C++. | |||
2677 | bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus; | |||
2678 | if ((!T->isDependentType() && !T->isIntegerType() && | |||
2679 | !T->isRealFloatingType()) || | |||
2680 | (IsNoBoolVecLang && T->isBooleanType())) { | |||
2681 | Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; | |||
2682 | return QualType(); | |||
2683 | } | |||
2684 | ||||
2685 | if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { | |||
2686 | Optional<llvm::APSInt> vecSize = ArraySize->getIntegerConstantExpr(Context); | |||
2687 | if (!vecSize) { | |||
2688 | Diag(AttrLoc, diag::err_attribute_argument_type) | |||
2689 | << "ext_vector_type" << AANT_ArgumentIntegerConstant | |||
2690 | << ArraySize->getSourceRange(); | |||
2691 | return QualType(); | |||
2692 | } | |||
2693 | ||||
2694 | if (!vecSize->isIntN(32)) { | |||
2695 | Diag(AttrLoc, diag::err_attribute_size_too_large) | |||
2696 | << ArraySize->getSourceRange() << "vector"; | |||
2697 | return QualType(); | |||
2698 | } | |||
2699 | // Unlike gcc's vector_size attribute, the size is specified as the | |||
2700 | // number of elements, not the number of bytes. | |||
2701 | unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue()); | |||
2702 | ||||
2703 | if (vectorSize == 0) { | |||
2704 | Diag(AttrLoc, diag::err_attribute_zero_size) | |||
2705 | << ArraySize->getSourceRange() << "vector"; | |||
2706 | return QualType(); | |||
2707 | } | |||
2708 | ||||
2709 | return Context.getExtVectorType(T, vectorSize); | |||
2710 | } | |||
2711 | ||||
2712 | return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc); | |||
2713 | } | |||
2714 | ||||
2715 | QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols, | |||
2716 | SourceLocation AttrLoc) { | |||
2717 | assert(Context.getLangOpts().MatrixTypes &&(static_cast <bool> (Context.getLangOpts().MatrixTypes && "Should never build a matrix type when it is disabled") ? void (0) : __assert_fail ("Context.getLangOpts().MatrixTypes && \"Should never build a matrix type when it is disabled\"" , "clang/lib/Sema/SemaType.cpp", 2718, __extension__ __PRETTY_FUNCTION__ )) | |||
2718 | "Should never build a matrix type when it is disabled")(static_cast <bool> (Context.getLangOpts().MatrixTypes && "Should never build a matrix type when it is disabled") ? void (0) : __assert_fail ("Context.getLangOpts().MatrixTypes && \"Should never build a matrix type when it is disabled\"" , "clang/lib/Sema/SemaType.cpp", 2718, __extension__ __PRETTY_FUNCTION__ )); | |||
2719 | ||||
2720 | // Check element type, if it is not dependent. | |||
2721 | if (!ElementTy->isDependentType() && | |||
2722 | !MatrixType::isValidElementType(ElementTy)) { | |||
2723 | Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy; | |||
2724 | return QualType(); | |||
2725 | } | |||
2726 | ||||
2727 | if (NumRows->isTypeDependent() || NumCols->isTypeDependent() || | |||
2728 | NumRows->isValueDependent() || NumCols->isValueDependent()) | |||
2729 | return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols, | |||
2730 | AttrLoc); | |||
2731 | ||||
2732 | Optional<llvm::APSInt> ValueRows = NumRows->getIntegerConstantExpr(Context); | |||
2733 | Optional<llvm::APSInt> ValueColumns = | |||
2734 | NumCols->getIntegerConstantExpr(Context); | |||
2735 | ||||
2736 | auto const RowRange = NumRows->getSourceRange(); | |||
2737 | auto const ColRange = NumCols->getSourceRange(); | |||
2738 | ||||
2739 | // Both are row and column expressions are invalid. | |||
2740 | if (!ValueRows && !ValueColumns) { | |||
2741 | Diag(AttrLoc, diag::err_attribute_argument_type) | |||
2742 | << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange | |||
2743 | << ColRange; | |||
2744 | return QualType(); | |||
2745 | } | |||
2746 | ||||
2747 | // Only the row expression is invalid. | |||
2748 | if (!ValueRows) { | |||
2749 | Diag(AttrLoc, diag::err_attribute_argument_type) | |||
2750 | << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange; | |||
2751 | return QualType(); | |||
2752 | } | |||
2753 | ||||
2754 | // Only the column expression is invalid. | |||
2755 | if (!ValueColumns) { | |||
2756 | Diag(AttrLoc, diag::err_attribute_argument_type) | |||
2757 | << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange; | |||
2758 | return QualType(); | |||
2759 | } | |||
2760 | ||||
2761 | // Check the matrix dimensions. | |||
2762 | unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue()); | |||
2763 | unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue()); | |||
2764 | if (MatrixRows == 0 && MatrixColumns == 0) { | |||
2765 | Diag(AttrLoc, diag::err_attribute_zero_size) | |||
2766 | << "matrix" << RowRange << ColRange; | |||
2767 | return QualType(); | |||
2768 | } | |||
2769 | if (MatrixRows == 0) { | |||
2770 | Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange; | |||
2771 | return QualType(); | |||
2772 | } | |||
2773 | if (MatrixColumns == 0) { | |||
2774 | Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange; | |||
2775 | return QualType(); | |||
2776 | } | |||
2777 | if (!ConstantMatrixType::isDimensionValid(MatrixRows)) { | |||
2778 | Diag(AttrLoc, diag::err_attribute_size_too_large) | |||
2779 | << RowRange << "matrix row"; | |||
2780 | return QualType(); | |||
2781 | } | |||
2782 | if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) { | |||
2783 | Diag(AttrLoc, diag::err_attribute_size_too_large) | |||
2784 | << ColRange << "matrix column"; | |||
2785 | return QualType(); | |||
2786 | } | |||
2787 | return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns); | |||
2788 | } | |||
2789 | ||||
2790 | bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { | |||
2791 | if (T->isArrayType() || T->isFunctionType()) { | |||
2792 | Diag(Loc, diag::err_func_returning_array_function) | |||
2793 | << T->isFunctionType() << T; | |||
2794 | return true; | |||
2795 | } | |||
2796 | ||||
2797 | // Functions cannot return half FP. | |||
2798 | if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) { | |||
2799 | Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << | |||
2800 | FixItHint::CreateInsertion(Loc, "*"); | |||
2801 | return true; | |||
2802 | } | |||
2803 | ||||
2804 | // Methods cannot return interface types. All ObjC objects are | |||
2805 | // passed by reference. | |||
2806 | if (T->isObjCObjectType()) { | |||
2807 | Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) | |||
2808 | << 0 << T << FixItHint::CreateInsertion(Loc, "*"); | |||
2809 | return true; | |||
2810 | } | |||
2811 | ||||
2812 | if (T.hasNonTrivialToPrimitiveDestructCUnion() || | |||
2813 | T.hasNonTrivialToPrimitiveCopyCUnion()) | |||
2814 | checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn, | |||
2815 | NTCUK_Destruct|NTCUK_Copy); | |||
2816 | ||||
2817 | // C++2a [dcl.fct]p12: | |||
2818 | // A volatile-qualified return type is deprecated | |||
2819 | if (T.isVolatileQualified() && getLangOpts().CPlusPlus20) | |||
2820 | Diag(Loc, diag::warn_deprecated_volatile_return) << T; | |||
2821 | ||||
2822 | return false; | |||
2823 | } | |||
2824 | ||||
2825 | /// Check the extended parameter information. Most of the necessary | |||
2826 | /// checking should occur when applying the parameter attribute; the | |||
2827 | /// only other checks required are positional restrictions. | |||
2828 | static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes, | |||
2829 | const FunctionProtoType::ExtProtoInfo &EPI, | |||
2830 | llvm::function_ref<SourceLocation(unsigned)> getParamLoc) { | |||
2831 | assert(EPI.ExtParameterInfos && "shouldn't get here without param infos")(static_cast <bool> (EPI.ExtParameterInfos && "shouldn't get here without param infos" ) ? void (0) : __assert_fail ("EPI.ExtParameterInfos && \"shouldn't get here without param infos\"" , "clang/lib/Sema/SemaType.cpp", 2831, __extension__ __PRETTY_FUNCTION__ )); | |||
2832 | ||||
2833 | bool emittedError = false; | |||
2834 | auto actualCC = EPI.ExtInfo.getCC(); | |||
2835 | enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync }; | |||
2836 | auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) { | |||
2837 | bool isCompatible = | |||
2838 | (required == RequiredCC::OnlySwift) | |||
2839 | ? (actualCC == CC_Swift) | |||
2840 | : (actualCC == CC_Swift || actualCC == CC_SwiftAsync); | |||
2841 | if (isCompatible || emittedError) | |||
2842 | return; | |||
2843 | S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall) | |||
2844 | << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI()) | |||
2845 | << (required == RequiredCC::OnlySwift); | |||
2846 | emittedError = true; | |||
2847 | }; | |||
2848 | for (size_t paramIndex = 0, numParams = paramTypes.size(); | |||
2849 | paramIndex != numParams; ++paramIndex) { | |||
2850 | switch (EPI.ExtParameterInfos[paramIndex].getABI()) { | |||
2851 | // Nothing interesting to check for orindary-ABI parameters. | |||
2852 | case ParameterABI::Ordinary: | |||
2853 | continue; | |||
2854 | ||||
2855 | // swift_indirect_result parameters must be a prefix of the function | |||
2856 | // arguments. | |||
2857 | case ParameterABI::SwiftIndirectResult: | |||
2858 | checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync); | |||
2859 | if (paramIndex != 0 && | |||
2860 | EPI.ExtParameterInfos[paramIndex - 1].getABI() | |||
2861 | != ParameterABI::SwiftIndirectResult) { | |||
2862 | S.Diag(getParamLoc(paramIndex), | |||
2863 | diag::err_swift_indirect_result_not_first); | |||
2864 | } | |||
2865 | continue; | |||
2866 | ||||
2867 | case ParameterABI::SwiftContext: | |||
2868 | checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync); | |||
2869 | continue; | |||
2870 | ||||
2871 | // SwiftAsyncContext is not limited to swiftasynccall functions. | |||
2872 | case ParameterABI::SwiftAsyncContext: | |||
2873 | continue; | |||
2874 | ||||
2875 | // swift_error parameters must be preceded by a swift_context parameter. | |||
2876 | case ParameterABI::SwiftErrorResult: | |||
2877 | checkCompatible(paramIndex, RequiredCC::OnlySwift); | |||
2878 | if (paramIndex == 0 || | |||
2879 | EPI.ExtParameterInfos[paramIndex - 1].getABI() != | |||
2880 | ParameterABI::SwiftContext) { | |||
2881 | S.Diag(getParamLoc(paramIndex), | |||
2882 | diag::err_swift_error_result_not_after_swift_context); | |||
2883 | } | |||
2884 | continue; | |||
2885 | } | |||
2886 | llvm_unreachable("bad ABI kind")::llvm::llvm_unreachable_internal("bad ABI kind", "clang/lib/Sema/SemaType.cpp" , 2886); | |||
2887 | } | |||
2888 | } | |||
2889 | ||||
2890 | QualType Sema::BuildFunctionType(QualType T, | |||
2891 | MutableArrayRef<QualType> ParamTypes, | |||
2892 | SourceLocation Loc, DeclarationName Entity, | |||
2893 | const FunctionProtoType::ExtProtoInfo &EPI) { | |||
2894 | bool Invalid = false; | |||
2895 | ||||
2896 | Invalid |= CheckFunctionReturnType(T, Loc); | |||
2897 | ||||
2898 | for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { | |||
2899 | // FIXME: Loc is too inprecise here, should use proper locations for args. | |||
2900 | QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]); | |||
2901 | if (ParamType->isVoidType()) { | |||
2902 | Diag(Loc, diag::err_param_with_void_type); | |||
2903 | Invalid = true; | |||
2904 | } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) { | |||
2905 | // Disallow half FP arguments. | |||
2906 | Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << | |||
2907 | FixItHint::CreateInsertion(Loc, "*"); | |||
2908 | Invalid = true; | |||
2909 | } | |||
2910 | ||||
2911 | // C++2a [dcl.fct]p4: | |||
2912 | // A parameter with volatile-qualified type is deprecated | |||
2913 | if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20) | |||
2914 | Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType; | |||
2915 | ||||
2916 | ParamTypes[Idx] = ParamType; | |||
2917 | } | |||
2918 | ||||
2919 | if (EPI.ExtParameterInfos) { | |||
2920 | checkExtParameterInfos(*this, ParamTypes, EPI, | |||
2921 | [=](unsigned i) { return Loc; }); | |||
2922 | } | |||
2923 | ||||
2924 | if (EPI.ExtInfo.getProducesResult()) { | |||
2925 | // This is just a warning, so we can't fail to build if we see it. | |||
2926 | checkNSReturnsRetainedReturnType(Loc, T); | |||
2927 | } | |||
2928 | ||||
2929 | if (Invalid) | |||
2930 | return QualType(); | |||
2931 | ||||
2932 | return Context.getFunctionType(T, ParamTypes, EPI); | |||
2933 | } | |||
2934 | ||||
2935 | /// Build a member pointer type \c T Class::*. | |||
2936 | /// | |||
2937 | /// \param T the type to which the member pointer refers. | |||
2938 | /// \param Class the class type into which the member pointer points. | |||
2939 | /// \param Loc the location where this type begins | |||
2940 | /// \param Entity the name of the entity that will have this member pointer type | |||
2941 | /// | |||
2942 | /// \returns a member pointer type, if successful, or a NULL type if there was | |||
2943 | /// an error. | |||
2944 | QualType Sema::BuildMemberPointerType(QualType T, QualType Class, | |||
2945 | SourceLocation Loc, | |||
2946 | DeclarationName Entity) { | |||
2947 | // Verify that we're not building a pointer to pointer to function with | |||
2948 | // exception specification. | |||
2949 | if (CheckDistantExceptionSpec(T)) { | |||
2950 | Diag(Loc, diag::err_distant_exception_spec); | |||
2951 | return QualType(); | |||
2952 | } | |||
2953 | ||||
2954 | // C++ 8.3.3p3: A pointer to member shall not point to ... a member | |||
2955 | // with reference type, or "cv void." | |||
2956 | if (T->isReferenceType()) { | |||
2957 | Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) | |||
2958 | << getPrintableNameForEntity(Entity) << T; | |||
2959 | return QualType(); | |||
2960 | } | |||
2961 | ||||
2962 | if (T->isVoidType()) { | |||
2963 | Diag(Loc, diag::err_illegal_decl_mempointer_to_void) | |||
2964 | << getPrintableNameForEntity(Entity); | |||
2965 | return QualType(); | |||
2966 | } | |||
2967 | ||||
2968 | if (!Class->isDependentType() && !Class->isRecordType()) { | |||
2969 | Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; | |||
2970 | return QualType(); | |||
2971 | } | |||
2972 | ||||
2973 | if (T->isFunctionType() && getLangOpts().OpenCL && | |||
2974 | !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", | |||
2975 | getLangOpts())) { | |||
2976 | Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0; | |||
2977 | return QualType(); | |||
2978 | } | |||
2979 | ||||
2980 | if (getLangOpts().HLSL) { | |||
2981 | Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0; | |||
2982 | return QualType(); | |||
2983 | } | |||
2984 | ||||
2985 | // Adjust the default free function calling convention to the default method | |||
2986 | // calling convention. | |||
2987 | bool IsCtorOrDtor = | |||
2988 | (Entity.getNameKind() == DeclarationName::CXXConstructorName) || | |||
2989 | (Entity.getNameKind() == DeclarationName::CXXDestructorName); | |||
2990 | if (T->isFunctionType()) | |||
2991 | adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc); | |||
2992 | ||||
2993 | return Context.getMemberPointerType(T, Class.getTypePtr()); | |||
2994 | } | |||
2995 | ||||
2996 | /// Build a block pointer type. | |||
2997 | /// | |||
2998 | /// \param T The type to which we'll be building a block pointer. | |||
2999 | /// | |||
3000 | /// \param Loc The source location, used for diagnostics. | |||
3001 | /// | |||
3002 | /// \param Entity The name of the entity that involves the block pointer | |||
3003 | /// type, if known. | |||
3004 | /// | |||
3005 | /// \returns A suitable block pointer type, if there are no | |||
3006 | /// errors. Otherwise, returns a NULL type. | |||
3007 | QualType Sema::BuildBlockPointerType(QualType T, | |||
3008 | SourceLocation Loc, | |||
3009 | DeclarationName Entity) { | |||
3010 | if (!T->isFunctionType()) { | |||
3011 | Diag(Loc, diag::err_nonfunction_block_type); | |||
3012 | return QualType(); | |||
3013 | } | |||
3014 | ||||
3015 | if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer)) | |||
3016 | return QualType(); | |||
3017 | ||||
3018 | if (getLangOpts().OpenCL) | |||
3019 | T = deduceOpenCLPointeeAddrSpace(*this, T); | |||
3020 | ||||
3021 | return Context.getBlockPointerType(T); | |||
3022 | } | |||
3023 | ||||
3024 | QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { | |||
3025 | QualType QT = Ty.get(); | |||
3026 | if (QT.isNull()) { | |||
3027 | if (TInfo) *TInfo = nullptr; | |||
3028 | return QualType(); | |||
3029 | } | |||
3030 | ||||
3031 | TypeSourceInfo *DI = nullptr; | |||
3032 | if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { | |||
3033 | QT = LIT->getType(); | |||
3034 | DI = LIT->getTypeSourceInfo(); | |||
3035 | } | |||
3036 | ||||
3037 | if (TInfo) *TInfo = DI; | |||
3038 | return QT; | |||
3039 | } | |||
3040 | ||||
3041 | static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, | |||
3042 | Qualifiers::ObjCLifetime ownership, | |||
3043 | unsigned chunkIndex); | |||
3044 | ||||
3045 | /// Given that this is the declaration of a parameter under ARC, | |||
3046 | /// attempt to infer attributes and such for pointer-to-whatever | |||
3047 | /// types. | |||
3048 | static void inferARCWriteback(TypeProcessingState &state, | |||
3049 | QualType &declSpecType) { | |||
3050 | Sema &S = state.getSema(); | |||
3051 | Declarator &declarator = state.getDeclarator(); | |||
3052 | ||||
3053 | // TODO: should we care about decl qualifiers? | |||
3054 | ||||
3055 | // Check whether the declarator has the expected form. We walk | |||
3056 | // from the inside out in order to make the block logic work. | |||
3057 | unsigned outermostPointerIndex = 0; | |||
3058 | bool isBlockPointer = false; | |||
3059 | unsigned numPointers = 0; | |||
3060 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { | |||
3061 | unsigned chunkIndex = i; | |||
3062 | DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex); | |||
3063 | switch (chunk.Kind) { | |||
3064 | case DeclaratorChunk::Paren: | |||
3065 | // Ignore parens. | |||
3066 | break; | |||
3067 | ||||
3068 | case DeclaratorChunk::Reference: | |||
3069 | case DeclaratorChunk::Pointer: | |||
3070 | // Count the number of pointers. Treat references | |||
3071 | // interchangeably as pointers; if they're mis-ordered, normal | |||
3072 | // type building will discover that. | |||
3073 | outermostPointerIndex = chunkIndex; | |||
3074 | numPointers++; | |||
3075 | break; | |||
3076 | ||||
3077 | case DeclaratorChunk::BlockPointer: | |||
3078 | // If we have a pointer to block pointer, that's an acceptable | |||
3079 | // indirect reference; anything else is not an application of | |||
3080 | // the rules. | |||
3081 | if (numPointers != 1) return; | |||
3082 | numPointers++; | |||
3083 | outermostPointerIndex = chunkIndex; | |||
3084 | isBlockPointer = true; | |||
3085 | ||||
3086 | // We don't care about pointer structure in return values here. | |||
3087 | goto done; | |||
3088 | ||||
3089 | case DeclaratorChunk::Array: // suppress if written (id[])? | |||
3090 | case DeclaratorChunk::Function: | |||
3091 | case DeclaratorChunk::MemberPointer: | |||
3092 | case DeclaratorChunk::Pipe: | |||
3093 | return; | |||
3094 | } | |||
3095 | } | |||
3096 | done: | |||
3097 | ||||
3098 | // If we have *one* pointer, then we want to throw the qualifier on | |||
3099 | // the declaration-specifiers, which means that it needs to be a | |||
3100 | // retainable object type. | |||
3101 | if (numPointers == 1) { | |||
3102 | // If it's not a retainable object type, the rule doesn't apply. | |||
3103 | if (!declSpecType->isObjCRetainableType()) return; | |||
3104 | ||||
3105 | // If it already has lifetime, don't do anything. | |||
3106 | if (declSpecType.getObjCLifetime()) return; | |||
3107 | ||||
3108 | // Otherwise, modify the type in-place. | |||
3109 | Qualifiers qs; | |||
3110 | ||||
3111 | if (declSpecType->isObjCARCImplicitlyUnretainedType()) | |||
3112 | qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone); | |||
3113 | else | |||
3114 | qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing); | |||
3115 | declSpecType = S.Context.getQualifiedType(declSpecType, qs); | |||
3116 | ||||
3117 | // If we have *two* pointers, then we want to throw the qualifier on | |||
3118 | // the outermost pointer. | |||
3119 | } else if (numPointers == 2) { | |||
3120 | // If we don't have a block pointer, we need to check whether the | |||
3121 | // declaration-specifiers gave us something that will turn into a | |||
3122 | // retainable object pointer after we slap the first pointer on it. | |||
3123 | if (!isBlockPointer && !declSpecType->isObjCObjectType()) | |||
3124 | return; | |||
3125 | ||||
3126 | // Look for an explicit lifetime attribute there. | |||
3127 | DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex); | |||
3128 | if (chunk.Kind != DeclaratorChunk::Pointer && | |||
3129 | chunk.Kind != DeclaratorChunk::BlockPointer) | |||
3130 | return; | |||
3131 | for (const ParsedAttr &AL : chunk.getAttrs()) | |||
3132 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) | |||
3133 | return; | |||
3134 | ||||
3135 | transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing, | |||
3136 | outermostPointerIndex); | |||
3137 | ||||
3138 | // Any other number of pointers/references does not trigger the rule. | |||
3139 | } else return; | |||
3140 | ||||
3141 | // TODO: mark whether we did this inference? | |||
3142 | } | |||
3143 | ||||
3144 | void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, | |||
3145 | SourceLocation FallbackLoc, | |||
3146 | SourceLocation ConstQualLoc, | |||
3147 | SourceLocation VolatileQualLoc, | |||
3148 | SourceLocation RestrictQualLoc, | |||
3149 | SourceLocation AtomicQualLoc, | |||
3150 | SourceLocation UnalignedQualLoc) { | |||
3151 | if (!Quals) | |||
3152 | return; | |||
3153 | ||||
3154 | struct Qual { | |||
3155 | const char *Name; | |||
3156 | unsigned Mask; | |||
3157 | SourceLocation Loc; | |||
3158 | } const QualKinds[5] = { | |||
3159 | { "const", DeclSpec::TQ_const, ConstQualLoc }, | |||
3160 | { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc }, | |||
3161 | { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc }, | |||
3162 | { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc }, | |||
3163 | { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc } | |||
3164 | }; | |||
3165 | ||||
3166 | SmallString<32> QualStr; | |||
3167 | unsigned NumQuals = 0; | |||
3168 | SourceLocation Loc; | |||
3169 | FixItHint FixIts[5]; | |||
3170 | ||||
3171 | // Build a string naming the redundant qualifiers. | |||
3172 | for (auto &E : QualKinds) { | |||
3173 | if (Quals & E.Mask) { | |||
3174 | if (!QualStr.empty()) QualStr += ' '; | |||
3175 | QualStr += E.Name; | |||
3176 | ||||
3177 | // If we have a location for the qualifier, offer a fixit. | |||
3178 | SourceLocation QualLoc = E.Loc; | |||
3179 | if (QualLoc.isValid()) { | |||
3180 | FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc); | |||
3181 | if (Loc.isInvalid() || | |||
3182 | getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)) | |||
3183 | Loc = QualLoc; | |||
3184 | } | |||
3185 | ||||
3186 | ++NumQuals; | |||
3187 | } | |||
3188 | } | |||
3189 | ||||
3190 | Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID) | |||
3191 | << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; | |||
3192 | } | |||
3193 | ||||
3194 | // Diagnose pointless type qualifiers on the return type of a function. | |||
3195 | static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, | |||
3196 | Declarator &D, | |||
3197 | unsigned FunctionChunkIndex) { | |||
3198 | const DeclaratorChunk::FunctionTypeInfo &FTI = | |||
3199 | D.getTypeObject(FunctionChunkIndex).Fun; | |||
3200 | if (FTI.hasTrailingReturnType()) { | |||
3201 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | |||
3202 | RetTy.getLocalCVRQualifiers(), | |||
3203 | FTI.getTrailingReturnTypeLoc()); | |||
3204 | return; | |||
3205 | } | |||
3206 | ||||
3207 | for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, | |||
3208 | End = D.getNumTypeObjects(); | |||
3209 | OuterChunkIndex != End; ++OuterChunkIndex) { | |||
3210 | DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex); | |||
3211 | switch (OuterChunk.Kind) { | |||
3212 | case DeclaratorChunk::Paren: | |||
3213 | continue; | |||
3214 | ||||
3215 | case DeclaratorChunk::Pointer: { | |||
3216 | DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; | |||
3217 | S.diagnoseIgnoredQualifiers( | |||
3218 | diag::warn_qual_return_type, | |||
3219 | PTI.TypeQuals, | |||
3220 | SourceLocation(), | |||
3221 | PTI.ConstQualLoc, | |||
3222 | PTI.VolatileQualLoc, | |||
3223 | PTI.RestrictQualLoc, | |||
3224 | PTI.AtomicQualLoc, | |||
3225 | PTI.UnalignedQualLoc); | |||
3226 | return; | |||
3227 | } | |||
3228 | ||||
3229 | case DeclaratorChunk::Function: | |||
3230 | case DeclaratorChunk::BlockPointer: | |||
3231 | case DeclaratorChunk::Reference: | |||
3232 | case DeclaratorChunk::Array: | |||
3233 | case DeclaratorChunk::MemberPointer: | |||
3234 | case DeclaratorChunk::Pipe: | |||
3235 | // FIXME: We can't currently provide an accurate source location and a | |||
3236 | // fix-it hint for these. | |||
3237 | unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; | |||
3238 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | |||
3239 | RetTy.getCVRQualifiers() | AtomicQual, | |||
3240 | D.getIdentifierLoc()); | |||
3241 | return; | |||
3242 | } | |||
3243 | ||||
3244 | llvm_unreachable("unknown declarator chunk kind")::llvm::llvm_unreachable_internal("unknown declarator chunk kind" , "clang/lib/Sema/SemaType.cpp", 3244); | |||
3245 | } | |||
3246 | ||||
3247 | // If the qualifiers come from a conversion function type, don't diagnose | |||
3248 | // them -- they're not necessarily redundant, since such a conversion | |||
3249 | // operator can be explicitly called as "x.operator const int()". | |||
3250 | if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) | |||
3251 | return; | |||
3252 | ||||
3253 | // Just parens all the way out to the decl specifiers. Diagnose any qualifiers | |||
3254 | // which are present there. | |||
3255 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, | |||
3256 | D.getDeclSpec().getTypeQualifiers(), | |||
3257 | D.getIdentifierLoc(), | |||
3258 | D.getDeclSpec().getConstSpecLoc(), | |||
3259 | D.getDeclSpec().getVolatileSpecLoc(), | |||
3260 | D.getDeclSpec().getRestrictSpecLoc(), | |||
3261 | D.getDeclSpec().getAtomicSpecLoc(), | |||
3262 | D.getDeclSpec().getUnalignedSpecLoc()); | |||
3263 | } | |||
3264 | ||||
3265 | static std::pair<QualType, TypeSourceInfo *> | |||
3266 | InventTemplateParameter(TypeProcessingState &state, QualType T, | |||
3267 | TypeSourceInfo *TrailingTSI, AutoType *Auto, | |||
3268 | InventedTemplateParameterInfo &Info) { | |||
3269 | Sema &S = state.getSema(); | |||
3270 | Declarator &D = state.getDeclarator(); | |||
3271 | ||||
3272 | const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth; | |||
3273 | const unsigned AutoParameterPosition = Info.TemplateParams.size(); | |||
3274 | const bool IsParameterPack = D.hasEllipsis(); | |||
3275 | ||||
3276 | // If auto is mentioned in a lambda parameter or abbreviated function | |||
3277 | // template context, convert it to a template parameter type. | |||
3278 | ||||
3279 | // Create the TemplateTypeParmDecl here to retrieve the corresponding | |||
3280 | // template parameter type. Template parameters are temporarily added | |||
3281 | // to the TU until the associated TemplateDecl is created. | |||
3282 | TemplateTypeParmDecl *InventedTemplateParam = | |||
3283 | TemplateTypeParmDecl::Create( | |||
3284 | S.Context, S.Context.getTranslationUnitDecl(), | |||
3285 | /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(), | |||
3286 | /*NameLoc=*/D.getIdentifierLoc(), | |||
3287 | TemplateParameterDepth, AutoParameterPosition, | |||
3288 | S.InventAbbreviatedTemplateParameterTypeName( | |||
3289 | D.getIdentifier(), AutoParameterPosition), false, | |||
3290 | IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained()); | |||
3291 | InventedTemplateParam->setImplicit(); | |||
3292 | Info.TemplateParams.push_back(InventedTemplateParam); | |||
3293 | ||||
3294 | // Attach type constraints to the new parameter. | |||
3295 | if (Auto->isConstrained()) { | |||
3296 | if (TrailingTSI) { | |||
3297 | // The 'auto' appears in a trailing return type we've already built; | |||
3298 | // extract its type constraints to attach to the template parameter. | |||
3299 | AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc(); | |||
3300 | TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc()); | |||
3301 | bool Invalid = false; | |||
3302 | for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) { | |||
3303 | if (D.getEllipsisLoc().isInvalid() && !Invalid && | |||
3304 | S.DiagnoseUnexpandedParameterPack(AutoLoc.getArgLoc(Idx), | |||
3305 | Sema::UPPC_TypeConstraint)) | |||
3306 | Invalid = true; | |||
3307 | TAL.addArgument(AutoLoc.getArgLoc(Idx)); | |||
3308 | } | |||
3309 | ||||
3310 | if (!Invalid) { | |||
3311 | S.AttachTypeConstraint( | |||
3312 | AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(), | |||
3313 | AutoLoc.getNamedConcept(), | |||
3314 | AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr, | |||
3315 | InventedTemplateParam, D.getEllipsisLoc()); | |||
3316 | } | |||
3317 | } else { | |||
3318 | // The 'auto' appears in the decl-specifiers; we've not finished forming | |||
3319 | // TypeSourceInfo for it yet. | |||
3320 | TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId(); | |||
3321 | TemplateArgumentListInfo TemplateArgsInfo; | |||
3322 | bool Invalid = false; | |||
3323 | if (TemplateId->LAngleLoc.isValid()) { | |||
3324 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
3325 | TemplateId->NumArgs); | |||
3326 | S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); | |||
3327 | ||||
3328 | if (D.getEllipsisLoc().isInvalid()) { | |||
3329 | for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) { | |||
3330 | if (S.DiagnoseUnexpandedParameterPack(Arg, | |||
3331 | Sema::UPPC_TypeConstraint)) { | |||
3332 | Invalid = true; | |||
3333 | break; | |||
3334 | } | |||
3335 | } | |||
3336 | } | |||
3337 | } | |||
3338 | if (!Invalid) { | |||
3339 | S.AttachTypeConstraint( | |||
3340 | D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context), | |||
3341 | DeclarationNameInfo(DeclarationName(TemplateId->Name), | |||
3342 | TemplateId->TemplateNameLoc), | |||
3343 | cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()), | |||
3344 | TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr, | |||
3345 | InventedTemplateParam, D.getEllipsisLoc()); | |||
3346 | } | |||
3347 | } | |||
3348 | } | |||
3349 | ||||
3350 | // Replace the 'auto' in the function parameter with this invented | |||
3351 | // template type parameter. | |||
3352 | // FIXME: Retain some type sugar to indicate that this was written | |||
3353 | // as 'auto'? | |||
3354 | QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0); | |||
3355 | QualType NewT = state.ReplaceAutoType(T, Replacement); | |||
3356 | TypeSourceInfo *NewTSI = | |||
3357 | TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement) | |||
3358 | : nullptr; | |||
3359 | return {NewT, NewTSI}; | |||
3360 | } | |||
3361 | ||||
3362 | static TypeSourceInfo * | |||
3363 | GetTypeSourceInfoForDeclarator(TypeProcessingState &State, | |||
3364 | QualType T, TypeSourceInfo *ReturnTypeInfo); | |||
3365 | ||||
3366 | static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, | |||
3367 | TypeSourceInfo *&ReturnTypeInfo) { | |||
3368 | Sema &SemaRef = state.getSema(); | |||
3369 | Declarator &D = state.getDeclarator(); | |||
3370 | QualType T; | |||
3371 | ReturnTypeInfo = nullptr; | |||
3372 | ||||
3373 | // The TagDecl owned by the DeclSpec. | |||
3374 | TagDecl *OwnedTagDecl = nullptr; | |||
3375 | ||||
3376 | switch (D.getName().getKind()) { | |||
3377 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | |||
3378 | case UnqualifiedIdKind::IK_OperatorFunctionId: | |||
3379 | case UnqualifiedIdKind::IK_Identifier: | |||
3380 | case UnqualifiedIdKind::IK_LiteralOperatorId: | |||
3381 | case UnqualifiedIdKind::IK_TemplateId: | |||
3382 | T = ConvertDeclSpecToType(state); | |||
3383 | ||||
3384 | if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { | |||
3385 | OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | |||
3386 | // Owned declaration is embedded in declarator. | |||
3387 | OwnedTagDecl->setEmbeddedInDeclarator(true); | |||
3388 | } | |||
3389 | break; | |||
3390 | ||||
3391 | case UnqualifiedIdKind::IK_ConstructorName: | |||
3392 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | |||
3393 | case UnqualifiedIdKind::IK_DestructorName: | |||
3394 | // Constructors and destructors don't have return types. Use | |||
3395 | // "void" instead. | |||
3396 | T = SemaRef.Context.VoidTy; | |||
3397 | processTypeAttrs(state, T, TAL_DeclSpec, | |||
3398 | D.getMutableDeclSpec().getAttributes()); | |||
3399 | break; | |||
3400 | ||||
3401 | case UnqualifiedIdKind::IK_DeductionGuideName: | |||
3402 | // Deduction guides have a trailing return type and no type in their | |||
3403 | // decl-specifier sequence. Use a placeholder return type for now. | |||
3404 | T = SemaRef.Context.DependentTy; | |||
3405 | break; | |||
3406 | ||||
3407 | case UnqualifiedIdKind::IK_ConversionFunctionId: | |||
3408 | // The result type of a conversion function is the type that it | |||
3409 | // converts to. | |||
3410 | T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId, | |||
3411 | &ReturnTypeInfo); | |||
3412 | break; | |||
3413 | } | |||
3414 | ||||
3415 | if (!D.getAttributes().empty()) | |||
3416 | distributeTypeAttrsFromDeclarator(state, T); | |||
3417 | ||||
3418 | // Find the deduced type in this type. Look in the trailing return type if we | |||
3419 | // have one, otherwise in the DeclSpec type. | |||
3420 | // FIXME: The standard wording doesn't currently describe this. | |||
3421 | DeducedType *Deduced = T->getContainedDeducedType(); | |||
3422 | bool DeducedIsTrailingReturnType = false; | |||
3423 | if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) { | |||
3424 | QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType()); | |||
3425 | Deduced = T.isNull() ? nullptr : T->getContainedDeducedType(); | |||
3426 | DeducedIsTrailingReturnType = true; | |||
3427 | } | |||
3428 | ||||
3429 | // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. | |||
3430 | if (Deduced) { | |||
3431 | AutoType *Auto = dyn_cast<AutoType>(Deduced); | |||
3432 | int Error = -1; | |||
3433 | ||||
3434 | // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or | |||
3435 | // class template argument deduction)? | |||
3436 | bool IsCXXAutoType = | |||
3437 | (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType); | |||
3438 | bool IsDeducedReturnType = false; | |||
3439 | ||||
3440 | switch (D.getContext()) { | |||
3441 | case DeclaratorContext::LambdaExpr: | |||
3442 | // Declared return type of a lambda-declarator is implicit and is always | |||
3443 | // 'auto'. | |||
3444 | break; | |||
3445 | case DeclaratorContext::ObjCParameter: | |||
3446 | case DeclaratorContext::ObjCResult: | |||
3447 | Error = 0; | |||
3448 | break; | |||
3449 | case DeclaratorContext::RequiresExpr: | |||
3450 | Error = 22; | |||
3451 | break; | |||
3452 | case DeclaratorContext::Prototype: | |||
3453 | case DeclaratorContext::LambdaExprParameter: { | |||
3454 | InventedTemplateParameterInfo *Info = nullptr; | |||
3455 | if (D.getContext() == DeclaratorContext::Prototype) { | |||
3456 | // With concepts we allow 'auto' in function parameters. | |||
3457 | if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto || | |||
3458 | Auto->getKeyword() != AutoTypeKeyword::Auto) { | |||
3459 | Error = 0; | |||
3460 | break; | |||
3461 | } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) { | |||
3462 | Error = 21; | |||
3463 | break; | |||
3464 | } | |||
3465 | ||||
3466 | Info = &SemaRef.InventedParameterInfos.back(); | |||
3467 | } else { | |||
3468 | // In C++14, generic lambdas allow 'auto' in their parameters. | |||
3469 | if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto || | |||
3470 | Auto->getKeyword() != AutoTypeKeyword::Auto) { | |||
3471 | Error = 16; | |||
3472 | break; | |||
3473 | } | |||
3474 | Info = SemaRef.getCurLambda(); | |||
3475 | assert(Info && "No LambdaScopeInfo on the stack!")(static_cast <bool> (Info && "No LambdaScopeInfo on the stack!" ) ? void (0) : __assert_fail ("Info && \"No LambdaScopeInfo on the stack!\"" , "clang/lib/Sema/SemaType.cpp", 3475, __extension__ __PRETTY_FUNCTION__ )); | |||
3476 | } | |||
3477 | ||||
3478 | // We'll deal with inventing template parameters for 'auto' in trailing | |||
3479 | // return types when we pick up the trailing return type when processing | |||
3480 | // the function chunk. | |||
3481 | if (!DeducedIsTrailingReturnType) | |||
3482 | T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first; | |||
3483 | break; | |||
3484 | } | |||
3485 | case DeclaratorContext::Member: { | |||
3486 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || | |||
3487 | D.isFunctionDeclarator()) | |||
3488 | break; | |||
3489 | bool Cxx = SemaRef.getLangOpts().CPlusPlus; | |||
3490 | if (isa<ObjCContainerDecl>(SemaRef.CurContext)) { | |||
3491 | Error = 6; // Interface member. | |||
3492 | } else { | |||
3493 | switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) { | |||
3494 | case TTK_Enum: llvm_unreachable("unhandled tag kind")::llvm::llvm_unreachable_internal("unhandled tag kind", "clang/lib/Sema/SemaType.cpp" , 3494); | |||
3495 | case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break; | |||
3496 | case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break; | |||
3497 | case TTK_Class: Error = 5; /* Class member */ break; | |||
3498 | case TTK_Interface: Error = 6; /* Interface member */ break; | |||
3499 | } | |||
3500 | } | |||
3501 | if (D.getDeclSpec().isFriendSpecified()) | |||
3502 | Error = 20; // Friend type | |||
3503 | break; | |||
3504 | } | |||
3505 | case DeclaratorContext::CXXCatch: | |||
3506 | case DeclaratorContext::ObjCCatch: | |||
3507 | Error = 7; // Exception declaration | |||
3508 | break; | |||
3509 | case DeclaratorContext::TemplateParam: | |||
3510 | if (isa<DeducedTemplateSpecializationType>(Deduced) && | |||
3511 | !SemaRef.getLangOpts().CPlusPlus20) | |||
3512 | Error = 19; // Template parameter (until C++20) | |||
3513 | else if (!SemaRef.getLangOpts().CPlusPlus17) | |||
3514 | Error = 8; // Template parameter (until C++17) | |||
3515 | break; | |||
3516 | case DeclaratorContext::BlockLiteral: | |||
3517 | Error = 9; // Block literal | |||
3518 | break; | |||
3519 | case DeclaratorContext::TemplateArg: | |||
3520 | // Within a template argument list, a deduced template specialization | |||
3521 | // type will be reinterpreted as a template template argument. | |||
3522 | if (isa<DeducedTemplateSpecializationType>(Deduced) && | |||
3523 | !D.getNumTypeObjects() && | |||
3524 | D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier) | |||
3525 | break; | |||
3526 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
3527 | case DeclaratorContext::TemplateTypeArg: | |||
3528 | Error = 10; // Template type argument | |||
3529 | break; | |||
3530 | case DeclaratorContext::AliasDecl: | |||
3531 | case DeclaratorContext::AliasTemplate: | |||
3532 | Error = 12; // Type alias | |||
3533 | break; | |||
3534 | case DeclaratorContext::TrailingReturn: | |||
3535 | case DeclaratorContext::TrailingReturnVar: | |||
3536 | if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) | |||
3537 | Error = 13; // Function return type | |||
3538 | IsDeducedReturnType = true; | |||
3539 | break; | |||
3540 | case DeclaratorContext::ConversionId: | |||
3541 | if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) | |||
3542 | Error = 14; // conversion-type-id | |||
3543 | IsDeducedReturnType = true; | |||
3544 | break; | |||
3545 | case DeclaratorContext::FunctionalCast: | |||
3546 | if (isa<DeducedTemplateSpecializationType>(Deduced)) | |||
3547 | break; | |||
3548 | if (SemaRef.getLangOpts().CPlusPlus2b && IsCXXAutoType && | |||
3549 | !Auto->isDecltypeAuto()) | |||
3550 | break; // auto(x) | |||
3551 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
3552 | case DeclaratorContext::TypeName: | |||
3553 | Error = 15; // Generic | |||
3554 | break; | |||
3555 | case DeclaratorContext::File: | |||
3556 | case DeclaratorContext::Block: | |||
3557 | case DeclaratorContext::ForInit: | |||
3558 | case DeclaratorContext::SelectionInit: | |||
3559 | case DeclaratorContext::Condition: | |||
3560 | // FIXME: P0091R3 (erroneously) does not permit class template argument | |||
3561 | // deduction in conditions, for-init-statements, and other declarations | |||
3562 | // that are not simple-declarations. | |||
3563 | break; | |||
3564 | case DeclaratorContext::CXXNew: | |||
3565 | // FIXME: P0091R3 does not permit class template argument deduction here, | |||
3566 | // but we follow GCC and allow it anyway. | |||
3567 | if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced)) | |||
3568 | Error = 17; // 'new' type | |||
3569 | break; | |||
3570 | case DeclaratorContext::KNRTypeList: | |||
3571 | Error = 18; // K&R function parameter | |||
3572 | break; | |||
3573 | } | |||
3574 | ||||
3575 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) | |||
3576 | Error = 11; | |||
3577 | ||||
3578 | // In Objective-C it is an error to use 'auto' on a function declarator | |||
3579 | // (and everywhere for '__auto_type'). | |||
3580 | if (D.isFunctionDeclarator() && | |||
3581 | (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType)) | |||
3582 | Error = 13; | |||
3583 | ||||
3584 | SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); | |||
3585 | if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) | |||
3586 | AutoRange = D.getName().getSourceRange(); | |||
3587 | ||||
3588 | if (Error != -1) { | |||
3589 | unsigned Kind; | |||
3590 | if (Auto) { | |||
3591 | switch (Auto->getKeyword()) { | |||
3592 | case AutoTypeKeyword::Auto: Kind = 0; break; | |||
3593 | case AutoTypeKeyword::DecltypeAuto: Kind = 1; break; | |||
3594 | case AutoTypeKeyword::GNUAutoType: Kind = 2; break; | |||
3595 | } | |||
3596 | } else { | |||
3597 | assert(isa<DeducedTemplateSpecializationType>(Deduced) &&(static_cast <bool> (isa<DeducedTemplateSpecializationType >(Deduced) && "unknown auto type") ? void (0) : __assert_fail ("isa<DeducedTemplateSpecializationType>(Deduced) && \"unknown auto type\"" , "clang/lib/Sema/SemaType.cpp", 3598, __extension__ __PRETTY_FUNCTION__ )) | |||
3598 | "unknown auto type")(static_cast <bool> (isa<DeducedTemplateSpecializationType >(Deduced) && "unknown auto type") ? void (0) : __assert_fail ("isa<DeducedTemplateSpecializationType>(Deduced) && \"unknown auto type\"" , "clang/lib/Sema/SemaType.cpp", 3598, __extension__ __PRETTY_FUNCTION__ )); | |||
3599 | Kind = 3; | |||
3600 | } | |||
3601 | ||||
3602 | auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced); | |||
3603 | TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName(); | |||
3604 | ||||
3605 | SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) | |||
3606 | << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN) | |||
3607 | << QualType(Deduced, 0) << AutoRange; | |||
3608 | if (auto *TD = TN.getAsTemplateDecl()) | |||
3609 | SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here); | |||
3610 | ||||
3611 | T = SemaRef.Context.IntTy; | |||
3612 | D.setInvalidType(true); | |||
3613 | } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) { | |||
3614 | // If there was a trailing return type, we already got | |||
3615 | // warn_cxx98_compat_trailing_return_type in the parser. | |||
3616 | SemaRef.Diag(AutoRange.getBegin(), | |||
3617 | D.getContext() == DeclaratorContext::LambdaExprParameter | |||
3618 | ? diag::warn_cxx11_compat_generic_lambda | |||
3619 | : IsDeducedReturnType | |||
3620 | ? diag::warn_cxx11_compat_deduced_return_type | |||
3621 | : diag::warn_cxx98_compat_auto_type_specifier) | |||
3622 | << AutoRange; | |||
3623 | } | |||
3624 | } | |||
3625 | ||||
3626 | if (SemaRef.getLangOpts().CPlusPlus && | |||
3627 | OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { | |||
3628 | // Check the contexts where C++ forbids the declaration of a new class | |||
3629 | // or enumeration in a type-specifier-seq. | |||
3630 | unsigned DiagID = 0; | |||
3631 | switch (D.getContext()) { | |||
3632 | case DeclaratorContext::TrailingReturn: | |||
3633 | case DeclaratorContext::TrailingReturnVar: | |||
3634 | // Class and enumeration definitions are syntactically not allowed in | |||
3635 | // trailing return types. | |||
3636 | llvm_unreachable("parser should not have allowed this")::llvm::llvm_unreachable_internal("parser should not have allowed this" , "clang/lib/Sema/SemaType.cpp", 3636); | |||
3637 | break; | |||
3638 | case DeclaratorContext::File: | |||
3639 | case DeclaratorContext::Member: | |||
3640 | case DeclaratorContext::Block: | |||
3641 | case DeclaratorContext::ForInit: | |||
3642 | case DeclaratorContext::SelectionInit: | |||
3643 | case DeclaratorContext::BlockLiteral: | |||
3644 | case DeclaratorContext::LambdaExpr: | |||
3645 | // C++11 [dcl.type]p3: | |||
3646 | // A type-specifier-seq shall not define a class or enumeration unless | |||
3647 | // it appears in the type-id of an alias-declaration (7.1.3) that is not | |||
3648 | // the declaration of a template-declaration. | |||
3649 | case DeclaratorContext::AliasDecl: | |||
3650 | break; | |||
3651 | case DeclaratorContext::AliasTemplate: | |||
3652 | DiagID = diag::err_type_defined_in_alias_template; | |||
3653 | break; | |||
3654 | case DeclaratorContext::TypeName: | |||
3655 | case DeclaratorContext::FunctionalCast: | |||
3656 | case DeclaratorContext::ConversionId: | |||
3657 | case DeclaratorContext::TemplateParam: | |||
3658 | case DeclaratorContext::CXXNew: | |||
3659 | case DeclaratorContext::CXXCatch: | |||
3660 | case DeclaratorContext::ObjCCatch: | |||
3661 | case DeclaratorContext::TemplateArg: | |||
3662 | case DeclaratorContext::TemplateTypeArg: | |||
3663 | DiagID = diag::err_type_defined_in_type_specifier; | |||
3664 | break; | |||
3665 | case DeclaratorContext::Prototype: | |||
3666 | case DeclaratorContext::LambdaExprParameter: | |||
3667 | case DeclaratorContext::ObjCParameter: | |||
3668 | case DeclaratorContext::ObjCResult: | |||
3669 | case DeclaratorContext::KNRTypeList: | |||
3670 | case DeclaratorContext::RequiresExpr: | |||
3671 | // C++ [dcl.fct]p6: | |||
3672 | // Types shall not be defined in return or parameter types. | |||
3673 | DiagID = diag::err_type_defined_in_param_type; | |||
3674 | break; | |||
3675 | case DeclaratorContext::Condition: | |||
3676 | // C++ 6.4p2: | |||
3677 | // The type-specifier-seq shall not contain typedef and shall not declare | |||
3678 | // a new class or enumeration. | |||
3679 | DiagID = diag::err_type_defined_in_condition; | |||
3680 | break; | |||
3681 | } | |||
3682 | ||||
3683 | if (DiagID != 0) { | |||
3684 | SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID) | |||
3685 | << SemaRef.Context.getTypeDeclType(OwnedTagDecl); | |||
3686 | D.setInvalidType(true); | |||
3687 | } | |||
3688 | } | |||
3689 | ||||
3690 | assert(!T.isNull() && "This function should not return a null type")(static_cast <bool> (!T.isNull() && "This function should not return a null type" ) ? void (0) : __assert_fail ("!T.isNull() && \"This function should not return a null type\"" , "clang/lib/Sema/SemaType.cpp", 3690, __extension__ __PRETTY_FUNCTION__ )); | |||
3691 | return T; | |||
3692 | } | |||
3693 | ||||
3694 | /// Produce an appropriate diagnostic for an ambiguity between a function | |||
3695 | /// declarator and a C++ direct-initializer. | |||
3696 | static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, | |||
3697 | DeclaratorChunk &DeclType, QualType RT) { | |||
3698 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | |||
3699 | assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity")(static_cast <bool> (FTI.isAmbiguous && "no direct-initializer / function ambiguity" ) ? void (0) : __assert_fail ("FTI.isAmbiguous && \"no direct-initializer / function ambiguity\"" , "clang/lib/Sema/SemaType.cpp", 3699, __extension__ __PRETTY_FUNCTION__ )); | |||
3700 | ||||
3701 | // If the return type is void there is no ambiguity. | |||
3702 | if (RT->isVoidType()) | |||
3703 | return; | |||
3704 | ||||
3705 | // An initializer for a non-class type can have at most one argument. | |||
3706 | if (!RT->isRecordType() && FTI.NumParams > 1) | |||
3707 | return; | |||
3708 | ||||
3709 | // An initializer for a reference must have exactly one argument. | |||
3710 | if (RT->isReferenceType() && FTI.NumParams != 1) | |||
3711 | return; | |||
3712 | ||||
3713 | // Only warn if this declarator is declaring a function at block scope, and | |||
3714 | // doesn't have a storage class (such as 'extern') specified. | |||
3715 | if (!D.isFunctionDeclarator() || | |||
3716 | D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration || | |||
3717 | !S.CurContext->isFunctionOrMethod() || | |||
3718 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified) | |||
3719 | return; | |||
3720 | ||||
3721 | // Inside a condition, a direct initializer is not permitted. We allow one to | |||
3722 | // be parsed in order to give better diagnostics in condition parsing. | |||
3723 | if (D.getContext() == DeclaratorContext::Condition) | |||
3724 | return; | |||
3725 | ||||
3726 | SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); | |||
3727 | ||||
3728 | S.Diag(DeclType.Loc, | |||
3729 | FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration | |||
3730 | : diag::warn_empty_parens_are_function_decl) | |||
3731 | << ParenRange; | |||
3732 | ||||
3733 | // If the declaration looks like: | |||
3734 | // T var1, | |||
3735 | // f(); | |||
3736 | // and name lookup finds a function named 'f', then the ',' was | |||
3737 | // probably intended to be a ';'. | |||
3738 | if (!D.isFirstDeclarator() && D.getIdentifier()) { | |||
3739 | FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); | |||
3740 | FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); | |||
3741 | if (Comma.getFileID() != Name.getFileID() || | |||
3742 | Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { | |||
3743 | LookupResult Result(S, D.getIdentifier(), SourceLocation(), | |||
3744 | Sema::LookupOrdinaryName); | |||
3745 | if (S.LookupName(Result, S.getCurScope())) | |||
3746 | S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) | |||
3747 | << FixItHint::CreateReplacement(D.getCommaLoc(), ";") | |||
3748 | << D.getIdentifier(); | |||
3749 | Result.suppressDiagnostics(); | |||
3750 | } | |||
3751 | } | |||
3752 | ||||
3753 | if (FTI.NumParams > 0) { | |||
3754 | // For a declaration with parameters, eg. "T var(T());", suggest adding | |||
3755 | // parens around the first parameter to turn the declaration into a | |||
3756 | // variable declaration. | |||
3757 | SourceRange Range = FTI.Params[0].Param->getSourceRange(); | |||
3758 | SourceLocation B = Range.getBegin(); | |||
3759 | SourceLocation E = S.getLocForEndOfToken(Range.getEnd()); | |||
3760 | // FIXME: Maybe we should suggest adding braces instead of parens | |||
3761 | // in C++11 for classes that don't have an initializer_list constructor. | |||
3762 | S.Diag(B, diag::note_additional_parens_for_variable_declaration) | |||
3763 | << FixItHint::CreateInsertion(B, "(") | |||
3764 | << FixItHint::CreateInsertion(E, ")"); | |||
3765 | } else { | |||
3766 | // For a declaration without parameters, eg. "T var();", suggest replacing | |||
3767 | // the parens with an initializer to turn the declaration into a variable | |||
3768 | // declaration. | |||
3769 | const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); | |||
3770 | ||||
3771 | // Empty parens mean value-initialization, and no parens mean | |||
3772 | // default initialization. These are equivalent if the default | |||
3773 | // constructor is user-provided or if zero-initialization is a | |||
3774 | // no-op. | |||
3775 | if (RD && RD->hasDefinition() && | |||
3776 | (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) | |||
3777 | S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) | |||
3778 | << FixItHint::CreateRemoval(ParenRange); | |||
3779 | else { | |||
3780 | std::string Init = | |||
3781 | S.getFixItZeroInitializerForType(RT, ParenRange.getBegin()); | |||
3782 | if (Init.empty() && S.LangOpts.CPlusPlus11) | |||
3783 | Init = "{}"; | |||
3784 | if (!Init.empty()) | |||
3785 | S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) | |||
3786 | << FixItHint::CreateReplacement(ParenRange, Init); | |||
3787 | } | |||
3788 | } | |||
3789 | } | |||
3790 | ||||
3791 | /// Produce an appropriate diagnostic for a declarator with top-level | |||
3792 | /// parentheses. | |||
3793 | static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) { | |||
3794 | DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1); | |||
3795 | assert(Paren.Kind == DeclaratorChunk::Paren &&(static_cast <bool> (Paren.Kind == DeclaratorChunk::Paren && "do not have redundant top-level parentheses") ? void (0) : __assert_fail ("Paren.Kind == DeclaratorChunk::Paren && \"do not have redundant top-level parentheses\"" , "clang/lib/Sema/SemaType.cpp", 3796, __extension__ __PRETTY_FUNCTION__ )) | |||
3796 | "do not have redundant top-level parentheses")(static_cast <bool> (Paren.Kind == DeclaratorChunk::Paren && "do not have redundant top-level parentheses") ? void (0) : __assert_fail ("Paren.Kind == DeclaratorChunk::Paren && \"do not have redundant top-level parentheses\"" , "clang/lib/Sema/SemaType.cpp", 3796, __extension__ __PRETTY_FUNCTION__ )); | |||
3797 | ||||
3798 | // This is a syntactic check; we're not interested in cases that arise | |||
3799 | // during template instantiation. | |||
3800 | if (S.inTemplateInstantiation()) | |||
3801 | return; | |||
3802 | ||||
3803 | // Check whether this could be intended to be a construction of a temporary | |||
3804 | // object in C++ via a function-style cast. | |||
3805 | bool CouldBeTemporaryObject = | |||
3806 | S.getLangOpts().CPlusPlus && D.isExpressionContext() && | |||
3807 | !D.isInvalidType() && D.getIdentifier() && | |||
3808 | D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && | |||
3809 | (T->isRecordType() || T->isDependentType()) && | |||
3810 | D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator(); | |||
3811 | ||||
3812 | bool StartsWithDeclaratorId = true; | |||
3813 | for (auto &C : D.type_objects()) { | |||
3814 | switch (C.Kind) { | |||
3815 | case DeclaratorChunk::Paren: | |||
3816 | if (&C == &Paren) | |||
3817 | continue; | |||
3818 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
3819 | case DeclaratorChunk::Pointer: | |||
3820 | StartsWithDeclaratorId = false; | |||
3821 | continue; | |||
3822 | ||||
3823 | case DeclaratorChunk::Array: | |||
3824 | if (!C.Arr.NumElts) | |||
3825 | CouldBeTemporaryObject = false; | |||
3826 | continue; | |||
3827 | ||||
3828 | case DeclaratorChunk::Reference: | |||
3829 | // FIXME: Suppress the warning here if there is no initializer; we're | |||
3830 | // going to give an error anyway. | |||
3831 | // We assume that something like 'T (&x) = y;' is highly likely to not | |||
3832 | // be intended to be a temporary object. | |||
3833 | CouldBeTemporaryObject = false; | |||
3834 | StartsWithDeclaratorId = false; | |||
3835 | continue; | |||
3836 | ||||
3837 | case DeclaratorChunk::Function: | |||
3838 | // In a new-type-id, function chunks require parentheses. | |||
3839 | if (D.getContext() == DeclaratorContext::CXXNew) | |||
3840 | return; | |||
3841 | // FIXME: "A(f())" deserves a vexing-parse warning, not just a | |||
3842 | // redundant-parens warning, but we don't know whether the function | |||
3843 | // chunk was syntactically valid as an expression here. | |||
3844 | CouldBeTemporaryObject = false; | |||
3845 | continue; | |||
3846 | ||||
3847 | case DeclaratorChunk::BlockPointer: | |||
3848 | case DeclaratorChunk::MemberPointer: | |||
3849 | case DeclaratorChunk::Pipe: | |||
3850 | // These cannot appear in expressions. | |||
3851 | CouldBeTemporaryObject = false; | |||
3852 | StartsWithDeclaratorId = false; | |||
3853 | continue; | |||
3854 | } | |||
3855 | } | |||
3856 | ||||
3857 | // FIXME: If there is an initializer, assume that this is not intended to be | |||
3858 | // a construction of a temporary object. | |||
3859 | ||||
3860 | // Check whether the name has already been declared; if not, this is not a | |||
3861 | // function-style cast. | |||
3862 | if (CouldBeTemporaryObject) { | |||
3863 | LookupResult Result(S, D.getIdentifier(), SourceLocation(), | |||
3864 | Sema::LookupOrdinaryName); | |||
3865 | if (!S.LookupName(Result, S.getCurScope())) | |||
3866 | CouldBeTemporaryObject = false; | |||
3867 | Result.suppressDiagnostics(); | |||
3868 | } | |||
3869 | ||||
3870 | SourceRange ParenRange(Paren.Loc, Paren.EndLoc); | |||
3871 | ||||
3872 | if (!CouldBeTemporaryObject) { | |||
3873 | // If we have A (::B), the parentheses affect the meaning of the program. | |||
3874 | // Suppress the warning in that case. Don't bother looking at the DeclSpec | |||
3875 | // here: even (e.g.) "int ::x" is visually ambiguous even though it's | |||
3876 | // formally unambiguous. | |||
3877 | if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) { | |||
3878 | for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS; | |||
3879 | NNS = NNS->getPrefix()) { | |||
3880 | if (NNS->getKind() == NestedNameSpecifier::Global) | |||
3881 | return; | |||
3882 | } | |||
3883 | } | |||
3884 | ||||
3885 | S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator) | |||
3886 | << ParenRange << FixItHint::CreateRemoval(Paren.Loc) | |||
3887 | << FixItHint::CreateRemoval(Paren.EndLoc); | |||
3888 | return; | |||
3889 | } | |||
3890 | ||||
3891 | S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration) | |||
3892 | << ParenRange << D.getIdentifier(); | |||
3893 | auto *RD = T->getAsCXXRecordDecl(); | |||
3894 | if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor()) | |||
3895 | S.Diag(Paren.Loc, diag::note_raii_guard_add_name) | |||
3896 | << FixItHint::CreateInsertion(Paren.Loc, " varname") << T | |||
3897 | << D.getIdentifier(); | |||
3898 | // FIXME: A cast to void is probably a better suggestion in cases where it's | |||
3899 | // valid (when there is no initializer and we're not in a condition). | |||
3900 | S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses) | |||
3901 | << FixItHint::CreateInsertion(D.getBeginLoc(), "(") | |||
3902 | << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")"); | |||
3903 | S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration) | |||
3904 | << FixItHint::CreateRemoval(Paren.Loc) | |||
3905 | << FixItHint::CreateRemoval(Paren.EndLoc); | |||
3906 | } | |||
3907 | ||||
3908 | /// Helper for figuring out the default CC for a function declarator type. If | |||
3909 | /// this is the outermost chunk, then we can determine the CC from the | |||
3910 | /// declarator context. If not, then this could be either a member function | |||
3911 | /// type or normal function type. | |||
3912 | static CallingConv getCCForDeclaratorChunk( | |||
3913 | Sema &S, Declarator &D, const ParsedAttributesView &AttrList, | |||
3914 | const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) { | |||
3915 | assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function)(static_cast <bool> (D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function) ? void (0) : __assert_fail ("D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function" , "clang/lib/Sema/SemaType.cpp", 3915, __extension__ __PRETTY_FUNCTION__ )); | |||
3916 | ||||
3917 | // Check for an explicit CC attribute. | |||
3918 | for (const ParsedAttr &AL : AttrList) { | |||
3919 | switch (AL.getKind()) { | |||
3920 | CALLING_CONV_ATTRS_CASELISTcase ParsedAttr::AT_CDecl: case ParsedAttr::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr::AT_ThisCall: case ParsedAttr ::AT_RegCall: case ParsedAttr::AT_Pascal: case ParsedAttr::AT_SwiftCall : case ParsedAttr::AT_SwiftAsyncCall: case ParsedAttr::AT_VectorCall : case ParsedAttr::AT_AArch64VectorPcs: case ParsedAttr::AT_MSABI : case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr ::AT_IntelOclBicc: case ParsedAttr::AT_PreserveMost: case ParsedAttr ::AT_PreserveAll : { | |||
3921 | // Ignore attributes that don't validate or can't apply to the | |||
3922 | // function type. We'll diagnose the failure to apply them in | |||
3923 | // handleFunctionTypeAttr. | |||
3924 | CallingConv CC; | |||
3925 | if (!S.CheckCallingConvAttr(AL, CC) && | |||
3926 | (!FTI.isVariadic || supportsVariadicCall(CC))) { | |||
3927 | return CC; | |||
3928 | } | |||
3929 | break; | |||
3930 | } | |||
3931 | ||||
3932 | default: | |||
3933 | break; | |||
3934 | } | |||
3935 | } | |||
3936 | ||||
3937 | bool IsCXXInstanceMethod = false; | |||
3938 | ||||
3939 | if (S.getLangOpts().CPlusPlus) { | |||
3940 | // Look inwards through parentheses to see if this chunk will form a | |||
3941 | // member pointer type or if we're the declarator. Any type attributes | |||
3942 | // between here and there will override the CC we choose here. | |||
3943 | unsigned I = ChunkIndex; | |||
3944 | bool FoundNonParen = false; | |||
3945 | while (I && !FoundNonParen) { | |||
3946 | --I; | |||
3947 | if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren) | |||
3948 | FoundNonParen = true; | |||
3949 | } | |||
3950 | ||||
3951 | if (FoundNonParen) { | |||
3952 | // If we're not the declarator, we're a regular function type unless we're | |||
3953 | // in a member pointer. | |||
3954 | IsCXXInstanceMethod = | |||
3955 | D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer; | |||
3956 | } else if (D.getContext() == DeclaratorContext::LambdaExpr) { | |||
3957 | // This can only be a call operator for a lambda, which is an instance | |||
3958 | // method. | |||
3959 | IsCXXInstanceMethod = true; | |||
3960 | } else { | |||
3961 | // We're the innermost decl chunk, so must be a function declarator. | |||
3962 | assert(D.isFunctionDeclarator())(static_cast <bool> (D.isFunctionDeclarator()) ? void ( 0) : __assert_fail ("D.isFunctionDeclarator()", "clang/lib/Sema/SemaType.cpp" , 3962, __extension__ __PRETTY_FUNCTION__)); | |||
3963 | ||||
3964 | // If we're inside a record, we're declaring a method, but it could be | |||
3965 | // explicitly or implicitly static. | |||
3966 | IsCXXInstanceMethod = | |||
3967 | D.isFirstDeclarationOfMember() && | |||
3968 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && | |||
3969 | !D.isStaticMember(); | |||
3970 | } | |||
3971 | } | |||
3972 | ||||
3973 | CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic, | |||
3974 | IsCXXInstanceMethod); | |||
3975 | ||||
3976 | // Attribute AT_OpenCLKernel affects the calling convention for SPIR | |||
3977 | // and AMDGPU targets, hence it cannot be treated as a calling | |||
3978 | // convention attribute. This is the simplest place to infer | |||
3979 | // calling convention for OpenCL kernels. | |||
3980 | if (S.getLangOpts().OpenCL) { | |||
3981 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { | |||
3982 | if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) { | |||
3983 | CC = CC_OpenCLKernel; | |||
3984 | break; | |||
3985 | } | |||
3986 | } | |||
3987 | } else if (S.getLangOpts().CUDA) { | |||
3988 | // If we're compiling CUDA/HIP code and targeting SPIR-V we need to make | |||
3989 | // sure the kernels will be marked with the right calling convention so that | |||
3990 | // they will be visible by the APIs that ingest SPIR-V. | |||
3991 | llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); | |||
3992 | if (Triple.getArch() == llvm::Triple::spirv32 || | |||
3993 | Triple.getArch() == llvm::Triple::spirv64) { | |||
3994 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { | |||
3995 | if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) { | |||
3996 | CC = CC_OpenCLKernel; | |||
3997 | break; | |||
3998 | } | |||
3999 | } | |||
4000 | } | |||
4001 | } | |||
4002 | ||||
4003 | return CC; | |||
4004 | } | |||
4005 | ||||
4006 | namespace { | |||
4007 | /// A simple notion of pointer kinds, which matches up with the various | |||
4008 | /// pointer declarators. | |||
4009 | enum class SimplePointerKind { | |||
4010 | Pointer, | |||
4011 | BlockPointer, | |||
4012 | MemberPointer, | |||
4013 | Array, | |||
4014 | }; | |||
4015 | } // end anonymous namespace | |||
4016 | ||||
4017 | IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { | |||
4018 | switch (nullability) { | |||
4019 | case NullabilityKind::NonNull: | |||
4020 | if (!Ident__Nonnull) | |||
4021 | Ident__Nonnull = PP.getIdentifierInfo("_Nonnull"); | |||
4022 | return Ident__Nonnull; | |||
4023 | ||||
4024 | case NullabilityKind::Nullable: | |||
4025 | if (!Ident__Nullable) | |||
4026 | Ident__Nullable = PP.getIdentifierInfo("_Nullable"); | |||
4027 | return Ident__Nullable; | |||
4028 | ||||
4029 | case NullabilityKind::NullableResult: | |||
4030 | if (!Ident__Nullable_result) | |||
4031 | Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result"); | |||
4032 | return Ident__Nullable_result; | |||
4033 | ||||
4034 | case NullabilityKind::Unspecified: | |||
4035 | if (!Ident__Null_unspecified) | |||
4036 | Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified"); | |||
4037 | return Ident__Null_unspecified; | |||
4038 | } | |||
4039 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "clang/lib/Sema/SemaType.cpp", 4039); | |||
4040 | } | |||
4041 | ||||
4042 | /// Retrieve the identifier "NSError". | |||
4043 | IdentifierInfo *Sema::getNSErrorIdent() { | |||
4044 | if (!Ident_NSError) | |||
4045 | Ident_NSError = PP.getIdentifierInfo("NSError"); | |||
4046 | ||||
4047 | return Ident_NSError; | |||
4048 | } | |||
4049 | ||||
4050 | /// Check whether there is a nullability attribute of any kind in the given | |||
4051 | /// attribute list. | |||
4052 | static bool hasNullabilityAttr(const ParsedAttributesView &attrs) { | |||
4053 | for (const ParsedAttr &AL : attrs) { | |||
4054 | if (AL.getKind() == ParsedAttr::AT_TypeNonNull || | |||
4055 | AL.getKind() == ParsedAttr::AT_TypeNullable || | |||
4056 | AL.getKind() == ParsedAttr::AT_TypeNullableResult || | |||
4057 | AL.getKind() == ParsedAttr::AT_TypeNullUnspecified) | |||
4058 | return true; | |||
4059 | } | |||
4060 | ||||
4061 | return false; | |||
4062 | } | |||
4063 | ||||
4064 | namespace { | |||
4065 | /// Describes the kind of a pointer a declarator describes. | |||
4066 | enum class PointerDeclaratorKind { | |||
4067 | // Not a pointer. | |||
4068 | NonPointer, | |||
4069 | // Single-level pointer. | |||
4070 | SingleLevelPointer, | |||
4071 | // Multi-level pointer (of any pointer kind). | |||
4072 | MultiLevelPointer, | |||
4073 | // CFFooRef* | |||
4074 | MaybePointerToCFRef, | |||
4075 | // CFErrorRef* | |||
4076 | CFErrorRefPointer, | |||
4077 | // NSError** | |||
4078 | NSErrorPointerPointer, | |||
4079 | }; | |||
4080 | ||||
4081 | /// Describes a declarator chunk wrapping a pointer that marks inference as | |||
4082 | /// unexpected. | |||
4083 | // These values must be kept in sync with diagnostics. | |||
4084 | enum class PointerWrappingDeclaratorKind { | |||
4085 | /// Pointer is top-level. | |||
4086 | None = -1, | |||
4087 | /// Pointer is an array element. | |||
4088 | Array = 0, | |||
4089 | /// Pointer is the referent type of a C++ reference. | |||
4090 | Reference = 1 | |||
4091 | }; | |||
4092 | } // end anonymous namespace | |||
4093 | ||||
4094 | /// Classify the given declarator, whose type-specified is \c type, based on | |||
4095 | /// what kind of pointer it refers to. | |||
4096 | /// | |||
4097 | /// This is used to determine the default nullability. | |||
4098 | static PointerDeclaratorKind | |||
4099 | classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, | |||
4100 | PointerWrappingDeclaratorKind &wrappingKind) { | |||
4101 | unsigned numNormalPointers = 0; | |||
4102 | ||||
4103 | // For any dependent type, we consider it a non-pointer. | |||
4104 | if (type->isDependentType()) | |||
4105 | return PointerDeclaratorKind::NonPointer; | |||
4106 | ||||
4107 | // Look through the declarator chunks to identify pointers. | |||
4108 | for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { | |||
4109 | DeclaratorChunk &chunk = declarator.getTypeObject(i); | |||
4110 | switch (chunk.Kind) { | |||
4111 | case DeclaratorChunk::Array: | |||
4112 | if (numNormalPointers == 0) | |||
4113 | wrappingKind = PointerWrappingDeclaratorKind::Array; | |||
4114 | break; | |||
4115 | ||||
4116 | case DeclaratorChunk::Function: | |||
4117 | case DeclaratorChunk::Pipe: | |||
4118 | break; | |||
4119 | ||||
4120 | case DeclaratorChunk::BlockPointer: | |||
4121 | case DeclaratorChunk::MemberPointer: | |||
4122 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | |||
4123 | : PointerDeclaratorKind::SingleLevelPointer; | |||
4124 | ||||
4125 | case DeclaratorChunk::Paren: | |||
4126 | break; | |||
4127 | ||||
4128 | case DeclaratorChunk::Reference: | |||
4129 | if (numNormalPointers == 0) | |||
4130 | wrappingKind = PointerWrappingDeclaratorKind::Reference; | |||
4131 | break; | |||
4132 | ||||
4133 | case DeclaratorChunk::Pointer: | |||
4134 | ++numNormalPointers; | |||
4135 | if (numNormalPointers > 2) | |||
4136 | return PointerDeclaratorKind::MultiLevelPointer; | |||
4137 | break; | |||
4138 | } | |||
4139 | } | |||
4140 | ||||
4141 | // Then, dig into the type specifier itself. | |||
4142 | unsigned numTypeSpecifierPointers = 0; | |||
4143 | do { | |||
4144 | // Decompose normal pointers. | |||
4145 | if (auto ptrType = type->getAs<PointerType>()) { | |||
4146 | ++numNormalPointers; | |||
4147 | ||||
4148 | if (numNormalPointers > 2) | |||
4149 | return PointerDeclaratorKind::MultiLevelPointer; | |||
4150 | ||||
4151 | type = ptrType->getPointeeType(); | |||
4152 | ++numTypeSpecifierPointers; | |||
4153 | continue; | |||
4154 | } | |||
4155 | ||||
4156 | // Decompose block pointers. | |||
4157 | if (type->getAs<BlockPointerType>()) { | |||
4158 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | |||
4159 | : PointerDeclaratorKind::SingleLevelPointer; | |||
4160 | } | |||
4161 | ||||
4162 | // Decompose member pointers. | |||
4163 | if (type->getAs<MemberPointerType>()) { | |||
4164 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer | |||
4165 | : PointerDeclaratorKind::SingleLevelPointer; | |||
4166 | } | |||
4167 | ||||
4168 | // Look at Objective-C object pointers. | |||
4169 | if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { | |||
4170 | ++numNormalPointers; | |||
4171 | ++numTypeSpecifierPointers; | |||
4172 | ||||
4173 | // If this is NSError**, report that. | |||
4174 | if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { | |||
4175 | if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() && | |||
4176 | numNormalPointers == 2 && numTypeSpecifierPointers < 2) { | |||
4177 | return PointerDeclaratorKind::NSErrorPointerPointer; | |||
4178 | } | |||
4179 | } | |||
4180 | ||||
4181 | break; | |||
4182 | } | |||
4183 | ||||
4184 | // Look at Objective-C class types. | |||
4185 | if (auto objcClass = type->getAs<ObjCInterfaceType>()) { | |||
4186 | if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) { | |||
4187 | if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) | |||
4188 | return PointerDeclaratorKind::NSErrorPointerPointer; | |||
4189 | } | |||
4190 | ||||
4191 | break; | |||
4192 | } | |||
4193 | ||||
4194 | // If at this point we haven't seen a pointer, we won't see one. | |||
4195 | if (numNormalPointers == 0) | |||
4196 | return PointerDeclaratorKind::NonPointer; | |||
4197 | ||||
4198 | if (auto recordType = type->getAs<RecordType>()) { | |||
4199 | RecordDecl *recordDecl = recordType->getDecl(); | |||
4200 | ||||
4201 | // If this is CFErrorRef*, report it as such. | |||
4202 | if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 && | |||
4203 | S.isCFError(recordDecl)) { | |||
4204 | return PointerDeclaratorKind::CFErrorRefPointer; | |||
4205 | } | |||
4206 | break; | |||
4207 | } | |||
4208 | ||||
4209 | break; | |||
4210 | } while (true); | |||
4211 | ||||
4212 | switch (numNormalPointers) { | |||
4213 | case 0: | |||
4214 | return PointerDeclaratorKind::NonPointer; | |||
4215 | ||||
4216 | case 1: | |||
4217 | return PointerDeclaratorKind::SingleLevelPointer; | |||
4218 | ||||
4219 | case 2: | |||
4220 | return PointerDeclaratorKind::MaybePointerToCFRef; | |||
4221 | ||||
4222 | default: | |||
4223 | return PointerDeclaratorKind::MultiLevelPointer; | |||
4224 | } | |||
4225 | } | |||
4226 | ||||
4227 | bool Sema::isCFError(RecordDecl *RD) { | |||
4228 | // If we already know about CFError, test it directly. | |||
4229 | if (CFError) | |||
4230 | return CFError == RD; | |||
4231 | ||||
4232 | // Check whether this is CFError, which we identify based on its bridge to | |||
4233 | // NSError. CFErrorRef used to be declared with "objc_bridge" but is now | |||
4234 | // declared with "objc_bridge_mutable", so look for either one of the two | |||
4235 | // attributes. | |||
4236 | if (RD->getTagKind() == TTK_Struct) { | |||
4237 | IdentifierInfo *bridgedType = nullptr; | |||
4238 | if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>()) | |||
4239 | bridgedType = bridgeAttr->getBridgedType(); | |||
4240 | else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>()) | |||
4241 | bridgedType = bridgeAttr->getBridgedType(); | |||
4242 | ||||
4243 | if (bridgedType == getNSErrorIdent()) { | |||
4244 | CFError = RD; | |||
4245 | return true; | |||
4246 | } | |||
4247 | } | |||
4248 | ||||
4249 | return false; | |||
4250 | } | |||
4251 | ||||
4252 | static FileID getNullabilityCompletenessCheckFileID(Sema &S, | |||
4253 | SourceLocation loc) { | |||
4254 | // If we're anywhere in a function, method, or closure context, don't perform | |||
4255 | // completeness checks. | |||
4256 | for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { | |||
4257 | if (ctx->isFunctionOrMethod()) | |||
4258 | return FileID(); | |||
4259 | ||||
4260 | if (ctx->isFileContext()) | |||
4261 | break; | |||
4262 | } | |||
4263 | ||||
4264 | // We only care about the expansion location. | |||
4265 | loc = S.SourceMgr.getExpansionLoc(loc); | |||
4266 | FileID file = S.SourceMgr.getFileID(loc); | |||
4267 | if (file.isInvalid()) | |||
4268 | return FileID(); | |||
4269 | ||||
4270 | // Retrieve file information. | |||
4271 | bool invalid = false; | |||
4272 | const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid); | |||
4273 | if (invalid || !sloc.isFile()) | |||
4274 | return FileID(); | |||
4275 | ||||
4276 | // We don't want to perform completeness checks on the main file or in | |||
4277 | // system headers. | |||
4278 | const SrcMgr::FileInfo &fileInfo = sloc.getFile(); | |||
4279 | if (fileInfo.getIncludeLoc().isInvalid()) | |||
4280 | return FileID(); | |||
4281 | if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && | |||
4282 | S.Diags.getSuppressSystemWarnings()) { | |||
4283 | return FileID(); | |||
4284 | } | |||
4285 | ||||
4286 | return file; | |||
4287 | } | |||
4288 | ||||
4289 | /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc, | |||
4290 | /// taking into account whitespace before and after. | |||
4291 | template <typename DiagBuilderT> | |||
4292 | static void fixItNullability(Sema &S, DiagBuilderT &Diag, | |||
4293 | SourceLocation PointerLoc, | |||
4294 | NullabilityKind Nullability) { | |||
4295 | assert(PointerLoc.isValid())(static_cast <bool> (PointerLoc.isValid()) ? void (0) : __assert_fail ("PointerLoc.isValid()", "clang/lib/Sema/SemaType.cpp" , 4295, __extension__ __PRETTY_FUNCTION__)); | |||
4296 | if (PointerLoc.isMacroID()) | |||
4297 | return; | |||
4298 | ||||
4299 | SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc); | |||
4300 | if (!FixItLoc.isValid() || FixItLoc == PointerLoc) | |||
4301 | return; | |||
4302 | ||||
4303 | const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc); | |||
4304 | if (!NextChar) | |||
4305 | return; | |||
4306 | ||||
4307 | SmallString<32> InsertionTextBuf{" "}; | |||
4308 | InsertionTextBuf += getNullabilitySpelling(Nullability); | |||
4309 | InsertionTextBuf += " "; | |||
4310 | StringRef InsertionText = InsertionTextBuf.str(); | |||
4311 | ||||
4312 | if (isWhitespace(*NextChar)) { | |||
4313 | InsertionText = InsertionText.drop_back(); | |||
4314 | } else if (NextChar[-1] == '[') { | |||
4315 | if (NextChar[0] == ']') | |||
4316 | InsertionText = InsertionText.drop_back().drop_front(); | |||
4317 | else | |||
4318 | InsertionText = InsertionText.drop_front(); | |||
4319 | } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) && | |||
4320 | !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) { | |||
4321 | InsertionText = InsertionText.drop_back().drop_front(); | |||
4322 | } | |||
4323 | ||||
4324 | Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText); | |||
4325 | } | |||
4326 | ||||
4327 | static void emitNullabilityConsistencyWarning(Sema &S, | |||
4328 | SimplePointerKind PointerKind, | |||
4329 | SourceLocation PointerLoc, | |||
4330 | SourceLocation PointerEndLoc) { | |||
4331 | assert(PointerLoc.isValid())(static_cast <bool> (PointerLoc.isValid()) ? void (0) : __assert_fail ("PointerLoc.isValid()", "clang/lib/Sema/SemaType.cpp" , 4331, __extension__ __PRETTY_FUNCTION__)); | |||
4332 | ||||
4333 | if (PointerKind == SimplePointerKind::Array) { | |||
4334 | S.Diag(PointerLoc, diag::warn_nullability_missing_array); | |||
4335 | } else { | |||
4336 | S.Diag(PointerLoc, diag::warn_nullability_missing) | |||
4337 | << static_cast<unsigned>(PointerKind); | |||
4338 | } | |||
4339 | ||||
4340 | auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc; | |||
4341 | if (FixItLoc.isMacroID()) | |||
4342 | return; | |||
4343 | ||||
4344 | auto addFixIt = [&](NullabilityKind Nullability) { | |||
4345 | auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it); | |||
4346 | Diag << static_cast<unsigned>(Nullability); | |||
4347 | Diag << static_cast<unsigned>(PointerKind); | |||
4348 | fixItNullability(S, Diag, FixItLoc, Nullability); | |||
4349 | }; | |||
4350 | addFixIt(NullabilityKind::Nullable); | |||
4351 | addFixIt(NullabilityKind::NonNull); | |||
4352 | } | |||
4353 | ||||
4354 | /// Complains about missing nullability if the file containing \p pointerLoc | |||
4355 | /// has other uses of nullability (either the keywords or the \c assume_nonnull | |||
4356 | /// pragma). | |||
4357 | /// | |||
4358 | /// If the file has \e not seen other uses of nullability, this particular | |||
4359 | /// pointer is saved for possible later diagnosis. See recordNullabilitySeen(). | |||
4360 | static void | |||
4361 | checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, | |||
4362 | SourceLocation pointerLoc, | |||
4363 | SourceLocation pointerEndLoc = SourceLocation()) { | |||
4364 | // Determine which file we're performing consistency checking for. | |||
4365 | FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc); | |||
4366 | if (file.isInvalid()) | |||
4367 | return; | |||
4368 | ||||
4369 | // If we haven't seen any type nullability in this file, we won't warn now | |||
4370 | // about anything. | |||
4371 | FileNullability &fileNullability = S.NullabilityMap[file]; | |||
4372 | if (!fileNullability.SawTypeNullability) { | |||
4373 | // If this is the first pointer declarator in the file, and the appropriate | |||
4374 | // warning is on, record it in case we need to diagnose it retroactively. | |||
4375 | diag::kind diagKind; | |||
4376 | if (pointerKind == SimplePointerKind::Array) | |||
4377 | diagKind = diag::warn_nullability_missing_array; | |||
4378 | else | |||
4379 | diagKind = diag::warn_nullability_missing; | |||
4380 | ||||
4381 | if (fileNullability.PointerLoc.isInvalid() && | |||
4382 | !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) { | |||
4383 | fileNullability.PointerLoc = pointerLoc; | |||
4384 | fileNullability.PointerEndLoc = pointerEndLoc; | |||
4385 | fileNullability.PointerKind = static_cast<unsigned>(pointerKind); | |||
4386 | } | |||
4387 | ||||
4388 | return; | |||
4389 | } | |||
4390 | ||||
4391 | // Complain about missing nullability. | |||
4392 | emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc); | |||
4393 | } | |||
4394 | ||||
4395 | /// Marks that a nullability feature has been used in the file containing | |||
4396 | /// \p loc. | |||
4397 | /// | |||
4398 | /// If this file already had pointer types in it that were missing nullability, | |||
4399 | /// the first such instance is retroactively diagnosed. | |||
4400 | /// | |||
4401 | /// \sa checkNullabilityConsistency | |||
4402 | static void recordNullabilitySeen(Sema &S, SourceLocation loc) { | |||
4403 | FileID file = getNullabilityCompletenessCheckFileID(S, loc); | |||
4404 | if (file.isInvalid()) | |||
4405 | return; | |||
4406 | ||||
4407 | FileNullability &fileNullability = S.NullabilityMap[file]; | |||
4408 | if (fileNullability.SawTypeNullability) | |||
4409 | return; | |||
4410 | fileNullability.SawTypeNullability = true; | |||
4411 | ||||
4412 | // If we haven't seen any type nullability before, now we have. Retroactively | |||
4413 | // diagnose the first unannotated pointer, if there was one. | |||
4414 | if (fileNullability.PointerLoc.isInvalid()) | |||
4415 | return; | |||
4416 | ||||
4417 | auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind); | |||
4418 | emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc, | |||
4419 | fileNullability.PointerEndLoc); | |||
4420 | } | |||
4421 | ||||
4422 | /// Returns true if any of the declarator chunks before \p endIndex include a | |||
4423 | /// level of indirection: array, pointer, reference, or pointer-to-member. | |||
4424 | /// | |||
4425 | /// Because declarator chunks are stored in outer-to-inner order, testing | |||
4426 | /// every chunk before \p endIndex is testing all chunks that embed the current | |||
4427 | /// chunk as part of their type. | |||
4428 | /// | |||
4429 | /// It is legal to pass the result of Declarator::getNumTypeObjects() as the | |||
4430 | /// end index, in which case all chunks are tested. | |||
4431 | static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) { | |||
4432 | unsigned i = endIndex; | |||
4433 | while (i != 0) { | |||
4434 | // Walk outwards along the declarator chunks. | |||
4435 | --i; | |||
4436 | const DeclaratorChunk &DC = D.getTypeObject(i); | |||
4437 | switch (DC.Kind) { | |||
4438 | case DeclaratorChunk::Paren: | |||
4439 | break; | |||
4440 | case DeclaratorChunk::Array: | |||
4441 | case DeclaratorChunk::Pointer: | |||
4442 | case DeclaratorChunk::Reference: | |||
4443 | case DeclaratorChunk::MemberPointer: | |||
4444 | return true; | |||
4445 | case DeclaratorChunk::Function: | |||
4446 | case DeclaratorChunk::BlockPointer: | |||
4447 | case DeclaratorChunk::Pipe: | |||
4448 | // These are invalid anyway, so just ignore. | |||
4449 | break; | |||
4450 | } | |||
4451 | } | |||
4452 | return false; | |||
4453 | } | |||
4454 | ||||
4455 | static bool IsNoDerefableChunk(DeclaratorChunk Chunk) { | |||
4456 | return (Chunk.Kind == DeclaratorChunk::Pointer || | |||
4457 | Chunk.Kind == DeclaratorChunk::Array); | |||
4458 | } | |||
4459 | ||||
4460 | template<typename AttrT> | |||
4461 | static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) { | |||
4462 | AL.setUsedAsTypeAttr(); | |||
4463 | return ::new (Ctx) AttrT(Ctx, AL); | |||
4464 | } | |||
4465 | ||||
4466 | static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, | |||
4467 | NullabilityKind NK) { | |||
4468 | switch (NK) { | |||
4469 | case NullabilityKind::NonNull: | |||
4470 | return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr); | |||
4471 | ||||
4472 | case NullabilityKind::Nullable: | |||
4473 | return createSimpleAttr<TypeNullableAttr>(Ctx, Attr); | |||
4474 | ||||
4475 | case NullabilityKind::NullableResult: | |||
4476 | return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr); | |||
4477 | ||||
4478 | case NullabilityKind::Unspecified: | |||
4479 | return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr); | |||
4480 | } | |||
4481 | llvm_unreachable("unknown NullabilityKind")::llvm::llvm_unreachable_internal("unknown NullabilityKind", "clang/lib/Sema/SemaType.cpp" , 4481); | |||
4482 | } | |||
4483 | ||||
4484 | // Diagnose whether this is a case with the multiple addr spaces. | |||
4485 | // Returns true if this is an invalid case. | |||
4486 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified | |||
4487 | // by qualifiers for two or more different address spaces." | |||
4488 | static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld, | |||
4489 | LangAS ASNew, | |||
4490 | SourceLocation AttrLoc) { | |||
4491 | if (ASOld != LangAS::Default) { | |||
4492 | if (ASOld != ASNew) { | |||
4493 | S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); | |||
4494 | return true; | |||
4495 | } | |||
4496 | // Emit a warning if they are identical; it's likely unintended. | |||
4497 | S.Diag(AttrLoc, | |||
4498 | diag::warn_attribute_address_multiple_identical_qualifiers); | |||
4499 | } | |||
4500 | return false; | |||
4501 | } | |||
4502 | ||||
4503 | static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, | |||
4504 | QualType declSpecType, | |||
4505 | TypeSourceInfo *TInfo) { | |||
4506 | // The TypeSourceInfo that this function returns will not be a null type. | |||
4507 | // If there is an error, this function will fill in a dummy type as fallback. | |||
4508 | QualType T = declSpecType; | |||
4509 | Declarator &D = state.getDeclarator(); | |||
4510 | Sema &S = state.getSema(); | |||
4511 | ASTContext &Context = S.Context; | |||
4512 | const LangOptions &LangOpts = S.getLangOpts(); | |||
4513 | ||||
4514 | // The name we're declaring, if any. | |||
4515 | DeclarationName Name; | |||
4516 | if (D.getIdentifier()) | |||
4517 | Name = D.getIdentifier(); | |||
4518 | ||||
4519 | // Does this declaration declare a typedef-name? | |||
4520 | bool IsTypedefName = | |||
4521 | D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || | |||
4522 | D.getContext() == DeclaratorContext::AliasDecl || | |||
4523 | D.getContext() == DeclaratorContext::AliasTemplate; | |||
4524 | ||||
4525 | // Does T refer to a function type with a cv-qualifier or a ref-qualifier? | |||
4526 | bool IsQualifiedFunction = T->isFunctionProtoType() && | |||
4527 | (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() || | |||
4528 | T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); | |||
4529 | ||||
4530 | // If T is 'decltype(auto)', the only declarators we can have are parens | |||
4531 | // and at most one function declarator if this is a function declaration. | |||
4532 | // If T is a deduced class template specialization type, we can have no | |||
4533 | // declarator chunks at all. | |||
4534 | if (auto *DT = T->getAs<DeducedType>()) { | |||
4535 | const AutoType *AT = T->getAs<AutoType>(); | |||
4536 | bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT); | |||
4537 | if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) { | |||
4538 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { | |||
4539 | unsigned Index = E - I - 1; | |||
4540 | DeclaratorChunk &DeclChunk = D.getTypeObject(Index); | |||
4541 | unsigned DiagId = IsClassTemplateDeduction | |||
4542 | ? diag::err_deduced_class_template_compound_type | |||
4543 | : diag::err_decltype_auto_compound_type; | |||
4544 | unsigned DiagKind = 0; | |||
4545 | switch (DeclChunk.Kind) { | |||
4546 | case DeclaratorChunk::Paren: | |||
4547 | // FIXME: Rejecting this is a little silly. | |||
4548 | if (IsClassTemplateDeduction) { | |||
4549 | DiagKind = 4; | |||
4550 | break; | |||
4551 | } | |||
4552 | continue; | |||
4553 | case DeclaratorChunk::Function: { | |||
4554 | if (IsClassTemplateDeduction) { | |||
4555 | DiagKind = 3; | |||
4556 | break; | |||
4557 | } | |||
4558 | unsigned FnIndex; | |||
4559 | if (D.isFunctionDeclarationContext() && | |||
4560 | D.isFunctionDeclarator(FnIndex) && FnIndex == Index) | |||
4561 | continue; | |||
4562 | DiagId = diag::err_decltype_auto_function_declarator_not_declaration; | |||
4563 | break; | |||
4564 | } | |||
4565 | case DeclaratorChunk::Pointer: | |||
4566 | case DeclaratorChunk::BlockPointer: | |||
4567 | case DeclaratorChunk::MemberPointer: | |||
4568 | DiagKind = 0; | |||
4569 | break; | |||
4570 | case DeclaratorChunk::Reference: | |||
4571 | DiagKind = 1; | |||
4572 | break; | |||
4573 | case DeclaratorChunk::Array: | |||
4574 | DiagKind = 2; | |||
4575 | break; | |||
4576 | case DeclaratorChunk::Pipe: | |||
4577 | break; | |||
4578 | } | |||
4579 | ||||
4580 | S.Diag(DeclChunk.Loc, DiagId) << DiagKind; | |||
4581 | D.setInvalidType(true); | |||
4582 | break; | |||
4583 | } | |||
4584 | } | |||
4585 | } | |||
4586 | ||||
4587 | // Determine whether we should infer _Nonnull on pointer types. | |||
4588 | Optional<NullabilityKind> inferNullability; | |||
4589 | bool inferNullabilityCS = false; | |||
4590 | bool inferNullabilityInnerOnly = false; | |||
4591 | bool inferNullabilityInnerOnlyComplete = false; | |||
4592 | ||||
4593 | // Are we in an assume-nonnull region? | |||
4594 | bool inAssumeNonNullRegion = false; | |||
4595 | SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc(); | |||
4596 | if (assumeNonNullLoc.isValid()) { | |||
4597 | inAssumeNonNullRegion = true; | |||
4598 | recordNullabilitySeen(S, assumeNonNullLoc); | |||
4599 | } | |||
4600 | ||||
4601 | // Whether to complain about missing nullability specifiers or not. | |||
4602 | enum { | |||
4603 | /// Never complain. | |||
4604 | CAMN_No, | |||
4605 | /// Complain on the inner pointers (but not the outermost | |||
4606 | /// pointer). | |||
4607 | CAMN_InnerPointers, | |||
4608 | /// Complain about any pointers that don't have nullability | |||
4609 | /// specified or inferred. | |||
4610 | CAMN_Yes | |||
4611 | } complainAboutMissingNullability = CAMN_No; | |||
4612 | unsigned NumPointersRemaining = 0; | |||
4613 | auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None; | |||
4614 | ||||
4615 | if (IsTypedefName) { | |||
4616 | // For typedefs, we do not infer any nullability (the default), | |||
4617 | // and we only complain about missing nullability specifiers on | |||
4618 | // inner pointers. | |||
4619 | complainAboutMissingNullability = CAMN_InnerPointers; | |||
4620 | ||||
4621 | if (T->canHaveNullability(/*ResultIfUnknown*/false) && | |||
4622 | !T->getNullability(S.Context)) { | |||
4623 | // Note that we allow but don't require nullability on dependent types. | |||
4624 | ++NumPointersRemaining; | |||
4625 | } | |||
4626 | ||||
4627 | for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { | |||
4628 | DeclaratorChunk &chunk = D.getTypeObject(i); | |||
4629 | switch (chunk.Kind) { | |||
4630 | case DeclaratorChunk::Array: | |||
4631 | case DeclaratorChunk::Function: | |||
4632 | case DeclaratorChunk::Pipe: | |||
4633 | break; | |||
4634 | ||||
4635 | case DeclaratorChunk::BlockPointer: | |||
4636 | case DeclaratorChunk::MemberPointer: | |||
4637 | ++NumPointersRemaining; | |||
4638 | break; | |||
4639 | ||||
4640 | case DeclaratorChunk::Paren: | |||
4641 | case DeclaratorChunk::Reference: | |||
4642 | continue; | |||
4643 | ||||
4644 | case DeclaratorChunk::Pointer: | |||
4645 | ++NumPointersRemaining; | |||
4646 | continue; | |||
4647 | } | |||
4648 | } | |||
4649 | } else { | |||
4650 | bool isFunctionOrMethod = false; | |||
4651 | switch (auto context = state.getDeclarator().getContext()) { | |||
4652 | case DeclaratorContext::ObjCParameter: | |||
4653 | case DeclaratorContext::ObjCResult: | |||
4654 | case DeclaratorContext::Prototype: | |||
4655 | case DeclaratorContext::TrailingReturn: | |||
4656 | case DeclaratorContext::TrailingReturnVar: | |||
4657 | isFunctionOrMethod = true; | |||
4658 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
4659 | ||||
4660 | case DeclaratorContext::Member: | |||
4661 | if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { | |||
4662 | complainAboutMissingNullability = CAMN_No; | |||
4663 | break; | |||
4664 | } | |||
4665 | ||||
4666 | // Weak properties are inferred to be nullable. | |||
4667 | if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) { | |||
4668 | inferNullability = NullabilityKind::Nullable; | |||
4669 | break; | |||
4670 | } | |||
4671 | ||||
4672 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
4673 | ||||
4674 | case DeclaratorContext::File: | |||
4675 | case DeclaratorContext::KNRTypeList: { | |||
4676 | complainAboutMissingNullability = CAMN_Yes; | |||
4677 | ||||
4678 | // Nullability inference depends on the type and declarator. | |||
4679 | auto wrappingKind = PointerWrappingDeclaratorKind::None; | |||
4680 | switch (classifyPointerDeclarator(S, T, D, wrappingKind)) { | |||
4681 | case PointerDeclaratorKind::NonPointer: | |||
4682 | case PointerDeclaratorKind::MultiLevelPointer: | |||
4683 | // Cannot infer nullability. | |||
4684 | break; | |||
4685 | ||||
4686 | case PointerDeclaratorKind::SingleLevelPointer: | |||
4687 | // Infer _Nonnull if we are in an assumes-nonnull region. | |||
4688 | if (inAssumeNonNullRegion) { | |||
4689 | complainAboutInferringWithinChunk = wrappingKind; | |||
4690 | inferNullability = NullabilityKind::NonNull; | |||
4691 | inferNullabilityCS = (context == DeclaratorContext::ObjCParameter || | |||
4692 | context == DeclaratorContext::ObjCResult); | |||
4693 | } | |||
4694 | break; | |||
4695 | ||||
4696 | case PointerDeclaratorKind::CFErrorRefPointer: | |||
4697 | case PointerDeclaratorKind::NSErrorPointerPointer: | |||
4698 | // Within a function or method signature, infer _Nullable at both | |||
4699 | // levels. | |||
4700 | if (isFunctionOrMethod && inAssumeNonNullRegion) | |||
4701 | inferNullability = NullabilityKind::Nullable; | |||
4702 | break; | |||
4703 | ||||
4704 | case PointerDeclaratorKind::MaybePointerToCFRef: | |||
4705 | if (isFunctionOrMethod) { | |||
4706 | // On pointer-to-pointer parameters marked cf_returns_retained or | |||
4707 | // cf_returns_not_retained, if the outer pointer is explicit then | |||
4708 | // infer the inner pointer as _Nullable. | |||
4709 | auto hasCFReturnsAttr = | |||
4710 | [](const ParsedAttributesView &AttrList) -> bool { | |||
4711 | return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) || | |||
4712 | AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained); | |||
4713 | }; | |||
4714 | if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { | |||
4715 | if (hasCFReturnsAttr(D.getAttributes()) || | |||
4716 | hasCFReturnsAttr(InnermostChunk->getAttrs()) || | |||
4717 | hasCFReturnsAttr(D.getDeclSpec().getAttributes())) { | |||
4718 | inferNullability = NullabilityKind::Nullable; | |||
4719 | inferNullabilityInnerOnly = true; | |||
4720 | } | |||
4721 | } | |||
4722 | } | |||
4723 | break; | |||
4724 | } | |||
4725 | break; | |||
4726 | } | |||
4727 | ||||
4728 | case DeclaratorContext::ConversionId: | |||
4729 | complainAboutMissingNullability = CAMN_Yes; | |||
4730 | break; | |||
4731 | ||||
4732 | case DeclaratorContext::AliasDecl: | |||
4733 | case DeclaratorContext::AliasTemplate: | |||
4734 | case DeclaratorContext::Block: | |||
4735 | case DeclaratorContext::BlockLiteral: | |||
4736 | case DeclaratorContext::Condition: | |||
4737 | case DeclaratorContext::CXXCatch: | |||
4738 | case DeclaratorContext::CXXNew: | |||
4739 | case DeclaratorContext::ForInit: | |||
4740 | case DeclaratorContext::SelectionInit: | |||
4741 | case DeclaratorContext::LambdaExpr: | |||
4742 | case DeclaratorContext::LambdaExprParameter: | |||
4743 | case DeclaratorContext::ObjCCatch: | |||
4744 | case DeclaratorContext::TemplateParam: | |||
4745 | case DeclaratorContext::TemplateArg: | |||
4746 | case DeclaratorContext::TemplateTypeArg: | |||
4747 | case DeclaratorContext::TypeName: | |||
4748 | case DeclaratorContext::FunctionalCast: | |||
4749 | case DeclaratorContext::RequiresExpr: | |||
4750 | // Don't infer in these contexts. | |||
4751 | break; | |||
4752 | } | |||
4753 | } | |||
4754 | ||||
4755 | // Local function that returns true if its argument looks like a va_list. | |||
4756 | auto isVaList = [&S](QualType T) -> bool { | |||
4757 | auto *typedefTy = T->getAs<TypedefType>(); | |||
4758 | if (!typedefTy) | |||
4759 | return false; | |||
4760 | TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl(); | |||
4761 | do { | |||
4762 | if (typedefTy->getDecl() == vaListTypedef) | |||
4763 | return true; | |||
4764 | if (auto *name = typedefTy->getDecl()->getIdentifier()) | |||
4765 | if (name->isStr("va_list")) | |||
4766 | return true; | |||
4767 | typedefTy = typedefTy->desugar()->getAs<TypedefType>(); | |||
4768 | } while (typedefTy); | |||
4769 | return false; | |||
4770 | }; | |||
4771 | ||||
4772 | // Local function that checks the nullability for a given pointer declarator. | |||
4773 | // Returns true if _Nonnull was inferred. | |||
4774 | auto inferPointerNullability = | |||
4775 | [&](SimplePointerKind pointerKind, SourceLocation pointerLoc, | |||
4776 | SourceLocation pointerEndLoc, | |||
4777 | ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * { | |||
4778 | // We've seen a pointer. | |||
4779 | if (NumPointersRemaining > 0) | |||
4780 | --NumPointersRemaining; | |||
4781 | ||||
4782 | // If a nullability attribute is present, there's nothing to do. | |||
4783 | if (hasNullabilityAttr(attrs)) | |||
4784 | return nullptr; | |||
4785 | ||||
4786 | // If we're supposed to infer nullability, do so now. | |||
4787 | if (inferNullability && !inferNullabilityInnerOnlyComplete) { | |||
4788 | ParsedAttr::Syntax syntax = inferNullabilityCS | |||
4789 | ? ParsedAttr::AS_ContextSensitiveKeyword | |||
4790 | : ParsedAttr::AS_Keyword; | |||
4791 | ParsedAttr *nullabilityAttr = Pool.create( | |||
4792 | S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc), | |||
4793 | nullptr, SourceLocation(), nullptr, 0, syntax); | |||
4794 | ||||
4795 | attrs.addAtEnd(nullabilityAttr); | |||
4796 | ||||
4797 | if (inferNullabilityCS) { | |||
4798 | state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() | |||
4799 | ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); | |||
4800 | } | |||
4801 | ||||
4802 | if (pointerLoc.isValid() && | |||
4803 | complainAboutInferringWithinChunk != | |||
4804 | PointerWrappingDeclaratorKind::None) { | |||
4805 | auto Diag = | |||
4806 | S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type); | |||
4807 | Diag << static_cast<int>(complainAboutInferringWithinChunk); | |||
4808 | fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull); | |||
4809 | } | |||
4810 | ||||
4811 | if (inferNullabilityInnerOnly) | |||
4812 | inferNullabilityInnerOnlyComplete = true; | |||
4813 | return nullabilityAttr; | |||
4814 | } | |||
4815 | ||||
4816 | // If we're supposed to complain about missing nullability, do so | |||
4817 | // now if it's truly missing. | |||
4818 | switch (complainAboutMissingNullability) { | |||
4819 | case CAMN_No: | |||
4820 | break; | |||
4821 | ||||
4822 | case CAMN_InnerPointers: | |||
4823 | if (NumPointersRemaining == 0) | |||
4824 | break; | |||
4825 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
4826 | ||||
4827 | case CAMN_Yes: | |||
4828 | checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc); | |||
4829 | } | |||
4830 | return nullptr; | |||
4831 | }; | |||
4832 | ||||
4833 | // If the type itself could have nullability but does not, infer pointer | |||
4834 | // nullability and perform consistency checking. | |||
4835 | if (S.CodeSynthesisContexts.empty()) { | |||
4836 | if (T->canHaveNullability(/*ResultIfUnknown*/false) && | |||
4837 | !T->getNullability(S.Context)) { | |||
4838 | if (isVaList(T)) { | |||
4839 | // Record that we've seen a pointer, but do nothing else. | |||
4840 | if (NumPointersRemaining > 0) | |||
4841 | --NumPointersRemaining; | |||
4842 | } else { | |||
4843 | SimplePointerKind pointerKind = SimplePointerKind::Pointer; | |||
4844 | if (T->isBlockPointerType()) | |||
4845 | pointerKind = SimplePointerKind::BlockPointer; | |||
4846 | else if (T->isMemberPointerType()) | |||
4847 | pointerKind = SimplePointerKind::MemberPointer; | |||
4848 | ||||
4849 | if (auto *attr = inferPointerNullability( | |||
4850 | pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), | |||
4851 | D.getDeclSpec().getEndLoc(), | |||
4852 | D.getMutableDeclSpec().getAttributes(), | |||
4853 | D.getMutableDeclSpec().getAttributePool())) { | |||
4854 | T = state.getAttributedType( | |||
4855 | createNullabilityAttr(Context, *attr, *inferNullability), T, T); | |||
4856 | } | |||
4857 | } | |||
4858 | } | |||
4859 | ||||
4860 | if (complainAboutMissingNullability == CAMN_Yes && | |||
4861 | T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) && | |||
4862 | D.isPrototypeContext() && | |||
4863 | !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) { | |||
4864 | checkNullabilityConsistency(S, SimplePointerKind::Array, | |||
4865 | D.getDeclSpec().getTypeSpecTypeLoc()); | |||
4866 | } | |||
4867 | } | |||
4868 | ||||
4869 | bool ExpectNoDerefChunk = | |||
4870 | state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref); | |||
4871 | ||||
4872 | // Walk the DeclTypeInfo, building the recursive type as we go. | |||
4873 | // DeclTypeInfos are ordered from the identifier out, which is | |||
4874 | // opposite of what we want :). | |||
4875 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
4876 | unsigned chunkIndex = e - i - 1; | |||
4877 | state.setCurrentChunkIndex(chunkIndex); | |||
4878 | DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex); | |||
4879 | IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; | |||
4880 | switch (DeclType.Kind) { | |||
4881 | case DeclaratorChunk::Paren: | |||
4882 | if (i == 0) | |||
4883 | warnAboutRedundantParens(S, D, T); | |||
4884 | T = S.BuildParenType(T); | |||
4885 | break; | |||
4886 | case DeclaratorChunk::BlockPointer: | |||
4887 | // If blocks are disabled, emit an error. | |||
4888 | if (!LangOpts.Blocks) | |||
4889 | S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL; | |||
4890 | ||||
4891 | // Handle pointer nullability. | |||
4892 | inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc, | |||
4893 | DeclType.EndLoc, DeclType.getAttrs(), | |||
4894 | state.getDeclarator().getAttributePool()); | |||
4895 | ||||
4896 | T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name); | |||
4897 | if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) { | |||
4898 | // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly | |||
4899 | // qualified with const. | |||
4900 | if (LangOpts.OpenCL) | |||
4901 | DeclType.Cls.TypeQuals |= DeclSpec::TQ_const; | |||
4902 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals); | |||
4903 | } | |||
4904 | break; | |||
4905 | case DeclaratorChunk::Pointer: | |||
4906 | // Verify that we're not building a pointer to pointer to function with | |||
4907 | // exception specification. | |||
4908 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | |||
4909 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | |||
4910 | D.setInvalidType(true); | |||
4911 | // Build the type anyway. | |||
4912 | } | |||
4913 | ||||
4914 | // Handle pointer nullability | |||
4915 | inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, | |||
4916 | DeclType.EndLoc, DeclType.getAttrs(), | |||
4917 | state.getDeclarator().getAttributePool()); | |||
4918 | ||||
4919 | if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) { | |||
4920 | T = Context.getObjCObjectPointerType(T); | |||
4921 | if (DeclType.Ptr.TypeQuals) | |||
4922 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); | |||
4923 | break; | |||
4924 | } | |||
4925 | ||||
4926 | // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used. | |||
4927 | // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used. | |||
4928 | // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed. | |||
4929 | if (LangOpts.OpenCL) { | |||
4930 | if (T->isImageType() || T->isSamplerT() || T->isPipeType() || | |||
4931 | T->isBlockPointerType()) { | |||
4932 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T; | |||
4933 | D.setInvalidType(true); | |||
4934 | } | |||
4935 | } | |||
4936 | ||||
4937 | T = S.BuildPointerType(T, DeclType.Loc, Name); | |||
4938 | if (DeclType.Ptr.TypeQuals) | |||
4939 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals); | |||
4940 | break; | |||
4941 | case DeclaratorChunk::Reference: { | |||
4942 | // Verify that we're not building a reference to pointer to function with | |||
4943 | // exception specification. | |||
4944 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | |||
4945 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | |||
4946 | D.setInvalidType(true); | |||
4947 | // Build the type anyway. | |||
4948 | } | |||
4949 | T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name); | |||
4950 | ||||
4951 | if (DeclType.Ref.HasRestrict) | |||
4952 | T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict); | |||
4953 | break; | |||
4954 | } | |||
4955 | case DeclaratorChunk::Array: { | |||
4956 | // Verify that we're not building an array of pointers to function with | |||
4957 | // exception specification. | |||
4958 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { | |||
4959 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); | |||
4960 | D.setInvalidType(true); | |||
4961 | // Build the type anyway. | |||
4962 | } | |||
4963 | DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; | |||
4964 | Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); | |||
4965 | ArrayType::ArraySizeModifier ASM; | |||
4966 | if (ATI.isStar) | |||
4967 | ASM = ArrayType::Star; | |||
4968 | else if (ATI.hasStatic) | |||
4969 | ASM = ArrayType::Static; | |||
4970 | else | |||
4971 | ASM = ArrayType::Normal; | |||
4972 | if (ASM == ArrayType::Star && !D.isPrototypeContext()) { | |||
4973 | // FIXME: This check isn't quite right: it allows star in prototypes | |||
4974 | // for function definitions, and disallows some edge cases detailed | |||
4975 | // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html | |||
4976 | S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); | |||
4977 | ASM = ArrayType::Normal; | |||
4978 | D.setInvalidType(true); | |||
4979 | } | |||
4980 | ||||
4981 | // C99 6.7.5.2p1: The optional type qualifiers and the keyword static | |||
4982 | // shall appear only in a declaration of a function parameter with an | |||
4983 | // array type, ... | |||
4984 | if (ASM == ArrayType::Static || ATI.TypeQuals) { | |||
4985 | if (!(D.isPrototypeContext() || | |||
4986 | D.getContext() == DeclaratorContext::KNRTypeList)) { | |||
4987 | S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) << | |||
4988 | (ASM == ArrayType::Static ? "'static'" : "type qualifier"); | |||
4989 | // Remove the 'static' and the type qualifiers. | |||
4990 | if (ASM == ArrayType::Static) | |||
4991 | ASM = ArrayType::Normal; | |||
4992 | ATI.TypeQuals = 0; | |||
4993 | D.setInvalidType(true); | |||
4994 | } | |||
4995 | ||||
4996 | // C99 6.7.5.2p1: ... and then only in the outermost array type | |||
4997 | // derivation. | |||
4998 | if (hasOuterPointerLikeChunk(D, chunkIndex)) { | |||
4999 | S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) << | |||
5000 | (ASM == ArrayType::Static ? "'static'" : "type qualifier"); | |||
5001 | if (ASM == ArrayType::Static) | |||
5002 | ASM = ArrayType::Normal; | |||
5003 | ATI.TypeQuals = 0; | |||
5004 | D.setInvalidType(true); | |||
5005 | } | |||
5006 | } | |||
5007 | const AutoType *AT = T->getContainedAutoType(); | |||
5008 | // Allow arrays of auto if we are a generic lambda parameter. | |||
5009 | // i.e. [](auto (&array)[5]) { return array[0]; }; OK | |||
5010 | if (AT && D.getContext() != DeclaratorContext::LambdaExprParameter) { | |||
5011 | // We've already diagnosed this for decltype(auto). | |||
5012 | if (!AT->isDecltypeAuto()) | |||
5013 | S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto) | |||
5014 | << getPrintableNameForEntity(Name) << T; | |||
5015 | T = QualType(); | |||
5016 | break; | |||
5017 | } | |||
5018 | ||||
5019 | // Array parameters can be marked nullable as well, although it's not | |||
5020 | // necessary if they're marked 'static'. | |||
5021 | if (complainAboutMissingNullability == CAMN_Yes && | |||
5022 | !hasNullabilityAttr(DeclType.getAttrs()) && | |||
5023 | ASM != ArrayType::Static && | |||
5024 | D.isPrototypeContext() && | |||
5025 | !hasOuterPointerLikeChunk(D, chunkIndex)) { | |||
5026 | checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc); | |||
5027 | } | |||
5028 | ||||
5029 | T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, | |||
5030 | SourceRange(DeclType.Loc, DeclType.EndLoc), Name); | |||
5031 | break; | |||
5032 | } | |||
5033 | case DeclaratorChunk::Function: { | |||
5034 | // If the function declarator has a prototype (i.e. it is not () and | |||
5035 | // does not have a K&R-style identifier list), then the arguments are part | |||
5036 | // of the type, otherwise the argument list is (). | |||
5037 | DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | |||
5038 | IsQualifiedFunction = | |||
5039 | FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier(); | |||
5040 | ||||
5041 | // Check for auto functions and trailing return type and adjust the | |||
5042 | // return type accordingly. | |||
5043 | if (!D.isInvalidType()) { | |||
5044 | // trailing-return-type is only required if we're declaring a function, | |||
5045 | // and not, for instance, a pointer to a function. | |||
5046 | if (D.getDeclSpec().hasAutoTypeSpec() && | |||
5047 | !FTI.hasTrailingReturnType() && chunkIndex == 0) { | |||
5048 | if (!S.getLangOpts().CPlusPlus14) { | |||
5049 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), | |||
5050 | D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto | |||
5051 | ? diag::err_auto_missing_trailing_return | |||
5052 | : diag::err_deduced_return_type); | |||
5053 | T = Context.IntTy; | |||
5054 | D.setInvalidType(true); | |||
5055 | } else { | |||
5056 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), | |||
5057 | diag::warn_cxx11_compat_deduced_return_type); | |||
5058 | } | |||
5059 | } else if (FTI.hasTrailingReturnType()) { | |||
5060 | // T must be exactly 'auto' at this point. See CWG issue 681. | |||
5061 | if (isa<ParenType>(T)) { | |||
5062 | S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens) | |||
5063 | << T << D.getSourceRange(); | |||
5064 | D.setInvalidType(true); | |||
5065 | } else if (D.getName().getKind() == | |||
5066 | UnqualifiedIdKind::IK_DeductionGuideName) { | |||
5067 | if (T != Context.DependentTy) { | |||
5068 | S.Diag(D.getDeclSpec().getBeginLoc(), | |||
5069 | diag::err_deduction_guide_with_complex_decl) | |||
5070 | << D.getSourceRange(); | |||
5071 | D.setInvalidType(true); | |||
5072 | } | |||
5073 | } else if (D.getContext() != DeclaratorContext::LambdaExpr && | |||
5074 | (T.hasQualifiers() || !isa<AutoType>(T) || | |||
5075 | cast<AutoType>(T)->getKeyword() != | |||
5076 | AutoTypeKeyword::Auto || | |||
5077 | cast<AutoType>(T)->isConstrained())) { | |||
5078 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), | |||
5079 | diag::err_trailing_return_without_auto) | |||
5080 | << T << D.getDeclSpec().getSourceRange(); | |||
5081 | D.setInvalidType(true); | |||
5082 | } | |||
5083 | T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo); | |||
5084 | if (T.isNull()) { | |||
5085 | // An error occurred parsing the trailing return type. | |||
5086 | T = Context.IntTy; | |||
5087 | D.setInvalidType(true); | |||
5088 | } else if (AutoType *Auto = T->getContainedAutoType()) { | |||
5089 | // If the trailing return type contains an `auto`, we may need to | |||
5090 | // invent a template parameter for it, for cases like | |||
5091 | // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`. | |||
5092 | InventedTemplateParameterInfo *InventedParamInfo = nullptr; | |||
5093 | if (D.getContext() == DeclaratorContext::Prototype) | |||
5094 | InventedParamInfo = &S.InventedParameterInfos.back(); | |||
5095 | else if (D.getContext() == DeclaratorContext::LambdaExprParameter) | |||
5096 | InventedParamInfo = S.getCurLambda(); | |||
5097 | if (InventedParamInfo) { | |||
5098 | std::tie(T, TInfo) = InventTemplateParameter( | |||
5099 | state, T, TInfo, Auto, *InventedParamInfo); | |||
5100 | } | |||
5101 | } | |||
5102 | } else { | |||
5103 | // This function type is not the type of the entity being declared, | |||
5104 | // so checking the 'auto' is not the responsibility of this chunk. | |||
5105 | } | |||
5106 | } | |||
5107 | ||||
5108 | // C99 6.7.5.3p1: The return type may not be a function or array type. | |||
5109 | // For conversion functions, we'll diagnose this particular error later. | |||
5110 | if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) && | |||
5111 | (D.getName().getKind() != | |||
5112 | UnqualifiedIdKind::IK_ConversionFunctionId)) { | |||
5113 | unsigned diagID = diag::err_func_returning_array_function; | |||
5114 | // Last processing chunk in block context means this function chunk | |||
5115 | // represents the block. | |||
5116 | if (chunkIndex == 0 && | |||
5117 | D.getContext() == DeclaratorContext::BlockLiteral) | |||
5118 | diagID = diag::err_block_returning_array_function; | |||
5119 | S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T; | |||
5120 | T = Context.IntTy; | |||
5121 | D.setInvalidType(true); | |||
5122 | } | |||
5123 | ||||
5124 | // Do not allow returning half FP value. | |||
5125 | // FIXME: This really should be in BuildFunctionType. | |||
5126 | if (T->isHalfType()) { | |||
5127 | if (S.getLangOpts().OpenCL) { | |||
5128 | if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", | |||
5129 | S.getLangOpts())) { | |||
5130 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) | |||
5131 | << T << 0 /*pointer hint*/; | |||
5132 | D.setInvalidType(true); | |||
5133 | } | |||
5134 | } else if (!S.getLangOpts().HalfArgsAndReturns) { | |||
5135 | S.Diag(D.getIdentifierLoc(), | |||
5136 | diag::err_parameters_retval_cannot_have_fp16_type) << 1; | |||
5137 | D.setInvalidType(true); | |||
5138 | } | |||
5139 | } | |||
5140 | ||||
5141 | if (LangOpts.OpenCL) { | |||
5142 | // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a | |||
5143 | // function. | |||
5144 | if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() || | |||
5145 | T->isPipeType()) { | |||
5146 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) | |||
5147 | << T << 1 /*hint off*/; | |||
5148 | D.setInvalidType(true); | |||
5149 | } | |||
5150 | // OpenCL doesn't support variadic functions and blocks | |||
5151 | // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf. | |||
5152 | // We also allow here any toolchain reserved identifiers. | |||
5153 | if (FTI.isVariadic && | |||
5154 | !S.getOpenCLOptions().isAvailableOption( | |||
5155 | "__cl_clang_variadic_functions", S.getLangOpts()) && | |||
5156 | !(D.getIdentifier() && | |||
5157 | ((D.getIdentifier()->getName() == "printf" && | |||
5158 | LangOpts.getOpenCLCompatibleVersion() >= 120) || | |||
5159 | D.getIdentifier()->getName().startswith("__")))) { | |||
5160 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function); | |||
5161 | D.setInvalidType(true); | |||
5162 | } | |||
5163 | } | |||
5164 | ||||
5165 | // Methods cannot return interface types. All ObjC objects are | |||
5166 | // passed by reference. | |||
5167 | if (T->isObjCObjectType()) { | |||
5168 | SourceLocation DiagLoc, FixitLoc; | |||
5169 | if (TInfo) { | |||
5170 | DiagLoc = TInfo->getTypeLoc().getBeginLoc(); | |||
5171 | FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc()); | |||
5172 | } else { | |||
5173 | DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); | |||
5174 | FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc()); | |||
5175 | } | |||
5176 | S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) | |||
5177 | << 0 << T | |||
5178 | << FixItHint::CreateInsertion(FixitLoc, "*"); | |||
5179 | ||||
5180 | T = Context.getObjCObjectPointerType(T); | |||
5181 | if (TInfo) { | |||
5182 | TypeLocBuilder TLB; | |||
5183 | TLB.pushFullCopy(TInfo->getTypeLoc()); | |||
5184 | ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); | |||
5185 | TLoc.setStarLoc(FixitLoc); | |||
5186 | TInfo = TLB.getTypeSourceInfo(Context, T); | |||
5187 | } | |||
5188 | ||||
5189 | D.setInvalidType(true); | |||
5190 | } | |||
5191 | ||||
5192 | // cv-qualifiers on return types are pointless except when the type is a | |||
5193 | // class type in C++. | |||
5194 | if ((T.getCVRQualifiers() || T->isAtomicType()) && | |||
5195 | !(S.getLangOpts().CPlusPlus && | |||
5196 | (T->isDependentType() || T->isRecordType()))) { | |||
5197 | if (T->isVoidType() && !S.getLangOpts().CPlusPlus && | |||
5198 | D.getFunctionDefinitionKind() == | |||
5199 | FunctionDefinitionKind::Definition) { | |||
5200 | // [6.9.1/3] qualified void return is invalid on a C | |||
5201 | // function definition. Apparently ok on declarations and | |||
5202 | // in C++ though (!) | |||
5203 | S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; | |||
5204 | } else | |||
5205 | diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex); | |||
5206 | ||||
5207 | // C++2a [dcl.fct]p12: | |||
5208 | // A volatile-qualified return type is deprecated | |||
5209 | if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20) | |||
5210 | S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T; | |||
5211 | } | |||
5212 | ||||
5213 | // Objective-C ARC ownership qualifiers are ignored on the function | |||
5214 | // return type (by type canonicalization). Complain if this attribute | |||
5215 | // was written here. | |||
5216 | if (T.getQualifiers().hasObjCLifetime()) { | |||
5217 | SourceLocation AttrLoc; | |||
5218 | if (chunkIndex + 1 < D.getNumTypeObjects()) { | |||
5219 | DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1); | |||
5220 | for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) { | |||
5221 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { | |||
5222 | AttrLoc = AL.getLoc(); | |||
5223 | break; | |||
5224 | } | |||
5225 | } | |||
5226 | } | |||
5227 | if (AttrLoc.isInvalid()) { | |||
5228 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { | |||
5229 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { | |||
5230 | AttrLoc = AL.getLoc(); | |||
5231 | break; | |||
5232 | } | |||
5233 | } | |||
5234 | } | |||
5235 | ||||
5236 | if (AttrLoc.isValid()) { | |||
5237 | // The ownership attributes are almost always written via | |||
5238 | // the predefined | |||
5239 | // __strong/__weak/__autoreleasing/__unsafe_unretained. | |||
5240 | if (AttrLoc.isMacroID()) | |||
5241 | AttrLoc = | |||
5242 | S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin(); | |||
5243 | ||||
5244 | S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) | |||
5245 | << T.getQualifiers().getObjCLifetime(); | |||
5246 | } | |||
5247 | } | |||
5248 | ||||
5249 | if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { | |||
5250 | // C++ [dcl.fct]p6: | |||
5251 | // Types shall not be defined in return or parameter types. | |||
5252 | TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | |||
5253 | S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) | |||
5254 | << Context.getTypeDeclType(Tag); | |||
5255 | } | |||
5256 | ||||
5257 | // Exception specs are not allowed in typedefs. Complain, but add it | |||
5258 | // anyway. | |||
5259 | if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17) | |||
5260 | S.Diag(FTI.getExceptionSpecLocBeg(), | |||
5261 | diag::err_exception_spec_in_typedef) | |||
5262 | << (D.getContext() == DeclaratorContext::AliasDecl || | |||
5263 | D.getContext() == DeclaratorContext::AliasTemplate); | |||
5264 | ||||
5265 | // If we see "T var();" or "T var(T());" at block scope, it is probably | |||
5266 | // an attempt to initialize a variable, not a function declaration. | |||
5267 | if (FTI.isAmbiguous) | |||
5268 | warnAboutAmbiguousFunction(S, D, DeclType, T); | |||
5269 | ||||
5270 | FunctionType::ExtInfo EI( | |||
5271 | getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex)); | |||
5272 | ||||
5273 | if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus | |||
5274 | && !LangOpts.OpenCL) { | |||
5275 | // Simple void foo(), where the incoming T is the result type. | |||
5276 | T = Context.getFunctionNoProtoType(T, EI); | |||
5277 | } else { | |||
5278 | // We allow a zero-parameter variadic function in C if the | |||
5279 | // function is marked with the "overloadable" attribute. Scan | |||
5280 | // for this attribute now. | |||
5281 | if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) | |||
5282 | if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable) && | |||
5283 | !D.getDeclSpec().getAttributes().hasAttribute( | |||
5284 | ParsedAttr::AT_Overloadable)) | |||
5285 | S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); | |||
5286 | ||||
5287 | if (FTI.NumParams && FTI.Params[0].Param == nullptr) { | |||
5288 | // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function | |||
5289 | // definition. | |||
5290 | S.Diag(FTI.Params[0].IdentLoc, | |||
5291 | diag::err_ident_list_in_fn_declaration); | |||
5292 | D.setInvalidType(true); | |||
5293 | // Recover by creating a K&R-style function type. | |||
5294 | T = Context.getFunctionNoProtoType(T, EI); | |||
5295 | break; | |||
5296 | } | |||
5297 | ||||
5298 | FunctionProtoType::ExtProtoInfo EPI; | |||
5299 | EPI.ExtInfo = EI; | |||
5300 | EPI.Variadic = FTI.isVariadic; | |||
5301 | EPI.EllipsisLoc = FTI.getEllipsisLoc(); | |||
5302 | EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); | |||
5303 | EPI.TypeQuals.addCVRUQualifiers( | |||
5304 | FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers() | |||
5305 | : 0); | |||
5306 | EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None | |||
5307 | : FTI.RefQualifierIsLValueRef? RQ_LValue | |||
5308 | : RQ_RValue; | |||
5309 | ||||
5310 | // Otherwise, we have a function with a parameter list that is | |||
5311 | // potentially variadic. | |||
5312 | SmallVector<QualType, 16> ParamTys; | |||
5313 | ParamTys.reserve(FTI.NumParams); | |||
5314 | ||||
5315 | SmallVector<FunctionProtoType::ExtParameterInfo, 16> | |||
5316 | ExtParameterInfos(FTI.NumParams); | |||
5317 | bool HasAnyInterestingExtParameterInfos = false; | |||
5318 | ||||
5319 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { | |||
5320 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | |||
5321 | QualType ParamTy = Param->getType(); | |||
5322 | assert(!ParamTy.isNull() && "Couldn't parse type?")(static_cast <bool> (!ParamTy.isNull() && "Couldn't parse type?" ) ? void (0) : __assert_fail ("!ParamTy.isNull() && \"Couldn't parse type?\"" , "clang/lib/Sema/SemaType.cpp", 5322, __extension__ __PRETTY_FUNCTION__ )); | |||
5323 | ||||
5324 | // Look for 'void'. void is allowed only as a single parameter to a | |||
5325 | // function with no other parameters (C99 6.7.5.3p10). We record | |||
5326 | // int(void) as a FunctionProtoType with an empty parameter list. | |||
5327 | if (ParamTy->isVoidType()) { | |||
5328 | // If this is something like 'float(int, void)', reject it. 'void' | |||
5329 | // is an incomplete type (C99 6.2.5p19) and function decls cannot | |||
5330 | // have parameters of incomplete type. | |||
5331 | if (FTI.NumParams != 1 || FTI.isVariadic) { | |||
5332 | S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param); | |||
5333 | ParamTy = Context.IntTy; | |||
5334 | Param->setType(ParamTy); | |||
5335 | } else if (FTI.Params[i].Ident) { | |||
5336 | // Reject, but continue to parse 'int(void abc)'. | |||
5337 | S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); | |||
5338 | ParamTy = Context.IntTy; | |||
5339 | Param->setType(ParamTy); | |||
5340 | } else { | |||
5341 | // Reject, but continue to parse 'float(const void)'. | |||
5342 | if (ParamTy.hasQualifiers()) | |||
5343 | S.Diag(DeclType.Loc, diag::err_void_param_qualified); | |||
5344 | ||||
5345 | // Do not add 'void' to the list. | |||
5346 | break; | |||
5347 | } | |||
5348 | } else if (ParamTy->isHalfType()) { | |||
5349 | // Disallow half FP parameters. | |||
5350 | // FIXME: This really should be in BuildFunctionType. | |||
5351 | if (S.getLangOpts().OpenCL) { | |||
5352 | if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", | |||
5353 | S.getLangOpts())) { | |||
5354 | S.Diag(Param->getLocation(), diag::err_opencl_invalid_param) | |||
5355 | << ParamTy << 0; | |||
5356 | D.setInvalidType(); | |||
5357 | Param->setInvalidDecl(); | |||
5358 | } | |||
5359 | } else if (!S.getLangOpts().HalfArgsAndReturns) { | |||
5360 | S.Diag(Param->getLocation(), | |||
5361 | diag::err_parameters_retval_cannot_have_fp16_type) << 0; | |||
5362 | D.setInvalidType(); | |||
5363 | } | |||
5364 | } else if (!FTI.hasPrototype) { | |||
5365 | if (ParamTy->isPromotableIntegerType()) { | |||
5366 | ParamTy = Context.getPromotedIntegerType(ParamTy); | |||
5367 | Param->setKNRPromoted(true); | |||
5368 | } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) { | |||
5369 | if (BTy->getKind() == BuiltinType::Float) { | |||
5370 | ParamTy = Context.DoubleTy; | |||
5371 | Param->setKNRPromoted(true); | |||
5372 | } | |||
5373 | } | |||
5374 | } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) { | |||
5375 | // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function. | |||
5376 | S.Diag(Param->getLocation(), diag::err_opencl_invalid_param) | |||
5377 | << ParamTy << 1 /*hint off*/; | |||
5378 | D.setInvalidType(); | |||
5379 | } | |||
5380 | ||||
5381 | if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { | |||
5382 | ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true); | |||
5383 | HasAnyInterestingExtParameterInfos = true; | |||
5384 | } | |||
5385 | ||||
5386 | if (auto attr = Param->getAttr<ParameterABIAttr>()) { | |||
5387 | ExtParameterInfos[i] = | |||
5388 | ExtParameterInfos[i].withABI(attr->getABI()); | |||
5389 | HasAnyInterestingExtParameterInfos = true; | |||
5390 | } | |||
5391 | ||||
5392 | if (Param->hasAttr<PassObjectSizeAttr>()) { | |||
5393 | ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize(); | |||
5394 | HasAnyInterestingExtParameterInfos = true; | |||
5395 | } | |||
5396 | ||||
5397 | if (Param->hasAttr<NoEscapeAttr>()) { | |||
5398 | ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true); | |||
5399 | HasAnyInterestingExtParameterInfos = true; | |||
5400 | } | |||
5401 | ||||
5402 | ParamTys.push_back(ParamTy); | |||
5403 | } | |||
5404 | ||||
5405 | if (HasAnyInterestingExtParameterInfos) { | |||
5406 | EPI.ExtParameterInfos = ExtParameterInfos.data(); | |||
5407 | checkExtParameterInfos(S, ParamTys, EPI, | |||
5408 | [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); | |||
5409 | } | |||
5410 | ||||
5411 | SmallVector<QualType, 4> Exceptions; | |||
5412 | SmallVector<ParsedType, 2> DynamicExceptions; | |||
5413 | SmallVector<SourceRange, 2> DynamicExceptionRanges; | |||
5414 | Expr *NoexceptExpr = nullptr; | |||
5415 | ||||
5416 | if (FTI.getExceptionSpecType() == EST_Dynamic) { | |||
5417 | // FIXME: It's rather inefficient to have to split into two vectors | |||
5418 | // here. | |||
5419 | unsigned N = FTI.getNumExceptions(); | |||
5420 | DynamicExceptions.reserve(N); | |||
5421 | DynamicExceptionRanges.reserve(N); | |||
5422 | for (unsigned I = 0; I != N; ++I) { | |||
5423 | DynamicExceptions.push_back(FTI.Exceptions[I].Ty); | |||
5424 | DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range); | |||
5425 | } | |||
5426 | } else if (isComputedNoexcept(FTI.getExceptionSpecType())) { | |||
5427 | NoexceptExpr = FTI.NoexceptExpr; | |||
5428 | } | |||
5429 | ||||
5430 | S.checkExceptionSpecification(D.isFunctionDeclarationContext(), | |||
5431 | FTI.getExceptionSpecType(), | |||
5432 | DynamicExceptions, | |||
5433 | DynamicExceptionRanges, | |||
5434 | NoexceptExpr, | |||
5435 | Exceptions, | |||
5436 | EPI.ExceptionSpec); | |||
5437 | ||||
5438 | // FIXME: Set address space from attrs for C++ mode here. | |||
5439 | // OpenCLCPlusPlus: A class member function has an address space. | |||
5440 | auto IsClassMember = [&]() { | |||
5441 | return (!state.getDeclarator().getCXXScopeSpec().isEmpty() && | |||
5442 | state.getDeclarator() | |||
5443 | .getCXXScopeSpec() | |||
5444 | .getScopeRep() | |||
5445 | ->getKind() == NestedNameSpecifier::TypeSpec) || | |||
5446 | state.getDeclarator().getContext() == | |||
5447 | DeclaratorContext::Member || | |||
5448 | state.getDeclarator().getContext() == | |||
5449 | DeclaratorContext::LambdaExpr; | |||
5450 | }; | |||
5451 | ||||
5452 | if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) { | |||
5453 | LangAS ASIdx = LangAS::Default; | |||
5454 | // Take address space attr if any and mark as invalid to avoid adding | |||
5455 | // them later while creating QualType. | |||
5456 | if (FTI.MethodQualifiers) | |||
5457 | for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) { | |||
5458 | LangAS ASIdxNew = attr.asOpenCLLangAS(); | |||
5459 | if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew, | |||
5460 | attr.getLoc())) | |||
5461 | D.setInvalidType(true); | |||
5462 | else | |||
5463 | ASIdx = ASIdxNew; | |||
5464 | } | |||
5465 | // If a class member function's address space is not set, set it to | |||
5466 | // __generic. | |||
5467 | LangAS AS = | |||
5468 | (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace() | |||
5469 | : ASIdx); | |||
5470 | EPI.TypeQuals.addAddressSpace(AS); | |||
5471 | } | |||
5472 | T = Context.getFunctionType(T, ParamTys, EPI); | |||
5473 | } | |||
5474 | break; | |||
5475 | } | |||
5476 | case DeclaratorChunk::MemberPointer: { | |||
5477 | // The scope spec must refer to a class, or be dependent. | |||
5478 | CXXScopeSpec &SS = DeclType.Mem.Scope(); | |||
5479 | QualType ClsType; | |||
5480 | ||||
5481 | // Handle pointer nullability. | |||
5482 | inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc, | |||
5483 | DeclType.EndLoc, DeclType.getAttrs(), | |||
5484 | state.getDeclarator().getAttributePool()); | |||
5485 | ||||
5486 | if (SS.isInvalid()) { | |||
5487 | // Avoid emitting extra errors if we already errored on the scope. | |||
5488 | D.setInvalidType(true); | |||
5489 | } else if (S.isDependentScopeSpecifier(SS) || | |||
5490 | isa_and_nonnull<CXXRecordDecl>(S.computeDeclContext(SS))) { | |||
5491 | NestedNameSpecifier *NNS = SS.getScopeRep(); | |||
5492 | NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); | |||
5493 | switch (NNS->getKind()) { | |||
5494 | case NestedNameSpecifier::Identifier: | |||
5495 | ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, | |||
5496 | NNS->getAsIdentifier()); | |||
5497 | break; | |||
5498 | ||||
5499 | case NestedNameSpecifier::Namespace: | |||
5500 | case NestedNameSpecifier::NamespaceAlias: | |||
5501 | case NestedNameSpecifier::Global: | |||
5502 | case NestedNameSpecifier::Super: | |||
5503 | llvm_unreachable("Nested-name-specifier must name a type")::llvm::llvm_unreachable_internal("Nested-name-specifier must name a type" , "clang/lib/Sema/SemaType.cpp", 5503); | |||
5504 | ||||
5505 | case NestedNameSpecifier::TypeSpec: | |||
5506 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
5507 | ClsType = QualType(NNS->getAsType(), 0); | |||
5508 | // Note: if the NNS has a prefix and ClsType is a nondependent | |||
5509 | // TemplateSpecializationType, then the NNS prefix is NOT included | |||
5510 | // in ClsType; hence we wrap ClsType into an ElaboratedType. | |||
5511 | // NOTE: in particular, no wrap occurs if ClsType already is an | |||
5512 | // Elaborated, DependentName, or DependentTemplateSpecialization. | |||
5513 | if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType())) | |||
5514 | ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); | |||
5515 | break; | |||
5516 | } | |||
5517 | } else { | |||
5518 | S.Diag(DeclType.Mem.Scope().getBeginLoc(), | |||
5519 | diag::err_illegal_decl_mempointer_in_nonclass) | |||
5520 | << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") | |||
5521 | << DeclType.Mem.Scope().getRange(); | |||
5522 | D.setInvalidType(true); | |||
5523 | } | |||
5524 | ||||
5525 | if (!ClsType.isNull()) | |||
5526 | T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, | |||
5527 | D.getIdentifier()); | |||
5528 | if (T.isNull()) { | |||
5529 | T = Context.IntTy; | |||
5530 | D.setInvalidType(true); | |||
5531 | } else if (DeclType.Mem.TypeQuals) { | |||
5532 | T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals); | |||
5533 | } | |||
5534 | break; | |||
5535 | } | |||
5536 | ||||
5537 | case DeclaratorChunk::Pipe: { | |||
5538 | T = S.BuildReadPipeType(T, DeclType.Loc); | |||
5539 | processTypeAttrs(state, T, TAL_DeclSpec, | |||
5540 | D.getMutableDeclSpec().getAttributes()); | |||
5541 | break; | |||
5542 | } | |||
5543 | } | |||
5544 | ||||
5545 | if (T.isNull()) { | |||
5546 | D.setInvalidType(true); | |||
5547 | T = Context.IntTy; | |||
5548 | } | |||
5549 | ||||
5550 | // See if there are any attributes on this declarator chunk. | |||
5551 | processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs()); | |||
5552 | ||||
5553 | if (DeclType.Kind != DeclaratorChunk::Paren) { | |||
5554 | if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType)) | |||
5555 | S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array); | |||
5556 | ||||
5557 | ExpectNoDerefChunk = state.didParseNoDeref(); | |||
5558 | } | |||
5559 | } | |||
5560 | ||||
5561 | if (ExpectNoDerefChunk) | |||
5562 | S.Diag(state.getDeclarator().getBeginLoc(), | |||
5563 | diag::warn_noderef_on_non_pointer_or_array); | |||
5564 | ||||
5565 | // GNU warning -Wstrict-prototypes | |||
5566 | // Warn if a function declaration or definition is without a prototype. | |||
5567 | // This warning is issued for all kinds of unprototyped function | |||
5568 | // declarations (i.e. function type typedef, function pointer etc.) | |||
5569 | // C99 6.7.5.3p14: | |||
5570 | // The empty list in a function declarator that is not part of a definition | |||
5571 | // of that function specifies that no information about the number or types | |||
5572 | // of the parameters is supplied. | |||
5573 | // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of | |||
5574 | // function declarations whose behavior changes in C2x. | |||
5575 | if (!LangOpts.CPlusPlus) { | |||
5576 | bool IsBlock = false; | |||
5577 | for (const DeclaratorChunk &DeclType : D.type_objects()) { | |||
5578 | switch (DeclType.Kind) { | |||
5579 | case DeclaratorChunk::BlockPointer: | |||
5580 | IsBlock = true; | |||
5581 | break; | |||
5582 | case DeclaratorChunk::Function: { | |||
5583 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; | |||
5584 | // We suppress the warning when there's no LParen location, as this | |||
5585 | // indicates the declaration was an implicit declaration, which gets | |||
5586 | // warned about separately via -Wimplicit-function-declaration. | |||
5587 | if (FTI.NumParams == 0 && !FTI.isVariadic && FTI.getLParenLoc().isValid()) | |||
5588 | S.Diag(DeclType.Loc, diag::warn_strict_prototypes) | |||
5589 | << IsBlock | |||
5590 | << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void"); | |||
5591 | IsBlock = false; | |||
5592 | break; | |||
5593 | } | |||
5594 | default: | |||
5595 | break; | |||
5596 | } | |||
5597 | } | |||
5598 | } | |||
5599 | ||||
5600 | assert(!T.isNull() && "T must not be null after this point")(static_cast <bool> (!T.isNull() && "T must not be null after this point" ) ? void (0) : __assert_fail ("!T.isNull() && \"T must not be null after this point\"" , "clang/lib/Sema/SemaType.cpp", 5600, __extension__ __PRETTY_FUNCTION__ )); | |||
5601 | ||||
5602 | if (LangOpts.CPlusPlus && T->isFunctionType()) { | |||
5603 | const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); | |||
5604 | assert(FnTy && "Why oh why is there not a FunctionProtoType here?")(static_cast <bool> (FnTy && "Why oh why is there not a FunctionProtoType here?" ) ? void (0) : __assert_fail ("FnTy && \"Why oh why is there not a FunctionProtoType here?\"" , "clang/lib/Sema/SemaType.cpp", 5604, __extension__ __PRETTY_FUNCTION__ )); | |||
5605 | ||||
5606 | // C++ 8.3.5p4: | |||
5607 | // A cv-qualifier-seq shall only be part of the function type | |||
5608 | // for a nonstatic member function, the function type to which a pointer | |||
5609 | // to member refers, or the top-level function type of a function typedef | |||
5610 | // declaration. | |||
5611 | // | |||
5612 | // Core issue 547 also allows cv-qualifiers on function types that are | |||
5613 | // top-level template type arguments. | |||
5614 | enum { NonMember, Member, DeductionGuide } Kind = NonMember; | |||
5615 | if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) | |||
5616 | Kind = DeductionGuide; | |||
5617 | else if (!D.getCXXScopeSpec().isSet()) { | |||
5618 | if ((D.getContext() == DeclaratorContext::Member || | |||
5619 | D.getContext() == DeclaratorContext::LambdaExpr) && | |||
5620 | !D.getDeclSpec().isFriendSpecified()) | |||
5621 | Kind = Member; | |||
5622 | } else { | |||
5623 | DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec()); | |||
5624 | if (!DC || DC->isRecord()) | |||
5625 | Kind = Member; | |||
5626 | } | |||
5627 | ||||
5628 | // C++11 [dcl.fct]p6 (w/DR1417): | |||
5629 | // An attempt to specify a function type with a cv-qualifier-seq or a | |||
5630 | // ref-qualifier (including by typedef-name) is ill-formed unless it is: | |||
5631 | // - the function type for a non-static member function, | |||
5632 | // - the function type to which a pointer to member refers, | |||
5633 | // - the top-level function type of a function typedef declaration or | |||
5634 | // alias-declaration, | |||
5635 | // - the type-id in the default argument of a type-parameter, or | |||
5636 | // - the type-id of a template-argument for a type-parameter | |||
5637 | // | |||
5638 | // FIXME: Checking this here is insufficient. We accept-invalid on: | |||
5639 | // | |||
5640 | // template<typename T> struct S { void f(T); }; | |||
5641 | // S<int() const> s; | |||
5642 | // | |||
5643 | // ... for instance. | |||
5644 | if (IsQualifiedFunction && | |||
5645 | !(Kind == Member && | |||
5646 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) && | |||
5647 | !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg && | |||
5648 | D.getContext() != DeclaratorContext::TemplateTypeArg) { | |||
5649 | SourceLocation Loc = D.getBeginLoc(); | |||
5650 | SourceRange RemovalRange; | |||
5651 | unsigned I; | |||
5652 | if (D.isFunctionDeclarator(I)) { | |||
5653 | SmallVector<SourceLocation, 4> RemovalLocs; | |||
5654 | const DeclaratorChunk &Chunk = D.getTypeObject(I); | |||
5655 | assert(Chunk.Kind == DeclaratorChunk::Function)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Function ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function" , "clang/lib/Sema/SemaType.cpp", 5655, __extension__ __PRETTY_FUNCTION__ )); | |||
5656 | ||||
5657 | if (Chunk.Fun.hasRefQualifier()) | |||
5658 | RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc()); | |||
5659 | ||||
5660 | if (Chunk.Fun.hasMethodTypeQualifiers()) | |||
5661 | Chunk.Fun.MethodQualifiers->forEachQualifier( | |||
5662 | [&](DeclSpec::TQ TypeQual, StringRef QualName, | |||
5663 | SourceLocation SL) { RemovalLocs.push_back(SL); }); | |||
5664 | ||||
5665 | if (!RemovalLocs.empty()) { | |||
5666 | llvm::sort(RemovalLocs, | |||
5667 | BeforeThanCompare<SourceLocation>(S.getSourceManager())); | |||
5668 | RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); | |||
5669 | Loc = RemovalLocs.front(); | |||
5670 | } | |||
5671 | } | |||
5672 | ||||
5673 | S.Diag(Loc, diag::err_invalid_qualified_function_type) | |||
5674 | << Kind << D.isFunctionDeclarator() << T | |||
5675 | << getFunctionQualifiersAsString(FnTy) | |||
5676 | << FixItHint::CreateRemoval(RemovalRange); | |||
5677 | ||||
5678 | // Strip the cv-qualifiers and ref-qualifiers from the type. | |||
5679 | FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); | |||
5680 | EPI.TypeQuals.removeCVRQualifiers(); | |||
5681 | EPI.RefQualifier = RQ_None; | |||
5682 | ||||
5683 | T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(), | |||
5684 | EPI); | |||
5685 | // Rebuild any parens around the identifier in the function type. | |||
5686 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
5687 | if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) | |||
5688 | break; | |||
5689 | T = S.BuildParenType(T); | |||
5690 | } | |||
5691 | } | |||
5692 | } | |||
5693 | ||||
5694 | // Apply any undistributed attributes from the declarator. | |||
5695 | processTypeAttrs(state, T, TAL_DeclName, D.getAttributes()); | |||
5696 | ||||
5697 | // Diagnose any ignored type attributes. | |||
5698 | state.diagnoseIgnoredTypeAttrs(T); | |||
5699 | ||||
5700 | // C++0x [dcl.constexpr]p9: | |||
5701 | // A constexpr specifier used in an object declaration declares the object | |||
5702 | // as const. | |||
5703 | if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr && | |||
5704 | T->isObjectType()) | |||
5705 | T.addConst(); | |||
5706 | ||||
5707 | // C++2a [dcl.fct]p4: | |||
5708 | // A parameter with volatile-qualified type is deprecated | |||
5709 | if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 && | |||
5710 | (D.getContext() == DeclaratorContext::Prototype || | |||
5711 | D.getContext() == DeclaratorContext::LambdaExprParameter)) | |||
5712 | S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T; | |||
5713 | ||||
5714 | // If there was an ellipsis in the declarator, the declaration declares a | |||
5715 | // parameter pack whose type may be a pack expansion type. | |||
5716 | if (D.hasEllipsis()) { | |||
5717 | // C++0x [dcl.fct]p13: | |||
5718 | // A declarator-id or abstract-declarator containing an ellipsis shall | |||
5719 | // only be used in a parameter-declaration. Such a parameter-declaration | |||
5720 | // is a parameter pack (14.5.3). [...] | |||
5721 | switch (D.getContext()) { | |||
5722 | case DeclaratorContext::Prototype: | |||
5723 | case DeclaratorContext::LambdaExprParameter: | |||
5724 | case DeclaratorContext::RequiresExpr: | |||
5725 | // C++0x [dcl.fct]p13: | |||
5726 | // [...] When it is part of a parameter-declaration-clause, the | |||
5727 | // parameter pack is a function parameter pack (14.5.3). The type T | |||
5728 | // of the declarator-id of the function parameter pack shall contain | |||
5729 | // a template parameter pack; each template parameter pack in T is | |||
5730 | // expanded by the function parameter pack. | |||
5731 | // | |||
5732 | // We represent function parameter packs as function parameters whose | |||
5733 | // type is a pack expansion. | |||
5734 | if (!T->containsUnexpandedParameterPack() && | |||
5735 | (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) { | |||
5736 | S.Diag(D.getEllipsisLoc(), | |||
5737 | diag::err_function_parameter_pack_without_parameter_packs) | |||
5738 | << T << D.getSourceRange(); | |||
5739 | D.setEllipsisLoc(SourceLocation()); | |||
5740 | } else { | |||
5741 | T = Context.getPackExpansionType(T, None, /*ExpectPackInType=*/false); | |||
5742 | } | |||
5743 | break; | |||
5744 | case DeclaratorContext::TemplateParam: | |||
5745 | // C++0x [temp.param]p15: | |||
5746 | // If a template-parameter is a [...] is a parameter-declaration that | |||
5747 | // declares a parameter pack (8.3.5), then the template-parameter is a | |||
5748 | // template parameter pack (14.5.3). | |||
5749 | // | |||
5750 | // Note: core issue 778 clarifies that, if there are any unexpanded | |||
5751 | // parameter packs in the type of the non-type template parameter, then | |||
5752 | // it expands those parameter packs. | |||
5753 | if (T->containsUnexpandedParameterPack()) | |||
5754 | T = Context.getPackExpansionType(T, None); | |||
5755 | else | |||
5756 | S.Diag(D.getEllipsisLoc(), | |||
5757 | LangOpts.CPlusPlus11 | |||
5758 | ? diag::warn_cxx98_compat_variadic_templates | |||
5759 | : diag::ext_variadic_templates); | |||
5760 | break; | |||
5761 | ||||
5762 | case DeclaratorContext::File: | |||
5763 | case DeclaratorContext::KNRTypeList: | |||
5764 | case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here? | |||
5765 | case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here? | |||
5766 | case DeclaratorContext::TypeName: | |||
5767 | case DeclaratorContext::FunctionalCast: | |||
5768 | case DeclaratorContext::CXXNew: | |||
5769 | case DeclaratorContext::AliasDecl: | |||
5770 | case DeclaratorContext::AliasTemplate: | |||
5771 | case DeclaratorContext::Member: | |||
5772 | case DeclaratorContext::Block: | |||
5773 | case DeclaratorContext::ForInit: | |||
5774 | case DeclaratorContext::SelectionInit: | |||
5775 | case DeclaratorContext::Condition: | |||
5776 | case DeclaratorContext::CXXCatch: | |||
5777 | case DeclaratorContext::ObjCCatch: | |||
5778 | case DeclaratorContext::BlockLiteral: | |||
5779 | case DeclaratorContext::LambdaExpr: | |||
5780 | case DeclaratorContext::ConversionId: | |||
5781 | case DeclaratorContext::TrailingReturn: | |||
5782 | case DeclaratorContext::TrailingReturnVar: | |||
5783 | case DeclaratorContext::TemplateArg: | |||
5784 | case DeclaratorContext::TemplateTypeArg: | |||
5785 | // FIXME: We may want to allow parameter packs in block-literal contexts | |||
5786 | // in the future. | |||
5787 | S.Diag(D.getEllipsisLoc(), | |||
5788 | diag::err_ellipsis_in_declarator_not_parameter); | |||
5789 | D.setEllipsisLoc(SourceLocation()); | |||
5790 | break; | |||
5791 | } | |||
5792 | } | |||
5793 | ||||
5794 | assert(!T.isNull() && "T must not be null at the end of this function")(static_cast <bool> (!T.isNull() && "T must not be null at the end of this function" ) ? void (0) : __assert_fail ("!T.isNull() && \"T must not be null at the end of this function\"" , "clang/lib/Sema/SemaType.cpp", 5794, __extension__ __PRETTY_FUNCTION__ )); | |||
5795 | if (D.isInvalidType()) | |||
5796 | return Context.getTrivialTypeSourceInfo(T); | |||
5797 | ||||
5798 | return GetTypeSourceInfoForDeclarator(state, T, TInfo); | |||
5799 | } | |||
5800 | ||||
5801 | /// GetTypeForDeclarator - Convert the type for the specified | |||
5802 | /// declarator to Type instances. | |||
5803 | /// | |||
5804 | /// The result of this call will never be null, but the associated | |||
5805 | /// type may be a null type if there's an unrecoverable error. | |||
5806 | TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) { | |||
5807 | // Determine the type of the declarator. Not all forms of declarator | |||
5808 | // have a type. | |||
5809 | ||||
5810 | TypeProcessingState state(*this, D); | |||
5811 | ||||
5812 | TypeSourceInfo *ReturnTypeInfo = nullptr; | |||
5813 | QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); | |||
5814 | if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) | |||
5815 | inferARCWriteback(state, T); | |||
5816 | ||||
5817 | return GetFullTypeForDeclarator(state, T, ReturnTypeInfo); | |||
5818 | } | |||
5819 | ||||
5820 | static void transferARCOwnershipToDeclSpec(Sema &S, | |||
5821 | QualType &declSpecTy, | |||
5822 | Qualifiers::ObjCLifetime ownership) { | |||
5823 | if (declSpecTy->isObjCRetainableType() && | |||
5824 | declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { | |||
5825 | Qualifiers qs; | |||
5826 | qs.addObjCLifetime(ownership); | |||
5827 | declSpecTy = S.Context.getQualifiedType(declSpecTy, qs); | |||
5828 | } | |||
5829 | } | |||
5830 | ||||
5831 | static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, | |||
5832 | Qualifiers::ObjCLifetime ownership, | |||
5833 | unsigned chunkIndex) { | |||
5834 | Sema &S = state.getSema(); | |||
5835 | Declarator &D = state.getDeclarator(); | |||
5836 | ||||
5837 | // Look for an explicit lifetime attribute. | |||
5838 | DeclaratorChunk &chunk = D.getTypeObject(chunkIndex); | |||
5839 | if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership)) | |||
5840 | return; | |||
5841 | ||||
5842 | const char *attrStr = nullptr; | |||
5843 | switch (ownership) { | |||
5844 | case Qualifiers::OCL_None: llvm_unreachable("no ownership!")::llvm::llvm_unreachable_internal("no ownership!", "clang/lib/Sema/SemaType.cpp" , 5844); | |||
5845 | case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break; | |||
5846 | case Qualifiers::OCL_Strong: attrStr = "strong"; break; | |||
5847 | case Qualifiers::OCL_Weak: attrStr = "weak"; break; | |||
5848 | case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break; | |||
5849 | } | |||
5850 | ||||
5851 | IdentifierLoc *Arg = new (S.Context) IdentifierLoc; | |||
5852 | Arg->Ident = &S.Context.Idents.get(attrStr); | |||
5853 | Arg->Loc = SourceLocation(); | |||
5854 | ||||
5855 | ArgsUnion Args(Arg); | |||
5856 | ||||
5857 | // If there wasn't one, add one (with an invalid source location | |||
5858 | // so that we don't make an AttributedType for it). | |||
5859 | ParsedAttr *attr = D.getAttributePool().create( | |||
5860 | &S.Context.Idents.get("objc_ownership"), SourceLocation(), | |||
5861 | /*scope*/ nullptr, SourceLocation(), | |||
5862 | /*args*/ &Args, 1, ParsedAttr::AS_GNU); | |||
5863 | chunk.getAttrs().addAtEnd(attr); | |||
5864 | // TODO: mark whether we did this inference? | |||
5865 | } | |||
5866 | ||||
5867 | /// Used for transferring ownership in casts resulting in l-values. | |||
5868 | static void transferARCOwnership(TypeProcessingState &state, | |||
5869 | QualType &declSpecTy, | |||
5870 | Qualifiers::ObjCLifetime ownership) { | |||
5871 | Sema &S = state.getSema(); | |||
5872 | Declarator &D = state.getDeclarator(); | |||
5873 | ||||
5874 | int inner = -1; | |||
5875 | bool hasIndirection = false; | |||
5876 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
5877 | DeclaratorChunk &chunk = D.getTypeObject(i); | |||
5878 | switch (chunk.Kind) { | |||
5879 | case DeclaratorChunk::Paren: | |||
5880 | // Ignore parens. | |||
5881 | break; | |||
5882 | ||||
5883 | case DeclaratorChunk::Array: | |||
5884 | case DeclaratorChunk::Reference: | |||
5885 | case DeclaratorChunk::Pointer: | |||
5886 | if (inner != -1) | |||
5887 | hasIndirection = true; | |||
5888 | inner = i; | |||
5889 | break; | |||
5890 | ||||
5891 | case DeclaratorChunk::BlockPointer: | |||
5892 | if (inner != -1) | |||
5893 | transferARCOwnershipToDeclaratorChunk(state, ownership, i); | |||
5894 | return; | |||
5895 | ||||
5896 | case DeclaratorChunk::Function: | |||
5897 | case DeclaratorChunk::MemberPointer: | |||
5898 | case DeclaratorChunk::Pipe: | |||
5899 | return; | |||
5900 | } | |||
5901 | } | |||
5902 | ||||
5903 | if (inner == -1) | |||
5904 | return; | |||
5905 | ||||
5906 | DeclaratorChunk &chunk = D.getTypeObject(inner); | |||
5907 | if (chunk.Kind == DeclaratorChunk::Pointer) { | |||
5908 | if (declSpecTy->isObjCRetainableType()) | |||
5909 | return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); | |||
5910 | if (declSpecTy->isObjCObjectType() && hasIndirection) | |||
5911 | return transferARCOwnershipToDeclaratorChunk(state, ownership, inner); | |||
5912 | } else { | |||
5913 | assert(chunk.Kind == DeclaratorChunk::Array ||(static_cast <bool> (chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference) ? void (0) : __assert_fail ("chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference" , "clang/lib/Sema/SemaType.cpp", 5914, __extension__ __PRETTY_FUNCTION__ )) | |||
5914 | chunk.Kind == DeclaratorChunk::Reference)(static_cast <bool> (chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference) ? void (0) : __assert_fail ("chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference" , "clang/lib/Sema/SemaType.cpp", 5914, __extension__ __PRETTY_FUNCTION__ )); | |||
5915 | return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); | |||
5916 | } | |||
5917 | } | |||
5918 | ||||
5919 | TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { | |||
5920 | TypeProcessingState state(*this, D); | |||
5921 | ||||
5922 | TypeSourceInfo *ReturnTypeInfo = nullptr; | |||
5923 | QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); | |||
5924 | ||||
5925 | if (getLangOpts().ObjC) { | |||
5926 | Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy); | |||
5927 | if (ownership != Qualifiers::OCL_None) | |||
5928 | transferARCOwnership(state, declSpecTy, ownership); | |||
5929 | } | |||
5930 | ||||
5931 | return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo); | |||
5932 | } | |||
5933 | ||||
5934 | static void fillAttributedTypeLoc(AttributedTypeLoc TL, | |||
5935 | TypeProcessingState &State) { | |||
5936 | TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr())); | |||
5937 | } | |||
5938 | ||||
5939 | namespace { | |||
5940 | class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { | |||
5941 | Sema &SemaRef; | |||
5942 | ASTContext &Context; | |||
5943 | TypeProcessingState &State; | |||
5944 | const DeclSpec &DS; | |||
5945 | ||||
5946 | public: | |||
5947 | TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State, | |||
5948 | const DeclSpec &DS) | |||
5949 | : SemaRef(S), Context(Context), State(State), DS(DS) {} | |||
5950 | ||||
5951 | void VisitAttributedTypeLoc(AttributedTypeLoc TL) { | |||
5952 | Visit(TL.getModifiedLoc()); | |||
5953 | fillAttributedTypeLoc(TL, State); | |||
5954 | } | |||
5955 | void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { | |||
5956 | Visit(TL.getWrappedLoc()); | |||
5957 | } | |||
5958 | void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { | |||
5959 | Visit(TL.getInnerLoc()); | |||
5960 | TL.setExpansionLoc( | |||
5961 | State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); | |||
5962 | } | |||
5963 | void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { | |||
5964 | Visit(TL.getUnqualifiedLoc()); | |||
5965 | } | |||
5966 | // Allow to fill pointee's type locations, e.g., | |||
5967 | // int __attr * __attr * __attr *p; | |||
5968 | void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); } | |||
5969 | void VisitTypedefTypeLoc(TypedefTypeLoc TL) { | |||
5970 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
5971 | } | |||
5972 | void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { | |||
5973 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
5974 | // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires | |||
5975 | // addition field. What we have is good enough for display of location | |||
5976 | // of 'fixit' on interface name. | |||
5977 | TL.setNameEndLoc(DS.getEndLoc()); | |||
5978 | } | |||
5979 | void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { | |||
5980 | TypeSourceInfo *RepTInfo = nullptr; | |||
5981 | Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); | |||
5982 | TL.copy(RepTInfo->getTypeLoc()); | |||
5983 | } | |||
5984 | void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { | |||
5985 | TypeSourceInfo *RepTInfo = nullptr; | |||
5986 | Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo); | |||
5987 | TL.copy(RepTInfo->getTypeLoc()); | |||
5988 | } | |||
5989 | void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { | |||
5990 | TypeSourceInfo *TInfo = nullptr; | |||
5991 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
5992 | ||||
5993 | // If we got no declarator info from previous Sema routines, | |||
5994 | // just fill with the typespec loc. | |||
5995 | if (!TInfo) { | |||
5996 | TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); | |||
5997 | return; | |||
5998 | } | |||
5999 | ||||
6000 | TypeLoc OldTL = TInfo->getTypeLoc(); | |||
6001 | if (TInfo->getType()->getAs<ElaboratedType>()) { | |||
6002 | ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); | |||
6003 | TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() | |||
6004 | .castAs<TemplateSpecializationTypeLoc>(); | |||
6005 | TL.copy(NamedTL); | |||
6006 | } else { | |||
6007 | TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>()); | |||
6008 | assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc())(static_cast <bool> (TL.getRAngleLoc() == OldTL.castAs< TemplateSpecializationTypeLoc>().getRAngleLoc()) ? void (0 ) : __assert_fail ("TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()" , "clang/lib/Sema/SemaType.cpp", 6008, __extension__ __PRETTY_FUNCTION__ )); | |||
6009 | } | |||
6010 | ||||
6011 | } | |||
6012 | void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { | |||
6013 | assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr)(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_typeofExpr) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_typeofExpr" , "clang/lib/Sema/SemaType.cpp", 6013, __extension__ __PRETTY_FUNCTION__ )); | |||
6014 | TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); | |||
6015 | TL.setParensRange(DS.getTypeofParensRange()); | |||
6016 | } | |||
6017 | void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { | |||
6018 | assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType)(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_typeofType) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_typeofType" , "clang/lib/Sema/SemaType.cpp", 6018, __extension__ __PRETTY_FUNCTION__ )); | |||
6019 | TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); | |||
6020 | TL.setParensRange(DS.getTypeofParensRange()); | |||
6021 | assert(DS.getRepAsType())(static_cast <bool> (DS.getRepAsType()) ? void (0) : __assert_fail ("DS.getRepAsType()", "clang/lib/Sema/SemaType.cpp", 6021, __extension__ __PRETTY_FUNCTION__)); | |||
6022 | TypeSourceInfo *TInfo = nullptr; | |||
6023 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6024 | TL.setUnderlyingTInfo(TInfo); | |||
6025 | } | |||
6026 | void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { | |||
6027 | assert(DS.getTypeSpecType() == DeclSpec::TST_decltype)(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_decltype) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype" , "clang/lib/Sema/SemaType.cpp", 6027, __extension__ __PRETTY_FUNCTION__ )); | |||
6028 | TL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); | |||
6029 | TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); | |||
6030 | } | |||
6031 | void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { | |||
6032 | // FIXME: This holds only because we only have one unary transform. | |||
6033 | assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType)(static_cast <bool> (DS.getTypeSpecType() == DeclSpec:: TST_underlyingType) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_underlyingType" , "clang/lib/Sema/SemaType.cpp", 6033, __extension__ __PRETTY_FUNCTION__ )); | |||
6034 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | |||
6035 | TL.setParensRange(DS.getTypeofParensRange()); | |||
6036 | assert(DS.getRepAsType())(static_cast <bool> (DS.getRepAsType()) ? void (0) : __assert_fail ("DS.getRepAsType()", "clang/lib/Sema/SemaType.cpp", 6036, __extension__ __PRETTY_FUNCTION__)); | |||
6037 | TypeSourceInfo *TInfo = nullptr; | |||
6038 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6039 | TL.setUnderlyingTInfo(TInfo); | |||
6040 | } | |||
6041 | void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { | |||
6042 | // By default, use the source location of the type specifier. | |||
6043 | TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); | |||
6044 | if (TL.needsExtraLocalData()) { | |||
6045 | // Set info for the written builtin specifiers. | |||
6046 | TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); | |||
6047 | // Try to have a meaningful source location. | |||
6048 | if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified) | |||
6049 | TL.expandBuiltinRange(DS.getTypeSpecSignLoc()); | |||
6050 | if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified) | |||
6051 | TL.expandBuiltinRange(DS.getTypeSpecWidthRange()); | |||
6052 | } | |||
6053 | } | |||
6054 | void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { | |||
6055 | ElaboratedTypeKeyword Keyword | |||
6056 | = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); | |||
6057 | if (DS.getTypeSpecType() == TST_typename) { | |||
6058 | TypeSourceInfo *TInfo = nullptr; | |||
6059 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6060 | if (TInfo) { | |||
6061 | TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>()); | |||
6062 | return; | |||
6063 | } | |||
6064 | } | |||
6065 | TL.setElaboratedKeywordLoc(Keyword != ETK_None | |||
6066 | ? DS.getTypeSpecTypeLoc() | |||
6067 | : SourceLocation()); | |||
6068 | const CXXScopeSpec& SS = DS.getTypeSpecScope(); | |||
6069 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
6070 | Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); | |||
6071 | } | |||
6072 | void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { | |||
6073 | assert(DS.getTypeSpecType() == TST_typename)(static_cast <bool> (DS.getTypeSpecType() == TST_typename ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename" , "clang/lib/Sema/SemaType.cpp", 6073, __extension__ __PRETTY_FUNCTION__ )); | |||
6074 | TypeSourceInfo *TInfo = nullptr; | |||
6075 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6076 | assert(TInfo)(static_cast <bool> (TInfo) ? void (0) : __assert_fail ( "TInfo", "clang/lib/Sema/SemaType.cpp", 6076, __extension__ __PRETTY_FUNCTION__ )); | |||
6077 | TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); | |||
6078 | } | |||
6079 | void VisitDependentTemplateSpecializationTypeLoc( | |||
6080 | DependentTemplateSpecializationTypeLoc TL) { | |||
6081 | assert(DS.getTypeSpecType() == TST_typename)(static_cast <bool> (DS.getTypeSpecType() == TST_typename ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename" , "clang/lib/Sema/SemaType.cpp", 6081, __extension__ __PRETTY_FUNCTION__ )); | |||
6082 | TypeSourceInfo *TInfo = nullptr; | |||
6083 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6084 | assert(TInfo)(static_cast <bool> (TInfo) ? void (0) : __assert_fail ( "TInfo", "clang/lib/Sema/SemaType.cpp", 6084, __extension__ __PRETTY_FUNCTION__ )); | |||
6085 | TL.copy( | |||
6086 | TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); | |||
6087 | } | |||
6088 | void VisitAutoTypeLoc(AutoTypeLoc TL) { | |||
6089 | assert(DS.getTypeSpecType() == TST_auto ||(static_cast <bool> (DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType () == TST_auto_type || DS.getTypeSpecType() == TST_unspecified ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified" , "clang/lib/Sema/SemaType.cpp", 6092, __extension__ __PRETTY_FUNCTION__ )) | |||
6090 | DS.getTypeSpecType() == TST_decltype_auto ||(static_cast <bool> (DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType () == TST_auto_type || DS.getTypeSpecType() == TST_unspecified ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified" , "clang/lib/Sema/SemaType.cpp", 6092, __extension__ __PRETTY_FUNCTION__ )) | |||
6091 | DS.getTypeSpecType() == TST_auto_type ||(static_cast <bool> (DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType () == TST_auto_type || DS.getTypeSpecType() == TST_unspecified ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified" , "clang/lib/Sema/SemaType.cpp", 6092, __extension__ __PRETTY_FUNCTION__ )) | |||
6092 | DS.getTypeSpecType() == TST_unspecified)(static_cast <bool> (DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType () == TST_auto_type || DS.getTypeSpecType() == TST_unspecified ) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_auto || DS.getTypeSpecType() == TST_decltype_auto || DS.getTypeSpecType() == TST_auto_type || DS.getTypeSpecType() == TST_unspecified" , "clang/lib/Sema/SemaType.cpp", 6092, __extension__ __PRETTY_FUNCTION__ )); | |||
6093 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
6094 | if (DS.getTypeSpecType() == TST_decltype_auto) | |||
6095 | TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); | |||
6096 | if (!DS.isConstrainedAuto()) | |||
6097 | return; | |||
6098 | TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId(); | |||
6099 | if (!TemplateId) | |||
6100 | return; | |||
6101 | if (DS.getTypeSpecScope().isNotEmpty()) | |||
6102 | TL.setNestedNameSpecifierLoc( | |||
6103 | DS.getTypeSpecScope().getWithLocInContext(Context)); | |||
6104 | else | |||
6105 | TL.setNestedNameSpecifierLoc(NestedNameSpecifierLoc()); | |||
6106 | TL.setTemplateKWLoc(TemplateId->TemplateKWLoc); | |||
6107 | TL.setConceptNameLoc(TemplateId->TemplateNameLoc); | |||
6108 | TL.setFoundDecl(nullptr); | |||
6109 | TL.setLAngleLoc(TemplateId->LAngleLoc); | |||
6110 | TL.setRAngleLoc(TemplateId->RAngleLoc); | |||
6111 | if (TemplateId->NumArgs == 0) | |||
6112 | return; | |||
6113 | TemplateArgumentListInfo TemplateArgsInfo; | |||
6114 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
6115 | TemplateId->NumArgs); | |||
6116 | SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo); | |||
6117 | for (unsigned I = 0; I < TemplateId->NumArgs; ++I) | |||
6118 | TL.setArgLocInfo(I, TemplateArgsInfo.arguments()[I].getLocInfo()); | |||
6119 | } | |||
6120 | void VisitTagTypeLoc(TagTypeLoc TL) { | |||
6121 | TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); | |||
6122 | } | |||
6123 | void VisitAtomicTypeLoc(AtomicTypeLoc TL) { | |||
6124 | // An AtomicTypeLoc can come from either an _Atomic(...) type specifier | |||
6125 | // or an _Atomic qualifier. | |||
6126 | if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { | |||
6127 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | |||
6128 | TL.setParensRange(DS.getTypeofParensRange()); | |||
6129 | ||||
6130 | TypeSourceInfo *TInfo = nullptr; | |||
6131 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6132 | assert(TInfo)(static_cast <bool> (TInfo) ? void (0) : __assert_fail ( "TInfo", "clang/lib/Sema/SemaType.cpp", 6132, __extension__ __PRETTY_FUNCTION__ )); | |||
6133 | TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); | |||
6134 | } else { | |||
6135 | TL.setKWLoc(DS.getAtomicSpecLoc()); | |||
6136 | // No parens, to indicate this was spelled as an _Atomic qualifier. | |||
6137 | TL.setParensRange(SourceRange()); | |||
6138 | Visit(TL.getValueLoc()); | |||
6139 | } | |||
6140 | } | |||
6141 | ||||
6142 | void VisitPipeTypeLoc(PipeTypeLoc TL) { | |||
6143 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); | |||
6144 | ||||
6145 | TypeSourceInfo *TInfo = nullptr; | |||
6146 | Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo); | |||
6147 | TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc()); | |||
6148 | } | |||
6149 | ||||
6150 | void VisitExtIntTypeLoc(BitIntTypeLoc TL) { | |||
6151 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
6152 | } | |||
6153 | ||||
6154 | void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) { | |||
6155 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
6156 | } | |||
6157 | ||||
6158 | void VisitTypeLoc(TypeLoc TL) { | |||
6159 | // FIXME: add other typespec types and change this to an assert. | |||
6160 | TL.initialize(Context, DS.getTypeSpecTypeLoc()); | |||
6161 | } | |||
6162 | }; | |||
6163 | ||||
6164 | class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { | |||
6165 | ASTContext &Context; | |||
6166 | TypeProcessingState &State; | |||
6167 | const DeclaratorChunk &Chunk; | |||
6168 | ||||
6169 | public: | |||
6170 | DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State, | |||
6171 | const DeclaratorChunk &Chunk) | |||
6172 | : Context(Context), State(State), Chunk(Chunk) {} | |||
6173 | ||||
6174 | void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { | |||
6175 | llvm_unreachable("qualified type locs not expected here!")::llvm::llvm_unreachable_internal("qualified type locs not expected here!" , "clang/lib/Sema/SemaType.cpp", 6175); | |||
6176 | } | |||
6177 | void VisitDecayedTypeLoc(DecayedTypeLoc TL) { | |||
6178 | llvm_unreachable("decayed type locs not expected here!")::llvm::llvm_unreachable_internal("decayed type locs not expected here!" , "clang/lib/Sema/SemaType.cpp", 6178); | |||
6179 | } | |||
6180 | ||||
6181 | void VisitAttributedTypeLoc(AttributedTypeLoc TL) { | |||
6182 | fillAttributedTypeLoc(TL, State); | |||
6183 | } | |||
6184 | void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { | |||
6185 | // nothing | |||
6186 | } | |||
6187 | void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { | |||
6188 | // nothing | |||
6189 | } | |||
6190 | void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { | |||
6191 | assert(Chunk.Kind == DeclaratorChunk::BlockPointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::BlockPointer ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::BlockPointer" , "clang/lib/Sema/SemaType.cpp", 6191, __extension__ __PRETTY_FUNCTION__ )); | |||
6192 | TL.setCaretLoc(Chunk.Loc); | |||
6193 | } | |||
6194 | void VisitPointerTypeLoc(PointerTypeLoc TL) { | |||
6195 | assert(Chunk.Kind == DeclaratorChunk::Pointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Pointer ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pointer" , "clang/lib/Sema/SemaType.cpp", 6195, __extension__ __PRETTY_FUNCTION__ )); | |||
6196 | TL.setStarLoc(Chunk.Loc); | |||
6197 | } | |||
6198 | void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { | |||
6199 | assert(Chunk.Kind == DeclaratorChunk::Pointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Pointer ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pointer" , "clang/lib/Sema/SemaType.cpp", 6199, __extension__ __PRETTY_FUNCTION__ )); | |||
6200 | TL.setStarLoc(Chunk.Loc); | |||
6201 | } | |||
6202 | void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { | |||
6203 | assert(Chunk.Kind == DeclaratorChunk::MemberPointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::MemberPointer ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::MemberPointer" , "clang/lib/Sema/SemaType.cpp", 6203, __extension__ __PRETTY_FUNCTION__ )); | |||
6204 | const CXXScopeSpec& SS = Chunk.Mem.Scope(); | |||
6205 | NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); | |||
6206 | ||||
6207 | const Type* ClsTy = TL.getClass(); | |||
6208 | QualType ClsQT = QualType(ClsTy, 0); | |||
6209 | TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0); | |||
6210 | // Now copy source location info into the type loc component. | |||
6211 | TypeLoc ClsTL = ClsTInfo->getTypeLoc(); | |||
6212 | switch (NNSLoc.getNestedNameSpecifier()->getKind()) { | |||
6213 | case NestedNameSpecifier::Identifier: | |||
6214 | assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc")(static_cast <bool> (isa<DependentNameType>(ClsTy ) && "Unexpected TypeLoc") ? void (0) : __assert_fail ("isa<DependentNameType>(ClsTy) && \"Unexpected TypeLoc\"" , "clang/lib/Sema/SemaType.cpp", 6214, __extension__ __PRETTY_FUNCTION__ )); | |||
6215 | { | |||
6216 | DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); | |||
6217 | DNTLoc.setElaboratedKeywordLoc(SourceLocation()); | |||
6218 | DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); | |||
6219 | DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); | |||
6220 | } | |||
6221 | break; | |||
6222 | ||||
6223 | case NestedNameSpecifier::TypeSpec: | |||
6224 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
6225 | if (isa<ElaboratedType>(ClsTy)) { | |||
6226 | ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); | |||
6227 | ETLoc.setElaboratedKeywordLoc(SourceLocation()); | |||
6228 | ETLoc.setQualifierLoc(NNSLoc.getPrefix()); | |||
6229 | TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); | |||
6230 | NamedTL.initializeFullCopy(NNSLoc.getTypeLoc()); | |||
6231 | } else { | |||
6232 | ClsTL.initializeFullCopy(NNSLoc.getTypeLoc()); | |||
6233 | } | |||
6234 | break; | |||
6235 | ||||
6236 | case NestedNameSpecifier::Namespace: | |||
6237 | case NestedNameSpecifier::NamespaceAlias: | |||
6238 | case NestedNameSpecifier::Global: | |||
6239 | case NestedNameSpecifier::Super: | |||
6240 | llvm_unreachable("Nested-name-specifier must name a type")::llvm::llvm_unreachable_internal("Nested-name-specifier must name a type" , "clang/lib/Sema/SemaType.cpp", 6240); | |||
6241 | } | |||
6242 | ||||
6243 | // Finally fill in MemberPointerLocInfo fields. | |||
6244 | TL.setStarLoc(Chunk.Mem.StarLoc); | |||
6245 | TL.setClassTInfo(ClsTInfo); | |||
6246 | } | |||
6247 | void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { | |||
6248 | assert(Chunk.Kind == DeclaratorChunk::Reference)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Reference ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Reference" , "clang/lib/Sema/SemaType.cpp", 6248, __extension__ __PRETTY_FUNCTION__ )); | |||
6249 | // 'Amp' is misleading: this might have been originally | |||
6250 | /// spelled with AmpAmp. | |||
6251 | TL.setAmpLoc(Chunk.Loc); | |||
6252 | } | |||
6253 | void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { | |||
6254 | assert(Chunk.Kind == DeclaratorChunk::Reference)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Reference ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Reference" , "clang/lib/Sema/SemaType.cpp", 6254, __extension__ __PRETTY_FUNCTION__ )); | |||
6255 | assert(!Chunk.Ref.LValueRef)(static_cast <bool> (!Chunk.Ref.LValueRef) ? void (0) : __assert_fail ("!Chunk.Ref.LValueRef", "clang/lib/Sema/SemaType.cpp" , 6255, __extension__ __PRETTY_FUNCTION__)); | |||
6256 | TL.setAmpAmpLoc(Chunk.Loc); | |||
6257 | } | |||
6258 | void VisitArrayTypeLoc(ArrayTypeLoc TL) { | |||
6259 | assert(Chunk.Kind == DeclaratorChunk::Array)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Array ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Array" , "clang/lib/Sema/SemaType.cpp", 6259, __extension__ __PRETTY_FUNCTION__ )); | |||
6260 | TL.setLBracketLoc(Chunk.Loc); | |||
6261 | TL.setRBracketLoc(Chunk.EndLoc); | |||
6262 | TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); | |||
6263 | } | |||
6264 | void VisitFunctionTypeLoc(FunctionTypeLoc TL) { | |||
6265 | assert(Chunk.Kind == DeclaratorChunk::Function)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Function ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function" , "clang/lib/Sema/SemaType.cpp", 6265, __extension__ __PRETTY_FUNCTION__ )); | |||
6266 | TL.setLocalRangeBegin(Chunk.Loc); | |||
6267 | TL.setLocalRangeEnd(Chunk.EndLoc); | |||
6268 | ||||
6269 | const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; | |||
6270 | TL.setLParenLoc(FTI.getLParenLoc()); | |||
6271 | TL.setRParenLoc(FTI.getRParenLoc()); | |||
6272 | for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { | |||
6273 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | |||
6274 | TL.setParam(tpi++, Param); | |||
6275 | } | |||
6276 | TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); | |||
6277 | } | |||
6278 | void VisitParenTypeLoc(ParenTypeLoc TL) { | |||
6279 | assert(Chunk.Kind == DeclaratorChunk::Paren)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Paren ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Paren" , "clang/lib/Sema/SemaType.cpp", 6279, __extension__ __PRETTY_FUNCTION__ )); | |||
6280 | TL.setLParenLoc(Chunk.Loc); | |||
6281 | TL.setRParenLoc(Chunk.EndLoc); | |||
6282 | } | |||
6283 | void VisitPipeTypeLoc(PipeTypeLoc TL) { | |||
6284 | assert(Chunk.Kind == DeclaratorChunk::Pipe)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Pipe ) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pipe" , "clang/lib/Sema/SemaType.cpp", 6284, __extension__ __PRETTY_FUNCTION__ )); | |||
6285 | TL.setKWLoc(Chunk.Loc); | |||
6286 | } | |||
6287 | void VisitBitIntTypeLoc(BitIntTypeLoc TL) { | |||
6288 | TL.setNameLoc(Chunk.Loc); | |||
6289 | } | |||
6290 | void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { | |||
6291 | TL.setExpansionLoc(Chunk.Loc); | |||
6292 | } | |||
6293 | void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); } | |||
6294 | void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) { | |||
6295 | TL.setNameLoc(Chunk.Loc); | |||
6296 | } | |||
6297 | void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { | |||
6298 | TL.setNameLoc(Chunk.Loc); | |||
6299 | } | |||
6300 | void | |||
6301 | VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) { | |||
6302 | TL.setNameLoc(Chunk.Loc); | |||
6303 | } | |||
6304 | ||||
6305 | void VisitTypeLoc(TypeLoc TL) { | |||
6306 | llvm_unreachable("unsupported TypeLoc kind in declarator!")::llvm::llvm_unreachable_internal("unsupported TypeLoc kind in declarator!" , "clang/lib/Sema/SemaType.cpp", 6306); | |||
6307 | } | |||
6308 | }; | |||
6309 | } // end anonymous namespace | |||
6310 | ||||
6311 | static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { | |||
6312 | SourceLocation Loc; | |||
6313 | switch (Chunk.Kind) { | |||
6314 | case DeclaratorChunk::Function: | |||
6315 | case DeclaratorChunk::Array: | |||
6316 | case DeclaratorChunk::Paren: | |||
6317 | case DeclaratorChunk::Pipe: | |||
6318 | llvm_unreachable("cannot be _Atomic qualified")::llvm::llvm_unreachable_internal("cannot be _Atomic qualified" , "clang/lib/Sema/SemaType.cpp", 6318); | |||
6319 | ||||
6320 | case DeclaratorChunk::Pointer: | |||
6321 | Loc = Chunk.Ptr.AtomicQualLoc; | |||
6322 | break; | |||
6323 | ||||
6324 | case DeclaratorChunk::BlockPointer: | |||
6325 | case DeclaratorChunk::Reference: | |||
6326 | case DeclaratorChunk::MemberPointer: | |||
6327 | // FIXME: Provide a source location for the _Atomic keyword. | |||
6328 | break; | |||
6329 | } | |||
6330 | ||||
6331 | ATL.setKWLoc(Loc); | |||
6332 | ATL.setParensRange(SourceRange()); | |||
6333 | } | |||
6334 | ||||
6335 | static void | |||
6336 | fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, | |||
6337 | const ParsedAttributesView &Attrs) { | |||
6338 | for (const ParsedAttr &AL : Attrs) { | |||
6339 | if (AL.getKind() == ParsedAttr::AT_AddressSpace) { | |||
6340 | DASTL.setAttrNameLoc(AL.getLoc()); | |||
6341 | DASTL.setAttrExprOperand(AL.getArgAsExpr(0)); | |||
6342 | DASTL.setAttrOperandParensRange(SourceRange()); | |||
6343 | return; | |||
6344 | } | |||
6345 | } | |||
6346 | ||||
6347 | llvm_unreachable(::llvm::llvm_unreachable_internal("no address_space attribute found at the expected location!" , "clang/lib/Sema/SemaType.cpp", 6348) | |||
6348 | "no address_space attribute found at the expected location!")::llvm::llvm_unreachable_internal("no address_space attribute found at the expected location!" , "clang/lib/Sema/SemaType.cpp", 6348); | |||
6349 | } | |||
6350 | ||||
6351 | static void fillMatrixTypeLoc(MatrixTypeLoc MTL, | |||
6352 | const ParsedAttributesView &Attrs) { | |||
6353 | for (const ParsedAttr &AL : Attrs) { | |||
6354 | if (AL.getKind() == ParsedAttr::AT_MatrixType) { | |||
6355 | MTL.setAttrNameLoc(AL.getLoc()); | |||
6356 | MTL.setAttrRowOperand(AL.getArgAsExpr(0)); | |||
6357 | MTL.setAttrColumnOperand(AL.getArgAsExpr(1)); | |||
6358 | MTL.setAttrOperandParensRange(SourceRange()); | |||
6359 | return; | |||
6360 | } | |||
6361 | } | |||
6362 | ||||
6363 | llvm_unreachable("no matrix_type attribute found at the expected location!")::llvm::llvm_unreachable_internal("no matrix_type attribute found at the expected location!" , "clang/lib/Sema/SemaType.cpp", 6363); | |||
6364 | } | |||
6365 | ||||
6366 | /// Create and instantiate a TypeSourceInfo with type source information. | |||
6367 | /// | |||
6368 | /// \param T QualType referring to the type as written in source code. | |||
6369 | /// | |||
6370 | /// \param ReturnTypeInfo For declarators whose return type does not show | |||
6371 | /// up in the normal place in the declaration specifiers (such as a C++ | |||
6372 | /// conversion function), this pointer will refer to a type source information | |||
6373 | /// for that return type. | |||
6374 | static TypeSourceInfo * | |||
6375 | GetTypeSourceInfoForDeclarator(TypeProcessingState &State, | |||
6376 | QualType T, TypeSourceInfo *ReturnTypeInfo) { | |||
6377 | Sema &S = State.getSema(); | |||
6378 | Declarator &D = State.getDeclarator(); | |||
6379 | ||||
6380 | TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T); | |||
6381 | UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); | |||
6382 | ||||
6383 | // Handle parameter packs whose type is a pack expansion. | |||
6384 | if (isa<PackExpansionType>(T)) { | |||
6385 | CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); | |||
6386 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); | |||
6387 | } | |||
6388 | ||||
6389 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | |||
6390 | // An AtomicTypeLoc might be produced by an atomic qualifier in this | |||
6391 | // declarator chunk. | |||
6392 | if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { | |||
6393 | fillAtomicQualLoc(ATL, D.getTypeObject(i)); | |||
6394 | CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); | |||
6395 | } | |||
6396 | ||||
6397 | while (MacroQualifiedTypeLoc TL = CurrTL.getAs<MacroQualifiedTypeLoc>()) { | |||
6398 | TL.setExpansionLoc( | |||
6399 | State.getExpansionLocForMacroQualifiedType(TL.getTypePtr())); | |||
6400 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); | |||
6401 | } | |||
6402 | ||||
6403 | while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) { | |||
6404 | fillAttributedTypeLoc(TL, State); | |||
6405 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); | |||
6406 | } | |||
6407 | ||||
6408 | while (DependentAddressSpaceTypeLoc TL = | |||
6409 | CurrTL.getAs<DependentAddressSpaceTypeLoc>()) { | |||
6410 | fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs()); | |||
6411 | CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc(); | |||
6412 | } | |||
6413 | ||||
6414 | if (MatrixTypeLoc TL = CurrTL.getAs<MatrixTypeLoc>()) | |||
6415 | fillMatrixTypeLoc(TL, D.getTypeObject(i).getAttrs()); | |||
6416 | ||||
6417 | // FIXME: Ordering here? | |||
6418 | while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>()) | |||
6419 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); | |||
6420 | ||||
6421 | DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL); | |||
6422 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); | |||
6423 | } | |||
6424 | ||||
6425 | // If we have different source information for the return type, use | |||
6426 | // that. This really only applies to C++ conversion functions. | |||
6427 | if (ReturnTypeInfo) { | |||
6428 | TypeLoc TL = ReturnTypeInfo->getTypeLoc(); | |||
6429 | assert(TL.getFullDataSize() == CurrTL.getFullDataSize())(static_cast <bool> (TL.getFullDataSize() == CurrTL.getFullDataSize ()) ? void (0) : __assert_fail ("TL.getFullDataSize() == CurrTL.getFullDataSize()" , "clang/lib/Sema/SemaType.cpp", 6429, __extension__ __PRETTY_FUNCTION__ )); | |||
6430 | memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); | |||
6431 | } else { | |||
6432 | TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL); | |||
6433 | } | |||
6434 | ||||
6435 | return TInfo; | |||
6436 | } | |||
6437 | ||||
6438 | /// Create a LocInfoType to hold the given QualType and TypeSourceInfo. | |||
6439 | ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { | |||
6440 | // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser | |||
6441 | // and Sema during declaration parsing. Try deallocating/caching them when | |||
6442 | // it's appropriate, instead of allocating them and keeping them around. | |||
6443 | LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), | |||
6444 | TypeAlignment); | |||
6445 | new (LocT) LocInfoType(T, TInfo); | |||
6446 | assert(LocT->getTypeClass() != T->getTypeClass() &&(static_cast <bool> (LocT->getTypeClass() != T->getTypeClass () && "LocInfoType's TypeClass conflicts with an existing Type class" ) ? void (0) : __assert_fail ("LocT->getTypeClass() != T->getTypeClass() && \"LocInfoType's TypeClass conflicts with an existing Type class\"" , "clang/lib/Sema/SemaType.cpp", 6447, __extension__ __PRETTY_FUNCTION__ )) | |||
6447 | "LocInfoType's TypeClass conflicts with an existing Type class")(static_cast <bool> (LocT->getTypeClass() != T->getTypeClass () && "LocInfoType's TypeClass conflicts with an existing Type class" ) ? void (0) : __assert_fail ("LocT->getTypeClass() != T->getTypeClass() && \"LocInfoType's TypeClass conflicts with an existing Type class\"" , "clang/lib/Sema/SemaType.cpp", 6447, __extension__ __PRETTY_FUNCTION__ )); | |||
6448 | return ParsedType::make(QualType(LocT, 0)); | |||
6449 | } | |||
6450 | ||||
6451 | void LocInfoType::getAsStringInternal(std::string &Str, | |||
6452 | const PrintingPolicy &Policy) const { | |||
6453 | llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"::llvm::llvm_unreachable_internal("LocInfoType leaked into the type system; an opaque TypeTy*" " was used directly instead of getting the QualType through" " GetTypeFromParser", "clang/lib/Sema/SemaType.cpp", 6455) | |||
6454 | " was used directly instead of getting the QualType through"::llvm::llvm_unreachable_internal("LocInfoType leaked into the type system; an opaque TypeTy*" " was used directly instead of getting the QualType through" " GetTypeFromParser", "clang/lib/Sema/SemaType.cpp", 6455) | |||
6455 | " GetTypeFromParser")::llvm::llvm_unreachable_internal("LocInfoType leaked into the type system; an opaque TypeTy*" " was used directly instead of getting the QualType through" " GetTypeFromParser", "clang/lib/Sema/SemaType.cpp", 6455); | |||
6456 | } | |||
6457 | ||||
6458 | TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { | |||
6459 | // C99 6.7.6: Type names have no identifier. This is already validated by | |||
6460 | // the parser. | |||
6461 | assert(D.getIdentifier() == nullptr &&(static_cast <bool> (D.getIdentifier() == nullptr && "Type name should have no identifier!") ? void (0) : __assert_fail ("D.getIdentifier() == nullptr && \"Type name should have no identifier!\"" , "clang/lib/Sema/SemaType.cpp", 6462, __extension__ __PRETTY_FUNCTION__ )) | |||
6462 | "Type name should have no identifier!")(static_cast <bool> (D.getIdentifier() == nullptr && "Type name should have no identifier!") ? void (0) : __assert_fail ("D.getIdentifier() == nullptr && \"Type name should have no identifier!\"" , "clang/lib/Sema/SemaType.cpp", 6462, __extension__ __PRETTY_FUNCTION__ )); | |||
6463 | ||||
6464 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
6465 | QualType T = TInfo->getType(); | |||
6466 | if (D.isInvalidType()) | |||
6467 | return true; | |||
6468 | ||||
6469 | // Make sure there are no unused decl attributes on the declarator. | |||
6470 | // We don't want to do this for ObjC parameters because we're going | |||
6471 | // to apply them to the actual parameter declaration. | |||
6472 | // Likewise, we don't want to do this for alias declarations, because | |||
6473 | // we are actually going to build a declaration from this eventually. | |||
6474 | if (D.getContext() != DeclaratorContext::ObjCParameter && | |||
6475 | D.getContext() != DeclaratorContext::AliasDecl && | |||
6476 | D.getContext() != DeclaratorContext::AliasTemplate) | |||
6477 | checkUnusedDeclAttributes(D); | |||
6478 | ||||
6479 | if (getLangOpts().CPlusPlus) { | |||
6480 | // Check that there are no default arguments (C++ only). | |||
6481 | CheckExtraCXXDefaultArguments(D); | |||
6482 | } | |||
6483 | ||||
6484 | return CreateParsedType(T, TInfo); | |||
6485 | } | |||
6486 | ||||
6487 | ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { | |||
6488 | QualType T = Context.getObjCInstanceType(); | |||
6489 | TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | |||
6490 | return CreateParsedType(T, TInfo); | |||
6491 | } | |||
6492 | ||||
6493 | //===----------------------------------------------------------------------===// | |||
6494 | // Type Attribute Processing | |||
6495 | //===----------------------------------------------------------------------===// | |||
6496 | ||||
6497 | /// Build an AddressSpace index from a constant expression and diagnose any | |||
6498 | /// errors related to invalid address_spaces. Returns true on successfully | |||
6499 | /// building an AddressSpace index. | |||
6500 | static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, | |||
6501 | const Expr *AddrSpace, | |||
6502 | SourceLocation AttrLoc) { | |||
6503 | if (!AddrSpace->isValueDependent()) { | |||
6504 | Optional<llvm::APSInt> OptAddrSpace = | |||
6505 | AddrSpace->getIntegerConstantExpr(S.Context); | |||
6506 | if (!OptAddrSpace) { | |||
6507 | S.Diag(AttrLoc, diag::err_attribute_argument_type) | |||
6508 | << "'address_space'" << AANT_ArgumentIntegerConstant | |||
6509 | << AddrSpace->getSourceRange(); | |||
6510 | return false; | |||
6511 | } | |||
6512 | llvm::APSInt &addrSpace = *OptAddrSpace; | |||
6513 | ||||
6514 | // Bounds checking. | |||
6515 | if (addrSpace.isSigned()) { | |||
6516 | if (addrSpace.isNegative()) { | |||
6517 | S.Diag(AttrLoc, diag::err_attribute_address_space_negative) | |||
6518 | << AddrSpace->getSourceRange(); | |||
6519 | return false; | |||
6520 | } | |||
6521 | addrSpace.setIsSigned(false); | |||
6522 | } | |||
6523 | ||||
6524 | llvm::APSInt max(addrSpace.getBitWidth()); | |||
6525 | max = | |||
6526 | Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace; | |||
6527 | ||||
6528 | if (addrSpace > max) { | |||
6529 | S.Diag(AttrLoc, diag::err_attribute_address_space_too_high) | |||
6530 | << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange(); | |||
6531 | return false; | |||
6532 | } | |||
6533 | ||||
6534 | ASIdx = | |||
6535 | getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue())); | |||
6536 | return true; | |||
6537 | } | |||
6538 | ||||
6539 | // Default value for DependentAddressSpaceTypes | |||
6540 | ASIdx = LangAS::Default; | |||
6541 | return true; | |||
6542 | } | |||
6543 | ||||
6544 | /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression | |||
6545 | /// is uninstantiated. If instantiated it will apply the appropriate address | |||
6546 | /// space to the type. This function allows dependent template variables to be | |||
6547 | /// used in conjunction with the address_space attribute | |||
6548 | QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, | |||
6549 | SourceLocation AttrLoc) { | |||
6550 | if (!AddrSpace->isValueDependent()) { | |||
6551 | if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx, | |||
6552 | AttrLoc)) | |||
6553 | return QualType(); | |||
6554 | ||||
6555 | return Context.getAddrSpaceQualType(T, ASIdx); | |||
6556 | } | |||
6557 | ||||
6558 | // A check with similar intentions as checking if a type already has an | |||
6559 | // address space except for on a dependent types, basically if the | |||
6560 | // current type is already a DependentAddressSpaceType then its already | |||
6561 | // lined up to have another address space on it and we can't have | |||
6562 | // multiple address spaces on the one pointer indirection | |||
6563 | if (T->getAs<DependentAddressSpaceType>()) { | |||
6564 | Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); | |||
6565 | return QualType(); | |||
6566 | } | |||
6567 | ||||
6568 | return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc); | |||
6569 | } | |||
6570 | ||||
6571 | QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, | |||
6572 | SourceLocation AttrLoc) { | |||
6573 | LangAS ASIdx; | |||
6574 | if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc)) | |||
6575 | return QualType(); | |||
6576 | return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc); | |||
6577 | } | |||
6578 | ||||
6579 | static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr, | |||
6580 | TypeProcessingState &State) { | |||
6581 | Sema &S = State.getSema(); | |||
6582 | ||||
6583 | // Check the number of attribute arguments. | |||
6584 | if (Attr.getNumArgs() != 1) { | |||
6585 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) | |||
6586 | << Attr << 1; | |||
6587 | Attr.setInvalid(); | |||
6588 | return; | |||
6589 | } | |||
6590 | ||||
6591 | // Ensure the argument is a string. | |||
6592 | auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0)); | |||
6593 | if (!StrLiteral) { | |||
6594 | S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) | |||
6595 | << Attr << AANT_ArgumentString; | |||
6596 | Attr.setInvalid(); | |||
6597 | return; | |||
6598 | } | |||
6599 | ||||
6600 | ASTContext &Ctx = S.Context; | |||
6601 | StringRef BTFTypeTag = StrLiteral->getString(); | |||
6602 | Type = State.getBTFTagAttributedType( | |||
6603 | ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type); | |||
6604 | } | |||
6605 | ||||
6606 | /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the | |||
6607 | /// specified type. The attribute contains 1 argument, the id of the address | |||
6608 | /// space for the type. | |||
6609 | static void HandleAddressSpaceTypeAttribute(QualType &Type, | |||
6610 | const ParsedAttr &Attr, | |||
6611 | TypeProcessingState &State) { | |||
6612 | Sema &S = State.getSema(); | |||
6613 | ||||
6614 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be | |||
6615 | // qualified by an address-space qualifier." | |||
6616 | if (Type->isFunctionType()) { | |||
6617 | S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); | |||
6618 | Attr.setInvalid(); | |||
6619 | return; | |||
6620 | } | |||
6621 | ||||
6622 | LangAS ASIdx; | |||
6623 | if (Attr.getKind() == ParsedAttr::AT_AddressSpace) { | |||
6624 | ||||
6625 | // Check the attribute arguments. | |||
6626 | if (Attr.getNumArgs() != 1) { | |||
6627 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | |||
6628 | << 1; | |||
6629 | Attr.setInvalid(); | |||
6630 | return; | |||
6631 | } | |||
6632 | ||||
6633 | Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); | |||
6634 | LangAS ASIdx; | |||
6635 | if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) { | |||
6636 | Attr.setInvalid(); | |||
6637 | return; | |||
6638 | } | |||
6639 | ||||
6640 | ASTContext &Ctx = S.Context; | |||
6641 | auto *ASAttr = | |||
6642 | ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx)); | |||
6643 | ||||
6644 | // If the expression is not value dependent (not templated), then we can | |||
6645 | // apply the address space qualifiers just to the equivalent type. | |||
6646 | // Otherwise, we make an AttributedType with the modified and equivalent | |||
6647 | // type the same, and wrap it in a DependentAddressSpaceType. When this | |||
6648 | // dependent type is resolved, the qualifier is added to the equivalent type | |||
6649 | // later. | |||
6650 | QualType T; | |||
6651 | if (!ASArgExpr->isValueDependent()) { | |||
6652 | QualType EquivType = | |||
6653 | S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc()); | |||
6654 | if (EquivType.isNull()) { | |||
6655 | Attr.setInvalid(); | |||
6656 | return; | |||
6657 | } | |||
6658 | T = State.getAttributedType(ASAttr, Type, EquivType); | |||
6659 | } else { | |||
6660 | T = State.getAttributedType(ASAttr, Type, Type); | |||
6661 | T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc()); | |||
6662 | } | |||
6663 | ||||
6664 | if (!T.isNull()) | |||
6665 | Type = T; | |||
6666 | else | |||
6667 | Attr.setInvalid(); | |||
6668 | } else { | |||
6669 | // The keyword-based type attributes imply which address space to use. | |||
6670 | ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS() | |||
6671 | : Attr.asOpenCLLangAS(); | |||
6672 | ||||
6673 | if (ASIdx == LangAS::Default) | |||
6674 | llvm_unreachable("Invalid address space")::llvm::llvm_unreachable_internal("Invalid address space", "clang/lib/Sema/SemaType.cpp" , 6674); | |||
6675 | ||||
6676 | if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx, | |||
6677 | Attr.getLoc())) { | |||
6678 | Attr.setInvalid(); | |||
6679 | return; | |||
6680 | } | |||
6681 | ||||
6682 | Type = S.Context.getAddrSpaceQualType(Type, ASIdx); | |||
6683 | } | |||
6684 | } | |||
6685 | ||||
6686 | /// handleObjCOwnershipTypeAttr - Process an objc_ownership | |||
6687 | /// attribute on the specified type. | |||
6688 | /// | |||
6689 | /// Returns 'true' if the attribute was handled. | |||
6690 | static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, | |||
6691 | ParsedAttr &attr, QualType &type) { | |||
6692 | bool NonObjCPointer = false; | |||
6693 | ||||
6694 | if (!type->isDependentType() && !type->isUndeducedType()) { | |||
6695 | if (const PointerType *ptr = type->getAs<PointerType>()) { | |||
6696 | QualType pointee = ptr->getPointeeType(); | |||
6697 | if (pointee->isObjCRetainableType() || pointee->isPointerType()) | |||
6698 | return false; | |||
6699 | // It is important not to lose the source info that there was an attribute | |||
6700 | // applied to non-objc pointer. We will create an attributed type but | |||
6701 | // its type will be the same as the original type. | |||
6702 | NonObjCPointer = true; | |||
6703 | } else if (!type->isObjCRetainableType()) { | |||
6704 | return false; | |||
6705 | } | |||
6706 | ||||
6707 | // Don't accept an ownership attribute in the declspec if it would | |||
6708 | // just be the return type of a block pointer. | |||
6709 | if (state.isProcessingDeclSpec()) { | |||
6710 | Declarator &D = state.getDeclarator(); | |||
6711 | if (maybeMovePastReturnType(D, D.getNumTypeObjects(), | |||
6712 | /*onlyBlockPointers=*/true)) | |||
6713 | return false; | |||
6714 | } | |||
6715 | } | |||
6716 | ||||
6717 | Sema &S = state.getSema(); | |||
6718 | SourceLocation AttrLoc = attr.getLoc(); | |||
6719 | if (AttrLoc.isMacroID()) | |||
6720 | AttrLoc = | |||
6721 | S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin(); | |||
6722 | ||||
6723 | if (!attr.isArgIdent(0)) { | |||
6724 | S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr | |||
6725 | << AANT_ArgumentString; | |||
6726 | attr.setInvalid(); | |||
6727 | return true; | |||
6728 | } | |||
6729 | ||||
6730 | IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; | |||
6731 | Qualifiers::ObjCLifetime lifetime; | |||
6732 | if (II->isStr("none")) | |||
6733 | lifetime = Qualifiers::OCL_ExplicitNone; | |||
6734 | else if (II->isStr("strong")) | |||
6735 | lifetime = Qualifiers::OCL_Strong; | |||
6736 | else if (II->isStr("weak")) | |||
6737 | lifetime = Qualifiers::OCL_Weak; | |||
6738 | else if (II->isStr("autoreleasing")) | |||
6739 | lifetime = Qualifiers::OCL_Autoreleasing; | |||
6740 | else { | |||
6741 | S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II; | |||
6742 | attr.setInvalid(); | |||
6743 | return true; | |||
6744 | } | |||
6745 | ||||
6746 | // Just ignore lifetime attributes other than __weak and __unsafe_unretained | |||
6747 | // outside of ARC mode. | |||
6748 | if (!S.getLangOpts().ObjCAutoRefCount && | |||
6749 | lifetime != Qualifiers::OCL_Weak && | |||
6750 | lifetime != Qualifiers::OCL_ExplicitNone) { | |||
6751 | return true; | |||
6752 | } | |||
6753 | ||||
6754 | SplitQualType underlyingType = type.split(); | |||
6755 | ||||
6756 | // Check for redundant/conflicting ownership qualifiers. | |||
6757 | if (Qualifiers::ObjCLifetime previousLifetime | |||
6758 | = type.getQualifiers().getObjCLifetime()) { | |||
6759 | // If it's written directly, that's an error. | |||
6760 | if (S.Context.hasDirectOwnershipQualifier(type)) { | |||
6761 | S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) | |||
6762 | << type; | |||
6763 | return true; | |||
6764 | } | |||
6765 | ||||
6766 | // Otherwise, if the qualifiers actually conflict, pull sugar off | |||
6767 | // and remove the ObjCLifetime qualifiers. | |||
6768 | if (previousLifetime != lifetime) { | |||
6769 | // It's possible to have multiple local ObjCLifetime qualifiers. We | |||
6770 | // can't stop after we reach a type that is directly qualified. | |||
6771 | const Type *prevTy = nullptr; | |||
6772 | while (!prevTy || prevTy != underlyingType.Ty) { | |||
6773 | prevTy = underlyingType.Ty; | |||
6774 | underlyingType = underlyingType.getSingleStepDesugaredType(); | |||
6775 | } | |||
6776 | underlyingType.Quals.removeObjCLifetime(); | |||
6777 | } | |||
6778 | } | |||
6779 | ||||
6780 | underlyingType.Quals.addObjCLifetime(lifetime); | |||
6781 | ||||
6782 | if (NonObjCPointer) { | |||
6783 | StringRef name = attr.getAttrName()->getName(); | |||
6784 | switch (lifetime) { | |||
6785 | case Qualifiers::OCL_None: | |||
6786 | case Qualifiers::OCL_ExplicitNone: | |||
6787 | break; | |||
6788 | case Qualifiers::OCL_Strong: name = "__strong"; break; | |||
6789 | case Qualifiers::OCL_Weak: name = "__weak"; break; | |||
6790 | case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break; | |||
6791 | } | |||
6792 | S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name | |||
6793 | << TDS_ObjCObjOrBlock << type; | |||
6794 | } | |||
6795 | ||||
6796 | // Don't actually add the __unsafe_unretained qualifier in non-ARC files, | |||
6797 | // because having both 'T' and '__unsafe_unretained T' exist in the type | |||
6798 | // system causes unfortunate widespread consistency problems. (For example, | |||
6799 | // they're not considered compatible types, and we mangle them identicially | |||
6800 | // as template arguments.) These problems are all individually fixable, | |||
6801 | // but it's easier to just not add the qualifier and instead sniff it out | |||
6802 | // in specific places using isObjCInertUnsafeUnretainedType(). | |||
6803 | // | |||
6804 | // Doing this does means we miss some trivial consistency checks that | |||
6805 | // would've triggered in ARC, but that's better than trying to solve all | |||
6806 | // the coexistence problems with __unsafe_unretained. | |||
6807 | if (!S.getLangOpts().ObjCAutoRefCount && | |||
6808 | lifetime == Qualifiers::OCL_ExplicitNone) { | |||
6809 | type = state.getAttributedType( | |||
6810 | createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr), | |||
6811 | type, type); | |||
6812 | return true; | |||
6813 | } | |||
6814 | ||||
6815 | QualType origType = type; | |||
6816 | if (!NonObjCPointer) | |||
6817 | type = S.Context.getQualifiedType(underlyingType); | |||
6818 | ||||
6819 | // If we have a valid source location for the attribute, use an | |||
6820 | // AttributedType instead. | |||
6821 | if (AttrLoc.isValid()) { | |||
6822 | type = state.getAttributedType(::new (S.Context) | |||
6823 | ObjCOwnershipAttr(S.Context, attr, II), | |||
6824 | origType, type); | |||
6825 | } | |||
6826 | ||||
6827 | auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, | |||
6828 | unsigned diagnostic, QualType type) { | |||
6829 | if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { | |||
6830 | S.DelayedDiagnostics.add( | |||
6831 | sema::DelayedDiagnostic::makeForbiddenType( | |||
6832 | S.getSourceManager().getExpansionLoc(loc), | |||
6833 | diagnostic, type, /*ignored*/ 0)); | |||
6834 | } else { | |||
6835 | S.Diag(loc, diagnostic); | |||
6836 | } | |||
6837 | }; | |||
6838 | ||||
6839 | // Sometimes, __weak isn't allowed. | |||
6840 | if (lifetime == Qualifiers::OCL_Weak && | |||
6841 | !S.getLangOpts().ObjCWeak && !NonObjCPointer) { | |||
6842 | ||||
6843 | // Use a specialized diagnostic if the runtime just doesn't support them. | |||
6844 | unsigned diagnostic = | |||
6845 | (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled | |||
6846 | : diag::err_arc_weak_no_runtime); | |||
6847 | ||||
6848 | // In any case, delay the diagnostic until we know what we're parsing. | |||
6849 | diagnoseOrDelay(S, AttrLoc, diagnostic, type); | |||
6850 | ||||
6851 | attr.setInvalid(); | |||
6852 | return true; | |||
6853 | } | |||
6854 | ||||
6855 | // Forbid __weak for class objects marked as | |||
6856 | // objc_arc_weak_reference_unavailable | |||
6857 | if (lifetime == Qualifiers::OCL_Weak) { | |||
6858 | if (const ObjCObjectPointerType *ObjT = | |||
6859 | type->getAs<ObjCObjectPointerType>()) { | |||
6860 | if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { | |||
6861 | if (Class->isArcWeakrefUnavailable()) { | |||
6862 | S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); | |||
6863 | S.Diag(ObjT->getInterfaceDecl()->getLocation(), | |||
6864 | diag::note_class_declared); | |||
6865 | } | |||
6866 | } | |||
6867 | } | |||
6868 | } | |||
6869 | ||||
6870 | return true; | |||
6871 | } | |||
6872 | ||||
6873 | /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type | |||
6874 | /// attribute on the specified type. Returns true to indicate that | |||
6875 | /// the attribute was handled, false to indicate that the type does | |||
6876 | /// not permit the attribute. | |||
6877 | static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | |||
6878 | QualType &type) { | |||
6879 | Sema &S = state.getSema(); | |||
6880 | ||||
6881 | // Delay if this isn't some kind of pointer. | |||
6882 | if (!type->isPointerType() && | |||
6883 | !type->isObjCObjectPointerType() && | |||
6884 | !type->isBlockPointerType()) | |||
6885 | return false; | |||
6886 | ||||
6887 | if (type.getObjCGCAttr() != Qualifiers::GCNone) { | |||
6888 | S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); | |||
6889 | attr.setInvalid(); | |||
6890 | return true; | |||
6891 | } | |||
6892 | ||||
6893 | // Check the attribute arguments. | |||
6894 | if (!attr.isArgIdent(0)) { | |||
6895 | S.Diag(attr.getLoc(), diag::err_attribute_argument_type) | |||
6896 | << attr << AANT_ArgumentString; | |||
6897 | attr.setInvalid(); | |||
6898 | return true; | |||
6899 | } | |||
6900 | Qualifiers::GC GCAttr; | |||
6901 | if (attr.getNumArgs() > 1) { | |||
6902 | S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr | |||
6903 | << 1; | |||
6904 | attr.setInvalid(); | |||
6905 | return true; | |||
6906 | } | |||
6907 | ||||
6908 | IdentifierInfo *II = attr.getArgAsIdent(0)->Ident; | |||
6909 | if (II->isStr("weak")) | |||
6910 | GCAttr = Qualifiers::Weak; | |||
6911 | else if (II->isStr("strong")) | |||
6912 | GCAttr = Qualifiers::Strong; | |||
6913 | else { | |||
6914 | S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) | |||
6915 | << attr << II; | |||
6916 | attr.setInvalid(); | |||
6917 | return true; | |||
6918 | } | |||
6919 | ||||
6920 | QualType origType = type; | |||
6921 | type = S.Context.getObjCGCQualType(origType, GCAttr); | |||
6922 | ||||
6923 | // Make an attributed type to preserve the source information. | |||
6924 | if (attr.getLoc().isValid()) | |||
6925 | type = state.getAttributedType( | |||
6926 | ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type); | |||
6927 | ||||
6928 | return true; | |||
6929 | } | |||
6930 | ||||
6931 | namespace { | |||
6932 | /// A helper class to unwrap a type down to a function for the | |||
6933 | /// purposes of applying attributes there. | |||
6934 | /// | |||
6935 | /// Use: | |||
6936 | /// FunctionTypeUnwrapper unwrapped(SemaRef, T); | |||
6937 | /// if (unwrapped.isFunctionType()) { | |||
6938 | /// const FunctionType *fn = unwrapped.get(); | |||
6939 | /// // change fn somehow | |||
6940 | /// T = unwrapped.wrap(fn); | |||
6941 | /// } | |||
6942 | struct FunctionTypeUnwrapper { | |||
6943 | enum WrapKind { | |||
6944 | Desugar, | |||
6945 | Attributed, | |||
6946 | Parens, | |||
6947 | Array, | |||
6948 | Pointer, | |||
6949 | BlockPointer, | |||
6950 | Reference, | |||
6951 | MemberPointer, | |||
6952 | MacroQualified, | |||
6953 | }; | |||
6954 | ||||
6955 | QualType Original; | |||
6956 | const FunctionType *Fn; | |||
6957 | SmallVector<unsigned char /*WrapKind*/, 8> Stack; | |||
6958 | ||||
6959 | FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { | |||
6960 | while (true) { | |||
6961 | const Type *Ty = T.getTypePtr(); | |||
6962 | if (isa<FunctionType>(Ty)) { | |||
6963 | Fn = cast<FunctionType>(Ty); | |||
6964 | return; | |||
6965 | } else if (isa<ParenType>(Ty)) { | |||
6966 | T = cast<ParenType>(Ty)->getInnerType(); | |||
6967 | Stack.push_back(Parens); | |||
6968 | } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) || | |||
6969 | isa<IncompleteArrayType>(Ty)) { | |||
6970 | T = cast<ArrayType>(Ty)->getElementType(); | |||
6971 | Stack.push_back(Array); | |||
6972 | } else if (isa<PointerType>(Ty)) { | |||
6973 | T = cast<PointerType>(Ty)->getPointeeType(); | |||
6974 | Stack.push_back(Pointer); | |||
6975 | } else if (isa<BlockPointerType>(Ty)) { | |||
6976 | T = cast<BlockPointerType>(Ty)->getPointeeType(); | |||
6977 | Stack.push_back(BlockPointer); | |||
6978 | } else if (isa<MemberPointerType>(Ty)) { | |||
6979 | T = cast<MemberPointerType>(Ty)->getPointeeType(); | |||
6980 | Stack.push_back(MemberPointer); | |||
6981 | } else if (isa<ReferenceType>(Ty)) { | |||
6982 | T = cast<ReferenceType>(Ty)->getPointeeType(); | |||
6983 | Stack.push_back(Reference); | |||
6984 | } else if (isa<AttributedType>(Ty)) { | |||
6985 | T = cast<AttributedType>(Ty)->getEquivalentType(); | |||
6986 | Stack.push_back(Attributed); | |||
6987 | } else if (isa<MacroQualifiedType>(Ty)) { | |||
6988 | T = cast<MacroQualifiedType>(Ty)->getUnderlyingType(); | |||
6989 | Stack.push_back(MacroQualified); | |||
6990 | } else { | |||
6991 | const Type *DTy = Ty->getUnqualifiedDesugaredType(); | |||
6992 | if (Ty == DTy) { | |||
6993 | Fn = nullptr; | |||
6994 | return; | |||
6995 | } | |||
6996 | ||||
6997 | T = QualType(DTy, 0); | |||
6998 | Stack.push_back(Desugar); | |||
6999 | } | |||
7000 | } | |||
7001 | } | |||
7002 | ||||
7003 | bool isFunctionType() const { return (Fn != nullptr); } | |||
7004 | const FunctionType *get() const { return Fn; } | |||
7005 | ||||
7006 | QualType wrap(Sema &S, const FunctionType *New) { | |||
7007 | // If T wasn't modified from the unwrapped type, do nothing. | |||
7008 | if (New == get()) return Original; | |||
7009 | ||||
7010 | Fn = New; | |||
7011 | return wrap(S.Context, Original, 0); | |||
7012 | } | |||
7013 | ||||
7014 | private: | |||
7015 | QualType wrap(ASTContext &C, QualType Old, unsigned I) { | |||
7016 | if (I == Stack.size()) | |||
7017 | return C.getQualifiedType(Fn, Old.getQualifiers()); | |||
7018 | ||||
7019 | // Build up the inner type, applying the qualifiers from the old | |||
7020 | // type to the new type. | |||
7021 | SplitQualType SplitOld = Old.split(); | |||
7022 | ||||
7023 | // As a special case, tail-recurse if there are no qualifiers. | |||
7024 | if (SplitOld.Quals.empty()) | |||
7025 | return wrap(C, SplitOld.Ty, I); | |||
7026 | return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals); | |||
7027 | } | |||
7028 | ||||
7029 | QualType wrap(ASTContext &C, const Type *Old, unsigned I) { | |||
7030 | if (I == Stack.size()) return QualType(Fn, 0); | |||
7031 | ||||
7032 | switch (static_cast<WrapKind>(Stack[I++])) { | |||
7033 | case Desugar: | |||
7034 | // This is the point at which we potentially lose source | |||
7035 | // information. | |||
7036 | return wrap(C, Old->getUnqualifiedDesugaredType(), I); | |||
7037 | ||||
7038 | case Attributed: | |||
7039 | return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I); | |||
7040 | ||||
7041 | case Parens: { | |||
7042 | QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I); | |||
7043 | return C.getParenType(New); | |||
7044 | } | |||
7045 | ||||
7046 | case MacroQualified: | |||
7047 | return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I); | |||
7048 | ||||
7049 | case Array: { | |||
7050 | if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) { | |||
7051 | QualType New = wrap(C, CAT->getElementType(), I); | |||
7052 | return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(), | |||
7053 | CAT->getSizeModifier(), | |||
7054 | CAT->getIndexTypeCVRQualifiers()); | |||
7055 | } | |||
7056 | ||||
7057 | if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) { | |||
7058 | QualType New = wrap(C, VAT->getElementType(), I); | |||
7059 | return C.getVariableArrayType( | |||
7060 | New, VAT->getSizeExpr(), VAT->getSizeModifier(), | |||
7061 | VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange()); | |||
7062 | } | |||
7063 | ||||
7064 | const auto *IAT = cast<IncompleteArrayType>(Old); | |||
7065 | QualType New = wrap(C, IAT->getElementType(), I); | |||
7066 | return C.getIncompleteArrayType(New, IAT->getSizeModifier(), | |||
7067 | IAT->getIndexTypeCVRQualifiers()); | |||
7068 | } | |||
7069 | ||||
7070 | case Pointer: { | |||
7071 | QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I); | |||
7072 | return C.getPointerType(New); | |||
7073 | } | |||
7074 | ||||
7075 | case BlockPointer: { | |||
7076 | QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I); | |||
7077 | return C.getBlockPointerType(New); | |||
7078 | } | |||
7079 | ||||
7080 | case MemberPointer: { | |||
7081 | const MemberPointerType *OldMPT = cast<MemberPointerType>(Old); | |||
7082 | QualType New = wrap(C, OldMPT->getPointeeType(), I); | |||
7083 | return C.getMemberPointerType(New, OldMPT->getClass()); | |||
7084 | } | |||
7085 | ||||
7086 | case Reference: { | |||
7087 | const ReferenceType *OldRef = cast<ReferenceType>(Old); | |||
7088 | QualType New = wrap(C, OldRef->getPointeeType(), I); | |||
7089 | if (isa<LValueReferenceType>(OldRef)) | |||
7090 | return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue()); | |||
7091 | else | |||
7092 | return C.getRValueReferenceType(New); | |||
7093 | } | |||
7094 | } | |||
7095 | ||||
7096 | llvm_unreachable("unknown wrapping kind")::llvm::llvm_unreachable_internal("unknown wrapping kind", "clang/lib/Sema/SemaType.cpp" , 7096); | |||
7097 | } | |||
7098 | }; | |||
7099 | } // end anonymous namespace | |||
7100 | ||||
7101 | static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, | |||
7102 | ParsedAttr &PAttr, QualType &Type) { | |||
7103 | Sema &S = State.getSema(); | |||
7104 | ||||
7105 | Attr *A; | |||
7106 | switch (PAttr.getKind()) { | |||
7107 | default: llvm_unreachable("Unknown attribute kind")::llvm::llvm_unreachable_internal("Unknown attribute kind", "clang/lib/Sema/SemaType.cpp" , 7107); | |||
7108 | case ParsedAttr::AT_Ptr32: | |||
7109 | A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr); | |||
7110 | break; | |||
7111 | case ParsedAttr::AT_Ptr64: | |||
7112 | A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr); | |||
7113 | break; | |||
7114 | case ParsedAttr::AT_SPtr: | |||
7115 | A = createSimpleAttr<SPtrAttr>(S.Context, PAttr); | |||
7116 | break; | |||
7117 | case ParsedAttr::AT_UPtr: | |||
7118 | A = createSimpleAttr<UPtrAttr>(S.Context, PAttr); | |||
7119 | break; | |||
7120 | } | |||
7121 | ||||
7122 | std::bitset<attr::LastAttr> Attrs; | |||
7123 | attr::Kind NewAttrKind = A->getKind(); | |||
7124 | QualType Desugared = Type; | |||
7125 | const AttributedType *AT = dyn_cast<AttributedType>(Type); | |||
7126 | while (AT) { | |||
7127 | Attrs[AT->getAttrKind()] = true; | |||
7128 | Desugared = AT->getModifiedType(); | |||
7129 | AT = dyn_cast<AttributedType>(Desugared); | |||
7130 | } | |||
7131 | ||||
7132 | // You cannot specify duplicate type attributes, so if the attribute has | |||
7133 | // already been applied, flag it. | |||
7134 | if (Attrs[NewAttrKind]) { | |||
7135 | S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr; | |||
7136 | return true; | |||
7137 | } | |||
7138 | Attrs[NewAttrKind] = true; | |||
7139 | ||||
7140 | // You cannot have both __sptr and __uptr on the same type, nor can you | |||
7141 | // have __ptr32 and __ptr64. | |||
7142 | if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) { | |||
7143 | S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) | |||
7144 | << "'__ptr32'" | |||
7145 | << "'__ptr64'"; | |||
7146 | return true; | |||
7147 | } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) { | |||
7148 | S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) | |||
7149 | << "'__sptr'" | |||
7150 | << "'__uptr'"; | |||
7151 | return true; | |||
7152 | } | |||
7153 | ||||
7154 | // Pointer type qualifiers can only operate on pointer types, but not | |||
7155 | // pointer-to-member types. | |||
7156 | // | |||
7157 | // FIXME: Should we really be disallowing this attribute if there is any | |||
7158 | // type sugar between it and the pointer (other than attributes)? Eg, this | |||
7159 | // disallows the attribute on a parenthesized pointer. | |||
7160 | // And if so, should we really allow *any* type attribute? | |||
7161 | if (!isa<PointerType>(Desugared)) { | |||
7162 | if (Type->isMemberPointerType()) | |||
7163 | S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr; | |||
7164 | else | |||
7165 | S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0; | |||
7166 | return true; | |||
7167 | } | |||
7168 | ||||
7169 | // Add address space to type based on its attributes. | |||
7170 | LangAS ASIdx = LangAS::Default; | |||
7171 | uint64_t PtrWidth = S.Context.getTargetInfo().getPointerWidth(0); | |||
7172 | if (PtrWidth == 32) { | |||
7173 | if (Attrs[attr::Ptr64]) | |||
7174 | ASIdx = LangAS::ptr64; | |||
7175 | else if (Attrs[attr::UPtr]) | |||
7176 | ASIdx = LangAS::ptr32_uptr; | |||
7177 | } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) { | |||
7178 | if (Attrs[attr::UPtr]) | |||
7179 | ASIdx = LangAS::ptr32_uptr; | |||
7180 | else | |||
7181 | ASIdx = LangAS::ptr32_sptr; | |||
7182 | } | |||
7183 | ||||
7184 | QualType Pointee = Type->getPointeeType(); | |||
7185 | if (ASIdx != LangAS::Default) | |||
7186 | Pointee = S.Context.getAddrSpaceQualType( | |||
7187 | S.Context.removeAddrSpaceQualType(Pointee), ASIdx); | |||
7188 | Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee)); | |||
7189 | return false; | |||
7190 | } | |||
7191 | ||||
7192 | /// Map a nullability attribute kind to a nullability kind. | |||
7193 | static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) { | |||
7194 | switch (kind) { | |||
7195 | case ParsedAttr::AT_TypeNonNull: | |||
7196 | return NullabilityKind::NonNull; | |||
7197 | ||||
7198 | case ParsedAttr::AT_TypeNullable: | |||
7199 | return NullabilityKind::Nullable; | |||
7200 | ||||
7201 | case ParsedAttr::AT_TypeNullableResult: | |||
7202 | return NullabilityKind::NullableResult; | |||
7203 | ||||
7204 | case ParsedAttr::AT_TypeNullUnspecified: | |||
7205 | return NullabilityKind::Unspecified; | |||
7206 | ||||
7207 | default: | |||
7208 | llvm_unreachable("not a nullability attribute kind")::llvm::llvm_unreachable_internal("not a nullability attribute kind" , "clang/lib/Sema/SemaType.cpp", 7208); | |||
7209 | } | |||
7210 | } | |||
7211 | ||||
7212 | /// Applies a nullability type specifier to the given type, if possible. | |||
7213 | /// | |||
7214 | /// \param state The type processing state. | |||
7215 | /// | |||
7216 | /// \param type The type to which the nullability specifier will be | |||
7217 | /// added. On success, this type will be updated appropriately. | |||
7218 | /// | |||
7219 | /// \param attr The attribute as written on the type. | |||
7220 | /// | |||
7221 | /// \param allowOnArrayType Whether to accept nullability specifiers on an | |||
7222 | /// array type (e.g., because it will decay to a pointer). | |||
7223 | /// | |||
7224 | /// \returns true if a problem has been diagnosed, false on success. | |||
7225 | static bool checkNullabilityTypeSpecifier(TypeProcessingState &state, | |||
7226 | QualType &type, | |||
7227 | ParsedAttr &attr, | |||
7228 | bool allowOnArrayType) { | |||
7229 | Sema &S = state.getSema(); | |||
7230 | ||||
7231 | NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind()); | |||
7232 | SourceLocation nullabilityLoc = attr.getLoc(); | |||
7233 | bool isContextSensitive = attr.isContextSensitiveKeywordAttribute(); | |||
7234 | ||||
7235 | recordNullabilitySeen(S, nullabilityLoc); | |||
7236 | ||||
7237 | // Check for existing nullability attributes on the type. | |||
7238 | QualType desugared = type; | |||
7239 | while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) { | |||
7240 | // Check whether there is already a null | |||
7241 | if (auto existingNullability = attributed->getImmediateNullability()) { | |||
7242 | // Duplicated nullability. | |||
7243 | if (nullability == *existingNullability) { | |||
7244 | S.Diag(nullabilityLoc, diag::warn_nullability_duplicate) | |||
7245 | << DiagNullabilityKind(nullability, isContextSensitive) | |||
7246 | << FixItHint::CreateRemoval(nullabilityLoc); | |||
7247 | ||||
7248 | break; | |||
7249 | } | |||
7250 | ||||
7251 | // Conflicting nullability. | |||
7252 | S.Diag(nullabilityLoc, diag::err_nullability_conflicting) | |||
7253 | << DiagNullabilityKind(nullability, isContextSensitive) | |||
7254 | << DiagNullabilityKind(*existingNullability, false); | |||
7255 | return true; | |||
7256 | } | |||
7257 | ||||
7258 | desugared = attributed->getModifiedType(); | |||
7259 | } | |||
7260 | ||||
7261 | // If there is already a different nullability specifier, complain. | |||
7262 | // This (unlike the code above) looks through typedefs that might | |||
7263 | // have nullability specifiers on them, which means we cannot | |||
7264 | // provide a useful Fix-It. | |||
7265 | if (auto existingNullability = desugared->getNullability(S.Context)) { | |||
7266 | if (nullability != *existingNullability) { | |||
7267 | S.Diag(nullabilityLoc, diag::err_nullability_conflicting) | |||
7268 | << DiagNullabilityKind(nullability, isContextSensitive) | |||
7269 | << DiagNullabilityKind(*existingNullability, false); | |||
7270 | ||||
7271 | // Try to find the typedef with the existing nullability specifier. | |||
7272 | if (auto typedefType = desugared->getAs<TypedefType>()) { | |||
7273 | TypedefNameDecl *typedefDecl = typedefType->getDecl(); | |||
7274 | QualType underlyingType = typedefDecl->getUnderlyingType(); | |||
7275 | if (auto typedefNullability | |||
7276 | = AttributedType::stripOuterNullability(underlyingType)) { | |||
7277 | if (*typedefNullability == *existingNullability) { | |||
7278 | S.Diag(typedefDecl->getLocation(), diag::note_nullability_here) | |||
7279 | << DiagNullabilityKind(*existingNullability, false); | |||
7280 | } | |||
7281 | } | |||
7282 | } | |||
7283 | ||||
7284 | return true; | |||
7285 | } | |||
7286 | } | |||
7287 | ||||
7288 | // If this definitely isn't a pointer type, reject the specifier. | |||
7289 | if (!desugared->canHaveNullability() && | |||
7290 | !(allowOnArrayType && desugared->isArrayType())) { | |||
7291 | S.Diag(nullabilityLoc, diag::err_nullability_nonpointer) | |||
7292 | << DiagNullabilityKind(nullability, isContextSensitive) << type; | |||
7293 | return true; | |||
7294 | } | |||
7295 | ||||
7296 | // For the context-sensitive keywords/Objective-C property | |||
7297 | // attributes, require that the type be a single-level pointer. | |||
7298 | if (isContextSensitive) { | |||
7299 | // Make sure that the pointee isn't itself a pointer type. | |||
7300 | const Type *pointeeType = nullptr; | |||
7301 | if (desugared->isArrayType()) | |||
7302 | pointeeType = desugared->getArrayElementTypeNoTypeQual(); | |||
7303 | else if (desugared->isAnyPointerType()) | |||
7304 | pointeeType = desugared->getPointeeType().getTypePtr(); | |||
7305 | ||||
7306 | if (pointeeType && (pointeeType->isAnyPointerType() || | |||
7307 | pointeeType->isObjCObjectPointerType() || | |||
7308 | pointeeType->isMemberPointerType())) { | |||
7309 | S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel) | |||
7310 | << DiagNullabilityKind(nullability, true) | |||
7311 | << type; | |||
7312 | S.Diag(nullabilityLoc, diag::note_nullability_type_specifier) | |||
7313 | << DiagNullabilityKind(nullability, false) | |||
7314 | << type | |||
7315 | << FixItHint::CreateReplacement(nullabilityLoc, | |||
7316 | getNullabilitySpelling(nullability)); | |||
7317 | return true; | |||
7318 | } | |||
7319 | } | |||
7320 | ||||
7321 | // Form the attributed type. | |||
7322 | type = state.getAttributedType( | |||
7323 | createNullabilityAttr(S.Context, attr, nullability), type, type); | |||
7324 | return false; | |||
7325 | } | |||
7326 | ||||
7327 | /// Check the application of the Objective-C '__kindof' qualifier to | |||
7328 | /// the given type. | |||
7329 | static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, | |||
7330 | ParsedAttr &attr) { | |||
7331 | Sema &S = state.getSema(); | |||
7332 | ||||
7333 | if (isa<ObjCTypeParamType>(type)) { | |||
7334 | // Build the attributed type to record where __kindof occurred. | |||
7335 | type = state.getAttributedType( | |||
7336 | createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type); | |||
7337 | return false; | |||
7338 | } | |||
7339 | ||||
7340 | // Find out if it's an Objective-C object or object pointer type; | |||
7341 | const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); | |||
7342 | const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() | |||
7343 | : type->getAs<ObjCObjectType>(); | |||
7344 | ||||
7345 | // If not, we can't apply __kindof. | |||
7346 | if (!objType) { | |||
7347 | // FIXME: Handle dependent types that aren't yet object types. | |||
7348 | S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject) | |||
7349 | << type; | |||
7350 | return true; | |||
7351 | } | |||
7352 | ||||
7353 | // Rebuild the "equivalent" type, which pushes __kindof down into | |||
7354 | // the object type. | |||
7355 | // There is no need to apply kindof on an unqualified id type. | |||
7356 | QualType equivType = S.Context.getObjCObjectType( | |||
7357 | objType->getBaseType(), objType->getTypeArgsAsWritten(), | |||
7358 | objType->getProtocols(), | |||
7359 | /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); | |||
7360 | ||||
7361 | // If we started with an object pointer type, rebuild it. | |||
7362 | if (ptrType) { | |||
7363 | equivType = S.Context.getObjCObjectPointerType(equivType); | |||
7364 | if (auto nullability = type->getNullability(S.Context)) { | |||
7365 | // We create a nullability attribute from the __kindof attribute. | |||
7366 | // Make sure that will make sense. | |||
7367 | assert(attr.getAttributeSpellingListIndex() == 0 &&(static_cast <bool> (attr.getAttributeSpellingListIndex () == 0 && "multiple spellings for __kindof?") ? void (0) : __assert_fail ("attr.getAttributeSpellingListIndex() == 0 && \"multiple spellings for __kindof?\"" , "clang/lib/Sema/SemaType.cpp", 7368, __extension__ __PRETTY_FUNCTION__ )) | |||
7368 | "multiple spellings for __kindof?")(static_cast <bool> (attr.getAttributeSpellingListIndex () == 0 && "multiple spellings for __kindof?") ? void (0) : __assert_fail ("attr.getAttributeSpellingListIndex() == 0 && \"multiple spellings for __kindof?\"" , "clang/lib/Sema/SemaType.cpp", 7368, __extension__ __PRETTY_FUNCTION__ )); | |||
7369 | Attr *A = createNullabilityAttr(S.Context, attr, *nullability); | |||
7370 | A->setImplicit(true); | |||
7371 | equivType = state.getAttributedType(A, equivType, equivType); | |||
7372 | } | |||
7373 | } | |||
7374 | ||||
7375 | // Build the attributed type to record where __kindof occurred. | |||
7376 | type = state.getAttributedType( | |||
7377 | createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType); | |||
7378 | return false; | |||
7379 | } | |||
7380 | ||||
7381 | /// Distribute a nullability type attribute that cannot be applied to | |||
7382 | /// the type specifier to a pointer, block pointer, or member pointer | |||
7383 | /// declarator, complaining if necessary. | |||
7384 | /// | |||
7385 | /// \returns true if the nullability annotation was distributed, false | |||
7386 | /// otherwise. | |||
7387 | static bool distributeNullabilityTypeAttr(TypeProcessingState &state, | |||
7388 | QualType type, ParsedAttr &attr) { | |||
7389 | Declarator &declarator = state.getDeclarator(); | |||
7390 | ||||
7391 | /// Attempt to move the attribute to the specified chunk. | |||
7392 | auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { | |||
7393 | // If there is already a nullability attribute there, don't add | |||
7394 | // one. | |||
7395 | if (hasNullabilityAttr(chunk.getAttrs())) | |||
7396 | return false; | |||
7397 | ||||
7398 | // Complain about the nullability qualifier being in the wrong | |||
7399 | // place. | |||
7400 | enum { | |||
7401 | PK_Pointer, | |||
7402 | PK_BlockPointer, | |||
7403 | PK_MemberPointer, | |||
7404 | PK_FunctionPointer, | |||
7405 | PK_MemberFunctionPointer, | |||
7406 | } pointerKind | |||
7407 | = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer | |||
7408 | : PK_Pointer) | |||
7409 | : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer | |||
7410 | : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; | |||
7411 | ||||
7412 | auto diag = state.getSema().Diag(attr.getLoc(), | |||
7413 | diag::warn_nullability_declspec) | |||
7414 | << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), | |||
7415 | attr.isContextSensitiveKeywordAttribute()) | |||
7416 | << type | |||
7417 | << static_cast<unsigned>(pointerKind); | |||
7418 | ||||
7419 | // FIXME: MemberPointer chunks don't carry the location of the *. | |||
7420 | if (chunk.Kind != DeclaratorChunk::MemberPointer) { | |||
7421 | diag << FixItHint::CreateRemoval(attr.getLoc()) | |||
7422 | << FixItHint::CreateInsertion( | |||
7423 | state.getSema().getPreprocessor().getLocForEndOfToken( | |||
7424 | chunk.Loc), | |||
7425 | " " + attr.getAttrName()->getName().str() + " "); | |||
7426 | } | |||
7427 | ||||
7428 | moveAttrFromListToList(attr, state.getCurrentAttributes(), | |||
7429 | chunk.getAttrs()); | |||
7430 | return true; | |||
7431 | }; | |||
7432 | ||||
7433 | // Move it to the outermost pointer, member pointer, or block | |||
7434 | // pointer declarator. | |||
7435 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { | |||
7436 | DeclaratorChunk &chunk = declarator.getTypeObject(i-1); | |||
7437 | switch (chunk.Kind) { | |||
7438 | case DeclaratorChunk::Pointer: | |||
7439 | case DeclaratorChunk::BlockPointer: | |||
7440 | case DeclaratorChunk::MemberPointer: | |||
7441 | return moveToChunk(chunk, false); | |||
7442 | ||||
7443 | case DeclaratorChunk::Paren: | |||
7444 | case DeclaratorChunk::Array: | |||
7445 | continue; | |||
7446 | ||||
7447 | case DeclaratorChunk::Function: | |||
7448 | // Try to move past the return type to a function/block/member | |||
7449 | // function pointer. | |||
7450 | if (DeclaratorChunk *dest = maybeMovePastReturnType( | |||
7451 | declarator, i, | |||
7452 | /*onlyBlockPointers=*/false)) { | |||
7453 | return moveToChunk(*dest, true); | |||
7454 | } | |||
7455 | ||||
7456 | return false; | |||
7457 | ||||
7458 | // Don't walk through these. | |||
7459 | case DeclaratorChunk::Reference: | |||
7460 | case DeclaratorChunk::Pipe: | |||
7461 | return false; | |||
7462 | } | |||
7463 | } | |||
7464 | ||||
7465 | return false; | |||
7466 | } | |||
7467 | ||||
7468 | static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { | |||
7469 | assert(!Attr.isInvalid())(static_cast <bool> (!Attr.isInvalid()) ? void (0) : __assert_fail ("!Attr.isInvalid()", "clang/lib/Sema/SemaType.cpp", 7469, __extension__ __PRETTY_FUNCTION__)); | |||
7470 | switch (Attr.getKind()) { | |||
7471 | default: | |||
7472 | llvm_unreachable("not a calling convention attribute")::llvm::llvm_unreachable_internal("not a calling convention attribute" , "clang/lib/Sema/SemaType.cpp", 7472); | |||
7473 | case ParsedAttr::AT_CDecl: | |||
7474 | return createSimpleAttr<CDeclAttr>(Ctx, Attr); | |||
7475 | case ParsedAttr::AT_FastCall: | |||
7476 | return createSimpleAttr<FastCallAttr>(Ctx, Attr); | |||
7477 | case ParsedAttr::AT_StdCall: | |||
7478 | return createSimpleAttr<StdCallAttr>(Ctx, Attr); | |||
7479 | case ParsedAttr::AT_ThisCall: | |||
7480 | return createSimpleAttr<ThisCallAttr>(Ctx, Attr); | |||
7481 | case ParsedAttr::AT_RegCall: | |||
7482 | return createSimpleAttr<RegCallAttr>(Ctx, Attr); | |||
7483 | case ParsedAttr::AT_Pascal: | |||
7484 | return createSimpleAttr<PascalAttr>(Ctx, Attr); | |||
7485 | case ParsedAttr::AT_SwiftCall: | |||
7486 | return createSimpleAttr<SwiftCallAttr>(Ctx, Attr); | |||
7487 | case ParsedAttr::AT_SwiftAsyncCall: | |||
7488 | return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr); | |||
7489 | case ParsedAttr::AT_VectorCall: | |||
7490 | return createSimpleAttr<VectorCallAttr>(Ctx, Attr); | |||
7491 | case ParsedAttr::AT_AArch64VectorPcs: | |||
7492 | return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr); | |||
7493 | case ParsedAttr::AT_Pcs: { | |||
7494 | // The attribute may have had a fixit applied where we treated an | |||
7495 | // identifier as a string literal. The contents of the string are valid, | |||
7496 | // but the form may not be. | |||
7497 | StringRef Str; | |||
7498 | if (Attr.isArgExpr(0)) | |||
7499 | Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString(); | |||
7500 | else | |||
7501 | Str = Attr.getArgAsIdent(0)->Ident->getName(); | |||
7502 | PcsAttr::PCSType Type; | |||
7503 | if (!PcsAttr::ConvertStrToPCSType(Str, Type)) | |||
7504 | llvm_unreachable("already validated the attribute")::llvm::llvm_unreachable_internal("already validated the attribute" , "clang/lib/Sema/SemaType.cpp", 7504); | |||
7505 | return ::new (Ctx) PcsAttr(Ctx, Attr, Type); | |||
7506 | } | |||
7507 | case ParsedAttr::AT_IntelOclBicc: | |||
7508 | return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr); | |||
7509 | case ParsedAttr::AT_MSABI: | |||
7510 | return createSimpleAttr<MSABIAttr>(Ctx, Attr); | |||
7511 | case ParsedAttr::AT_SysVABI: | |||
7512 | return createSimpleAttr<SysVABIAttr>(Ctx, Attr); | |||
7513 | case ParsedAttr::AT_PreserveMost: | |||
7514 | return createSimpleAttr<PreserveMostAttr>(Ctx, Attr); | |||
7515 | case ParsedAttr::AT_PreserveAll: | |||
7516 | return createSimpleAttr<PreserveAllAttr>(Ctx, Attr); | |||
7517 | } | |||
7518 | llvm_unreachable("unexpected attribute kind!")::llvm::llvm_unreachable_internal("unexpected attribute kind!" , "clang/lib/Sema/SemaType.cpp", 7518); | |||
7519 | } | |||
7520 | ||||
7521 | /// Process an individual function attribute. Returns true to | |||
7522 | /// indicate that the attribute was handled, false if it wasn't. | |||
7523 | static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, | |||
7524 | QualType &type) { | |||
7525 | Sema &S = state.getSema(); | |||
7526 | ||||
7527 | FunctionTypeUnwrapper unwrapped(S, type); | |||
7528 | ||||
7529 | if (attr.getKind() == ParsedAttr::AT_NoReturn) { | |||
7530 | if (S.CheckAttrNoArgs(attr)) | |||
7531 | return true; | |||
7532 | ||||
7533 | // Delay if this is not a function type. | |||
7534 | if (!unwrapped.isFunctionType()) | |||
7535 | return false; | |||
7536 | ||||
7537 | // Otherwise we can process right away. | |||
7538 | FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true); | |||
7539 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7540 | return true; | |||
7541 | } | |||
7542 | ||||
7543 | if (attr.getKind() == ParsedAttr::AT_CmseNSCall) { | |||
7544 | // Delay if this is not a function type. | |||
7545 | if (!unwrapped.isFunctionType()) | |||
7546 | return false; | |||
7547 | ||||
7548 | // Ignore if we don't have CMSE enabled. | |||
7549 | if (!S.getLangOpts().Cmse) { | |||
7550 | S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr; | |||
7551 | attr.setInvalid(); | |||
7552 | return true; | |||
7553 | } | |||
7554 | ||||
7555 | // Otherwise we can process right away. | |||
7556 | FunctionType::ExtInfo EI = | |||
7557 | unwrapped.get()->getExtInfo().withCmseNSCall(true); | |||
7558 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7559 | return true; | |||
7560 | } | |||
7561 | ||||
7562 | // ns_returns_retained is not always a type attribute, but if we got | |||
7563 | // here, we're treating it as one right now. | |||
7564 | if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) { | |||
7565 | if (attr.getNumArgs()) return true; | |||
7566 | ||||
7567 | // Delay if this is not a function type. | |||
7568 | if (!unwrapped.isFunctionType()) | |||
7569 | return false; | |||
7570 | ||||
7571 | // Check whether the return type is reasonable. | |||
7572 | if (S.checkNSReturnsRetainedReturnType(attr.getLoc(), | |||
7573 | unwrapped.get()->getReturnType())) | |||
7574 | return true; | |||
7575 | ||||
7576 | // Only actually change the underlying type in ARC builds. | |||
7577 | QualType origType = type; | |||
7578 | if (state.getSema().getLangOpts().ObjCAutoRefCount) { | |||
7579 | FunctionType::ExtInfo EI | |||
7580 | = unwrapped.get()->getExtInfo().withProducesResult(true); | |||
7581 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7582 | } | |||
7583 | type = state.getAttributedType( | |||
7584 | createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr), | |||
7585 | origType, type); | |||
7586 | return true; | |||
7587 | } | |||
7588 | ||||
7589 | if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) { | |||
7590 | if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) | |||
7591 | return true; | |||
7592 | ||||
7593 | // Delay if this is not a function type. | |||
7594 | if (!unwrapped.isFunctionType()) | |||
7595 | return false; | |||
7596 | ||||
7597 | FunctionType::ExtInfo EI = | |||
7598 | unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true); | |||
7599 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7600 | return true; | |||
7601 | } | |||
7602 | ||||
7603 | if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) { | |||
7604 | if (!S.getLangOpts().CFProtectionBranch) { | |||
7605 | S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored); | |||
7606 | attr.setInvalid(); | |||
7607 | return true; | |||
7608 | } | |||
7609 | ||||
7610 | if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr)) | |||
7611 | return true; | |||
7612 | ||||
7613 | // If this is not a function type, warning will be asserted by subject | |||
7614 | // check. | |||
7615 | if (!unwrapped.isFunctionType()) | |||
7616 | return true; | |||
7617 | ||||
7618 | FunctionType::ExtInfo EI = | |||
7619 | unwrapped.get()->getExtInfo().withNoCfCheck(true); | |||
7620 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7621 | return true; | |||
7622 | } | |||
7623 | ||||
7624 | if (attr.getKind() == ParsedAttr::AT_Regparm) { | |||
7625 | unsigned value; | |||
7626 | if (S.CheckRegparmAttr(attr, value)) | |||
7627 | return true; | |||
7628 | ||||
7629 | // Delay if this is not a function type. | |||
7630 | if (!unwrapped.isFunctionType()) | |||
7631 | return false; | |||
7632 | ||||
7633 | // Diagnose regparm with fastcall. | |||
7634 | const FunctionType *fn = unwrapped.get(); | |||
7635 | CallingConv CC = fn->getCallConv(); | |||
7636 | if (CC == CC_X86FastCall) { | |||
7637 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | |||
7638 | << FunctionType::getNameForCallConv(CC) | |||
7639 | << "regparm"; | |||
7640 | attr.setInvalid(); | |||
7641 | return true; | |||
7642 | } | |||
7643 | ||||
7644 | FunctionType::ExtInfo EI = | |||
7645 | unwrapped.get()->getExtInfo().withRegParm(value); | |||
7646 | type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7647 | return true; | |||
7648 | } | |||
7649 | ||||
7650 | if (attr.getKind() == ParsedAttr::AT_NoThrow) { | |||
7651 | // Delay if this is not a function type. | |||
7652 | if (!unwrapped.isFunctionType()) | |||
7653 | return false; | |||
7654 | ||||
7655 | if (S.CheckAttrNoArgs(attr)) { | |||
7656 | attr.setInvalid(); | |||
7657 | return true; | |||
7658 | } | |||
7659 | ||||
7660 | // Otherwise we can process right away. | |||
7661 | auto *Proto = unwrapped.get()->castAs<FunctionProtoType>(); | |||
7662 | ||||
7663 | // MSVC ignores nothrow if it is in conflict with an explicit exception | |||
7664 | // specification. | |||
7665 | if (Proto->hasExceptionSpec()) { | |||
7666 | switch (Proto->getExceptionSpecType()) { | |||
7667 | case EST_None: | |||
7668 | llvm_unreachable("This doesn't have an exception spec!")::llvm::llvm_unreachable_internal("This doesn't have an exception spec!" , "clang/lib/Sema/SemaType.cpp", 7668); | |||
7669 | ||||
7670 | case EST_DynamicNone: | |||
7671 | case EST_BasicNoexcept: | |||
7672 | case EST_NoexceptTrue: | |||
7673 | case EST_NoThrow: | |||
7674 | // Exception spec doesn't conflict with nothrow, so don't warn. | |||
7675 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
7676 | case EST_Unparsed: | |||
7677 | case EST_Uninstantiated: | |||
7678 | case EST_DependentNoexcept: | |||
7679 | case EST_Unevaluated: | |||
7680 | // We don't have enough information to properly determine if there is a | |||
7681 | // conflict, so suppress the warning. | |||
7682 | break; | |||
7683 | case EST_Dynamic: | |||
7684 | case EST_MSAny: | |||
7685 | case EST_NoexceptFalse: | |||
7686 | S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored); | |||
7687 | break; | |||
7688 | } | |||
7689 | return true; | |||
7690 | } | |||
7691 | ||||
7692 | type = unwrapped.wrap( | |||
7693 | S, S.Context | |||
7694 | .getFunctionTypeWithExceptionSpec( | |||
7695 | QualType{Proto, 0}, | |||
7696 | FunctionProtoType::ExceptionSpecInfo{EST_NoThrow}) | |||
7697 | ->getAs<FunctionType>()); | |||
7698 | return true; | |||
7699 | } | |||
7700 | ||||
7701 | // Delay if the type didn't work out to a function. | |||
7702 | if (!unwrapped.isFunctionType()) return false; | |||
7703 | ||||
7704 | // Otherwise, a calling convention. | |||
7705 | CallingConv CC; | |||
7706 | if (S.CheckCallingConvAttr(attr, CC)) | |||
7707 | return true; | |||
7708 | ||||
7709 | const FunctionType *fn = unwrapped.get(); | |||
7710 | CallingConv CCOld = fn->getCallConv(); | |||
7711 | Attr *CCAttr = getCCTypeAttr(S.Context, attr); | |||
7712 | ||||
7713 | if (CCOld != CC) { | |||
7714 | // Error out on when there's already an attribute on the type | |||
7715 | // and the CCs don't match. | |||
7716 | if (S.getCallingConvAttributedType(type)) { | |||
7717 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | |||
7718 | << FunctionType::getNameForCallConv(CC) | |||
7719 | << FunctionType::getNameForCallConv(CCOld); | |||
7720 | attr.setInvalid(); | |||
7721 | return true; | |||
7722 | } | |||
7723 | } | |||
7724 | ||||
7725 | // Diagnose use of variadic functions with calling conventions that | |||
7726 | // don't support them (e.g. because they're callee-cleanup). | |||
7727 | // We delay warning about this on unprototyped function declarations | |||
7728 | // until after redeclaration checking, just in case we pick up a | |||
7729 | // prototype that way. And apparently we also "delay" warning about | |||
7730 | // unprototyped function types in general, despite not necessarily having | |||
7731 | // much ability to diagnose it later. | |||
7732 | if (!supportsVariadicCall(CC)) { | |||
7733 | const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn); | |||
7734 | if (FnP && FnP->isVariadic()) { | |||
7735 | // stdcall and fastcall are ignored with a warning for GCC and MS | |||
7736 | // compatibility. | |||
7737 | if (CC == CC_X86StdCall || CC == CC_X86FastCall) | |||
7738 | return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported) | |||
7739 | << FunctionType::getNameForCallConv(CC) | |||
7740 | << (int)Sema::CallingConventionIgnoredReason::VariadicFunction; | |||
7741 | ||||
7742 | attr.setInvalid(); | |||
7743 | return S.Diag(attr.getLoc(), diag::err_cconv_varargs) | |||
7744 | << FunctionType::getNameForCallConv(CC); | |||
7745 | } | |||
7746 | } | |||
7747 | ||||
7748 | // Also diagnose fastcall with regparm. | |||
7749 | if (CC == CC_X86FastCall && fn->getHasRegParm()) { | |||
7750 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) | |||
7751 | << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall); | |||
7752 | attr.setInvalid(); | |||
7753 | return true; | |||
7754 | } | |||
7755 | ||||
7756 | // Modify the CC from the wrapped function type, wrap it all back, and then | |||
7757 | // wrap the whole thing in an AttributedType as written. The modified type | |||
7758 | // might have a different CC if we ignored the attribute. | |||
7759 | QualType Equivalent; | |||
7760 | if (CCOld == CC) { | |||
7761 | Equivalent = type; | |||
7762 | } else { | |||
7763 | auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC); | |||
7764 | Equivalent = | |||
7765 | unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI)); | |||
7766 | } | |||
7767 | type = state.getAttributedType(CCAttr, type, Equivalent); | |||
7768 | return true; | |||
7769 | } | |||
7770 | ||||
7771 | bool Sema::hasExplicitCallingConv(QualType T) { | |||
7772 | const AttributedType *AT; | |||
7773 | ||||
7774 | // Stop if we'd be stripping off a typedef sugar node to reach the | |||
7775 | // AttributedType. | |||
7776 | while ((AT = T->getAs<AttributedType>()) && | |||
7777 | AT->getAs<TypedefType>() == T->getAs<TypedefType>()) { | |||
7778 | if (AT->isCallingConv()) | |||
7779 | return true; | |||
7780 | T = AT->getModifiedType(); | |||
7781 | } | |||
7782 | return false; | |||
7783 | } | |||
7784 | ||||
7785 | void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, | |||
7786 | SourceLocation Loc) { | |||
7787 | FunctionTypeUnwrapper Unwrapped(*this, T); | |||
7788 | const FunctionType *FT = Unwrapped.get(); | |||
7789 | bool IsVariadic = (isa<FunctionProtoType>(FT) && | |||
7790 | cast<FunctionProtoType>(FT)->isVariadic()); | |||
7791 | CallingConv CurCC = FT->getCallConv(); | |||
7792 | CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic); | |||
7793 | ||||
7794 | if (CurCC == ToCC) | |||
7795 | return; | |||
7796 | ||||
7797 | // MS compiler ignores explicit calling convention attributes on structors. We | |||
7798 | // should do the same. | |||
7799 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { | |||
7800 | // Issue a warning on ignored calling convention -- except of __stdcall. | |||
7801 | // Again, this is what MS compiler does. | |||
7802 | if (CurCC != CC_X86StdCall) | |||
7803 | Diag(Loc, diag::warn_cconv_unsupported) | |||
7804 | << FunctionType::getNameForCallConv(CurCC) | |||
7805 | << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor; | |||
7806 | // Default adjustment. | |||
7807 | } else { | |||
7808 | // Only adjust types with the default convention. For example, on Windows | |||
7809 | // we should adjust a __cdecl type to __thiscall for instance methods, and a | |||
7810 | // __thiscall type to __cdecl for static methods. | |||
7811 | CallingConv DefaultCC = | |||
7812 | Context.getDefaultCallingConvention(IsVariadic, IsStatic); | |||
7813 | ||||
7814 | if (CurCC != DefaultCC || DefaultCC == ToCC) | |||
7815 | return; | |||
7816 | ||||
7817 | if (hasExplicitCallingConv(T)) | |||
7818 | return; | |||
7819 | } | |||
7820 | ||||
7821 | FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC)); | |||
7822 | QualType Wrapped = Unwrapped.wrap(*this, FT); | |||
7823 | T = Context.getAdjustedType(T, Wrapped); | |||
7824 | } | |||
7825 | ||||
7826 | /// HandleVectorSizeAttribute - this attribute is only applicable to integral | |||
7827 | /// and float scalars, although arrays, pointers, and function return values are | |||
7828 | /// allowed in conjunction with this construct. Aggregates with this attribute | |||
7829 | /// are invalid, even if they are of the same size as a corresponding scalar. | |||
7830 | /// The raw attribute should contain precisely 1 argument, the vector size for | |||
7831 | /// the variable, measured in bytes. If curType and rawAttr are well formed, | |||
7832 | /// this routine will return a new vector type. | |||
7833 | static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, | |||
7834 | Sema &S) { | |||
7835 | // Check the attribute arguments. | |||
7836 | if (Attr.getNumArgs() != 1) { | |||
7837 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | |||
7838 | << 1; | |||
7839 | Attr.setInvalid(); | |||
7840 | return; | |||
7841 | } | |||
7842 | ||||
7843 | Expr *SizeExpr = Attr.getArgAsExpr(0); | |||
7844 | QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc()); | |||
7845 | if (!T.isNull()) | |||
7846 | CurType = T; | |||
7847 | else | |||
7848 | Attr.setInvalid(); | |||
7849 | } | |||
7850 | ||||
7851 | /// Process the OpenCL-like ext_vector_type attribute when it occurs on | |||
7852 | /// a type. | |||
7853 | static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, | |||
7854 | Sema &S) { | |||
7855 | // check the attribute arguments. | |||
7856 | if (Attr.getNumArgs() != 1) { | |||
7857 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | |||
7858 | << 1; | |||
7859 | return; | |||
7860 | } | |||
7861 | ||||
7862 | Expr *SizeExpr = Attr.getArgAsExpr(0); | |||
7863 | QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc()); | |||
7864 | if (!T.isNull()) | |||
7865 | CurType = T; | |||
7866 | } | |||
7867 | ||||
7868 | static bool isPermittedNeonBaseType(QualType &Ty, | |||
7869 | VectorType::VectorKind VecKind, Sema &S) { | |||
7870 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); | |||
7871 | if (!BTy) | |||
7872 | return false; | |||
7873 | ||||
7874 | llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); | |||
7875 | ||||
7876 | // Signed poly is mathematically wrong, but has been baked into some ABIs by | |||
7877 | // now. | |||
7878 | bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || | |||
7879 | Triple.getArch() == llvm::Triple::aarch64_32 || | |||
7880 | Triple.getArch() == llvm::Triple::aarch64_be; | |||
7881 | if (VecKind == VectorType::NeonPolyVector) { | |||
7882 | if (IsPolyUnsigned) { | |||
7883 | // AArch64 polynomial vectors are unsigned. | |||
7884 | return BTy->getKind() == BuiltinType::UChar || | |||
7885 | BTy->getKind() == BuiltinType::UShort || | |||
7886 | BTy->getKind() == BuiltinType::ULong || | |||
7887 | BTy->getKind() == BuiltinType::ULongLong; | |||
7888 | } else { | |||
7889 | // AArch32 polynomial vectors are signed. | |||
7890 | return BTy->getKind() == BuiltinType::SChar || | |||
7891 | BTy->getKind() == BuiltinType::Short || | |||
7892 | BTy->getKind() == BuiltinType::LongLong; | |||
7893 | } | |||
7894 | } | |||
7895 | ||||
7896 | // Non-polynomial vector types: the usual suspects are allowed, as well as | |||
7897 | // float64_t on AArch64. | |||
7898 | if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) && | |||
7899 | BTy->getKind() == BuiltinType::Double) | |||
7900 | return true; | |||
7901 | ||||
7902 | return BTy->getKind() == BuiltinType::SChar || | |||
7903 | BTy->getKind() == BuiltinType::UChar || | |||
7904 | BTy->getKind() == BuiltinType::Short || | |||
7905 | BTy->getKind() == BuiltinType::UShort || | |||
7906 | BTy->getKind() == BuiltinType::Int || | |||
7907 | BTy->getKind() == BuiltinType::UInt || | |||
7908 | BTy->getKind() == BuiltinType::Long || | |||
7909 | BTy->getKind() == BuiltinType::ULong || | |||
7910 | BTy->getKind() == BuiltinType::LongLong || | |||
7911 | BTy->getKind() == BuiltinType::ULongLong || | |||
7912 | BTy->getKind() == BuiltinType::Float || | |||
7913 | BTy->getKind() == BuiltinType::Half || | |||
7914 | BTy->getKind() == BuiltinType::BFloat16; | |||
7915 | } | |||
7916 | ||||
7917 | static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr, | |||
7918 | llvm::APSInt &Result) { | |||
7919 | const auto *AttrExpr = Attr.getArgAsExpr(0); | |||
7920 | if (!AttrExpr->isTypeDependent()) { | |||
7921 | if (Optional<llvm::APSInt> Res = | |||
7922 | AttrExpr->getIntegerConstantExpr(S.Context)) { | |||
7923 | Result = *Res; | |||
7924 | return true; | |||
7925 | } | |||
7926 | } | |||
7927 | S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) | |||
7928 | << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange(); | |||
7929 | Attr.setInvalid(); | |||
7930 | return false; | |||
7931 | } | |||
7932 | ||||
7933 | /// HandleNeonVectorTypeAttr - The "neon_vector_type" and | |||
7934 | /// "neon_polyvector_type" attributes are used to create vector types that | |||
7935 | /// are mangled according to ARM's ABI. Otherwise, these types are identical | |||
7936 | /// to those created with the "vector_size" attribute. Unlike "vector_size" | |||
7937 | /// the argument to these Neon attributes is the number of vector elements, | |||
7938 | /// not the vector size in bytes. The vector width and element type must | |||
7939 | /// match one of the standard Neon vector types. | |||
7940 | static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, | |||
7941 | Sema &S, VectorType::VectorKind VecKind) { | |||
7942 | // Target must have NEON (or MVE, whose vectors are similar enough | |||
7943 | // not to need a separate attribute) | |||
7944 | if (!S.Context.getTargetInfo().hasFeature("neon") && | |||
7945 | !S.Context.getTargetInfo().hasFeature("mve")) { | |||
7946 | S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) | |||
7947 | << Attr << "'neon' or 'mve'"; | |||
7948 | Attr.setInvalid(); | |||
7949 | return; | |||
7950 | } | |||
7951 | // Check the attribute arguments. | |||
7952 | if (Attr.getNumArgs() != 1) { | |||
7953 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr | |||
7954 | << 1; | |||
7955 | Attr.setInvalid(); | |||
7956 | return; | |||
7957 | } | |||
7958 | // The number of elements must be an ICE. | |||
7959 | llvm::APSInt numEltsInt(32); | |||
7960 | if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt)) | |||
7961 | return; | |||
7962 | ||||
7963 | // Only certain element types are supported for Neon vectors. | |||
7964 | if (!isPermittedNeonBaseType(CurType, VecKind, S)) { | |||
7965 | S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; | |||
7966 | Attr.setInvalid(); | |||
7967 | return; | |||
7968 | } | |||
7969 | ||||
7970 | // The total size of the vector must be 64 or 128 bits. | |||
7971 | unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); | |||
7972 | unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); | |||
7973 | unsigned vecSize = typeSize * numElts; | |||
7974 | if (vecSize != 64 && vecSize != 128) { | |||
7975 | S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; | |||
7976 | Attr.setInvalid(); | |||
7977 | return; | |||
7978 | } | |||
7979 | ||||
7980 | CurType = S.Context.getVectorType(CurType, numElts, VecKind); | |||
7981 | } | |||
7982 | ||||
7983 | /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is | |||
7984 | /// used to create fixed-length versions of sizeless SVE types defined by | |||
7985 | /// the ACLE, such as svint32_t and svbool_t. | |||
7986 | static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, | |||
7987 | Sema &S) { | |||
7988 | // Target must have SVE. | |||
7989 | if (!S.Context.getTargetInfo().hasFeature("sve")) { | |||
7990 | S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'"; | |||
7991 | Attr.setInvalid(); | |||
7992 | return; | |||
7993 | } | |||
7994 | ||||
7995 | // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or | |||
7996 | // if <bits>+ syntax is used. | |||
7997 | if (!S.getLangOpts().VScaleMin || | |||
7998 | S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) { | |||
7999 | S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported) | |||
8000 | << Attr; | |||
8001 | Attr.setInvalid(); | |||
8002 | return; | |||
8003 | } | |||
8004 | ||||
8005 | // Check the attribute arguments. | |||
8006 | if (Attr.getNumArgs() != 1) { | |||
8007 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) | |||
8008 | << Attr << 1; | |||
8009 | Attr.setInvalid(); | |||
8010 | return; | |||
8011 | } | |||
8012 | ||||
8013 | // The vector size must be an integer constant expression. | |||
8014 | llvm::APSInt SveVectorSizeInBits(32); | |||
8015 | if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits)) | |||
8016 | return; | |||
8017 | ||||
8018 | unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue()); | |||
8019 | ||||
8020 | // The attribute vector size must match -msve-vector-bits. | |||
8021 | if (VecSize != S.getLangOpts().VScaleMin * 128) { | |||
8022 | S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size) | |||
8023 | << VecSize << S.getLangOpts().VScaleMin * 128; | |||
8024 | Attr.setInvalid(); | |||
8025 | return; | |||
8026 | } | |||
8027 | ||||
8028 | // Attribute can only be attached to a single SVE vector or predicate type. | |||
8029 | if (!CurType->isVLSTBuiltinType()) { | |||
8030 | S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type) | |||
8031 | << Attr << CurType; | |||
8032 | Attr.setInvalid(); | |||
8033 | return; | |||
8034 | } | |||
8035 | ||||
8036 | const auto *BT = CurType->castAs<BuiltinType>(); | |||
8037 | ||||
8038 | QualType EltType = CurType->getSveEltType(S.Context); | |||
8039 | unsigned TypeSize = S.Context.getTypeSize(EltType); | |||
8040 | VectorType::VectorKind VecKind = VectorType::SveFixedLengthDataVector; | |||
8041 | if (BT->getKind() == BuiltinType::SveBool) { | |||
8042 | // Predicates are represented as i8. | |||
8043 | VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth(); | |||
8044 | VecKind = VectorType::SveFixedLengthPredicateVector; | |||
8045 | } else | |||
8046 | VecSize /= TypeSize; | |||
8047 | CurType = S.Context.getVectorType(EltType, VecSize, VecKind); | |||
8048 | } | |||
8049 | ||||
8050 | static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State, | |||
8051 | QualType &CurType, | |||
8052 | ParsedAttr &Attr) { | |||
8053 | const VectorType *VT = dyn_cast<VectorType>(CurType); | |||
8054 | if (!VT || VT->getVectorKind() != VectorType::NeonVector) { | |||
8055 | State.getSema().Diag(Attr.getLoc(), | |||
8056 | diag::err_attribute_arm_mve_polymorphism); | |||
8057 | Attr.setInvalid(); | |||
8058 | return; | |||
8059 | } | |||
8060 | ||||
8061 | CurType = | |||
8062 | State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>( | |||
8063 | State.getSema().Context, Attr), | |||
8064 | CurType, CurType); | |||
8065 | } | |||
8066 | ||||
8067 | /// Handle OpenCL Access Qualifier Attribute. | |||
8068 | static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, | |||
8069 | Sema &S) { | |||
8070 | // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. | |||
8071 | if (!(CurType->isImageType() || CurType->isPipeType())) { | |||
8072 | S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); | |||
8073 | Attr.setInvalid(); | |||
8074 | return; | |||
8075 | } | |||
8076 | ||||
8077 | if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { | |||
8078 | QualType BaseTy = TypedefTy->desugar(); | |||
8079 | ||||
8080 | std::string PrevAccessQual; | |||
8081 | if (BaseTy->isPipeType()) { | |||
8082 | if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) { | |||
8083 | OpenCLAccessAttr *Attr = | |||
8084 | TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>(); | |||
8085 | PrevAccessQual = Attr->getSpelling(); | |||
8086 | } else { | |||
8087 | PrevAccessQual = "read_only"; | |||
8088 | } | |||
8089 | } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) { | |||
8090 | ||||
8091 | switch (ImgType->getKind()) { | |||
8092 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ | |||
8093 | case BuiltinType::Id: \ | |||
8094 | PrevAccessQual = #Access; \ | |||
8095 | break; | |||
8096 | #include "clang/Basic/OpenCLImageTypes.def" | |||
8097 | default: | |||
8098 | llvm_unreachable("Unable to find corresponding image type.")::llvm::llvm_unreachable_internal("Unable to find corresponding image type." , "clang/lib/Sema/SemaType.cpp", 8098); | |||
8099 | } | |||
8100 | } else { | |||
8101 | llvm_unreachable("unexpected type")::llvm::llvm_unreachable_internal("unexpected type", "clang/lib/Sema/SemaType.cpp" , 8101); | |||
8102 | } | |||
8103 | StringRef AttrName = Attr.getAttrName()->getName(); | |||
8104 | if (PrevAccessQual == AttrName.ltrim("_")) { | |||
8105 | // Duplicated qualifiers | |||
8106 | S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec) | |||
8107 | << AttrName << Attr.getRange(); | |||
8108 | } else { | |||
8109 | // Contradicting qualifiers | |||
8110 | S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); | |||
8111 | } | |||
8112 | ||||
8113 | S.Diag(TypedefTy->getDecl()->getBeginLoc(), | |||
8114 | diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; | |||
8115 | } else if (CurType->isPipeType()) { | |||
8116 | if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { | |||
8117 | QualType ElemType = CurType->castAs<PipeType>()->getElementType(); | |||
8118 | CurType = S.Context.getWritePipeType(ElemType); | |||
8119 | } | |||
8120 | } | |||
8121 | } | |||
8122 | ||||
8123 | /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type | |||
8124 | static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr, | |||
8125 | Sema &S) { | |||
8126 | if (!S.getLangOpts().MatrixTypes) { | |||
8127 | S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled); | |||
8128 | return; | |||
8129 | } | |||
8130 | ||||
8131 | if (Attr.getNumArgs() != 2) { | |||
8132 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) | |||
8133 | << Attr << 2; | |||
8134 | return; | |||
8135 | } | |||
8136 | ||||
8137 | Expr *RowsExpr = Attr.getArgAsExpr(0); | |||
8138 | Expr *ColsExpr = Attr.getArgAsExpr(1); | |||
8139 | QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc()); | |||
8140 | if (!T.isNull()) | |||
8141 | CurType = T; | |||
8142 | } | |||
8143 | ||||
8144 | static void HandleLifetimeBoundAttr(TypeProcessingState &State, | |||
8145 | QualType &CurType, | |||
8146 | ParsedAttr &Attr) { | |||
8147 | if (State.getDeclarator().isDeclarationOfFunction()) { | |||
8148 | CurType = State.getAttributedType( | |||
8149 | createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr), | |||
8150 | CurType, CurType); | |||
8151 | } | |||
8152 | } | |||
8153 | ||||
8154 | static bool isAddressSpaceKind(const ParsedAttr &attr) { | |||
8155 | auto attrKind = attr.getKind(); | |||
8156 | ||||
8157 | return attrKind == ParsedAttr::AT_AddressSpace || | |||
8158 | attrKind == ParsedAttr::AT_OpenCLPrivateAddressSpace || | |||
8159 | attrKind == ParsedAttr::AT_OpenCLGlobalAddressSpace || | |||
8160 | attrKind == ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace || | |||
8161 | attrKind == ParsedAttr::AT_OpenCLGlobalHostAddressSpace || | |||
8162 | attrKind == ParsedAttr::AT_OpenCLLocalAddressSpace || | |||
8163 | attrKind == ParsedAttr::AT_OpenCLConstantAddressSpace || | |||
8164 | attrKind == ParsedAttr::AT_OpenCLGenericAddressSpace; | |||
8165 | } | |||
8166 | ||||
8167 | static void processTypeAttrs(TypeProcessingState &state, QualType &type, | |||
8168 | TypeAttrLocation TAL, | |||
8169 | const ParsedAttributesView &attrs) { | |||
8170 | ||||
8171 | state.setParsedNoDeref(false); | |||
8172 | if (attrs.empty()) | |||
8173 | return; | |||
8174 | ||||
8175 | // Scan through and apply attributes to this type where it makes sense. Some | |||
8176 | // attributes (such as __address_space__, __vector_size__, etc) apply to the | |||
8177 | // type, but others can be present in the type specifiers even though they | |||
8178 | // apply to the decl. Here we apply type attributes and ignore the rest. | |||
8179 | ||||
8180 | // This loop modifies the list pretty frequently, but we still need to make | |||
8181 | // sure we visit every element once. Copy the attributes list, and iterate | |||
8182 | // over that. | |||
8183 | ParsedAttributesView AttrsCopy{attrs}; | |||
8184 | for (ParsedAttr &attr : AttrsCopy) { | |||
8185 | ||||
8186 | // Skip attributes that were marked to be invalid. | |||
8187 | if (attr.isInvalid()) | |||
8188 | continue; | |||
8189 | ||||
8190 | if (attr.isStandardAttributeSyntax()) { | |||
8191 | // [[gnu::...]] attributes are treated as declaration attributes, so may | |||
8192 | // not appertain to a DeclaratorChunk. If we handle them as type | |||
8193 | // attributes, accept them in that position and diagnose the GCC | |||
8194 | // incompatibility. | |||
8195 | if (attr.isGNUScope()) { | |||
8196 | bool IsTypeAttr = attr.isTypeAttr(); | |||
8197 | if (TAL == TAL_DeclChunk) { | |||
8198 | state.getSema().Diag(attr.getLoc(), | |||
8199 | IsTypeAttr | |||
8200 | ? diag::warn_gcc_ignores_type_attr | |||
8201 | : diag::warn_cxx11_gnu_attribute_on_type) | |||
8202 | << attr; | |||
8203 | if (!IsTypeAttr) | |||
8204 | continue; | |||
8205 | } | |||
8206 | } else if (TAL != TAL_DeclChunk && !isAddressSpaceKind(attr)) { | |||
8207 | // Otherwise, only consider type processing for a C++11 attribute if | |||
8208 | // it's actually been applied to a type. | |||
8209 | // We also allow C++11 address_space and | |||
8210 | // OpenCL language address space attributes to pass through. | |||
8211 | continue; | |||
8212 | } | |||
8213 | } | |||
8214 | ||||
8215 | // If this is an attribute we can handle, do so now, | |||
8216 | // otherwise, add it to the FnAttrs list for rechaining. | |||
8217 | switch (attr.getKind()) { | |||
8218 | default: | |||
8219 | // A [[]] attribute on a declarator chunk must appertain to a type. | |||
8220 | if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) { | |||
8221 | state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) | |||
8222 | << attr; | |||
8223 | attr.setUsedAsTypeAttr(); | |||
8224 | } | |||
8225 | break; | |||
8226 | ||||
8227 | case ParsedAttr::UnknownAttribute: | |||
8228 | if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) | |||
8229 | state.getSema().Diag(attr.getLoc(), | |||
8230 | diag::warn_unknown_attribute_ignored) | |||
8231 | << attr << attr.getRange(); | |||
8232 | break; | |||
8233 | ||||
8234 | case ParsedAttr::IgnoredAttribute: | |||
8235 | break; | |||
8236 | ||||
8237 | case ParsedAttr::AT_BTFTypeTag: | |||
8238 | HandleBTFTypeTagAttribute(type, attr, state); | |||
8239 | attr.setUsedAsTypeAttr(); | |||
8240 | break; | |||
8241 | ||||
8242 | case ParsedAttr::AT_MayAlias: | |||
8243 | // FIXME: This attribute needs to actually be handled, but if we ignore | |||
8244 | // it it breaks large amounts of Linux software. | |||
8245 | attr.setUsedAsTypeAttr(); | |||
8246 | break; | |||
8247 | case ParsedAttr::AT_OpenCLPrivateAddressSpace: | |||
8248 | case ParsedAttr::AT_OpenCLGlobalAddressSpace: | |||
8249 | case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace: | |||
8250 | case ParsedAttr::AT_OpenCLGlobalHostAddressSpace: | |||
8251 | case ParsedAttr::AT_OpenCLLocalAddressSpace: | |||
8252 | case ParsedAttr::AT_OpenCLConstantAddressSpace: | |||
8253 | case ParsedAttr::AT_OpenCLGenericAddressSpace: | |||
8254 | case ParsedAttr::AT_AddressSpace: | |||
8255 | HandleAddressSpaceTypeAttribute(type, attr, state); | |||
8256 | attr.setUsedAsTypeAttr(); | |||
8257 | break; | |||
8258 | OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership: | |||
8259 | if (!handleObjCPointerTypeAttr(state, attr, type)) | |||
8260 | distributeObjCPointerTypeAttr(state, attr, type); | |||
8261 | attr.setUsedAsTypeAttr(); | |||
8262 | break; | |||
8263 | case ParsedAttr::AT_VectorSize: | |||
8264 | HandleVectorSizeAttr(type, attr, state.getSema()); | |||
8265 | attr.setUsedAsTypeAttr(); | |||
8266 | break; | |||
8267 | case ParsedAttr::AT_ExtVectorType: | |||
8268 | HandleExtVectorTypeAttr(type, attr, state.getSema()); | |||
8269 | attr.setUsedAsTypeAttr(); | |||
8270 | break; | |||
8271 | case ParsedAttr::AT_NeonVectorType: | |||
8272 | HandleNeonVectorTypeAttr(type, attr, state.getSema(), | |||
8273 | VectorType::NeonVector); | |||
8274 | attr.setUsedAsTypeAttr(); | |||
8275 | break; | |||
8276 | case ParsedAttr::AT_NeonPolyVectorType: | |||
8277 | HandleNeonVectorTypeAttr(type, attr, state.getSema(), | |||
8278 | VectorType::NeonPolyVector); | |||
8279 | attr.setUsedAsTypeAttr(); | |||
8280 | break; | |||
8281 | case ParsedAttr::AT_ArmSveVectorBits: | |||
8282 | HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema()); | |||
8283 | attr.setUsedAsTypeAttr(); | |||
8284 | break; | |||
8285 | case ParsedAttr::AT_ArmMveStrictPolymorphism: { | |||
8286 | HandleArmMveStrictPolymorphismAttr(state, type, attr); | |||
8287 | attr.setUsedAsTypeAttr(); | |||
8288 | break; | |||
8289 | } | |||
8290 | case ParsedAttr::AT_OpenCLAccess: | |||
8291 | HandleOpenCLAccessAttr(type, attr, state.getSema()); | |||
8292 | attr.setUsedAsTypeAttr(); | |||
8293 | break; | |||
8294 | case ParsedAttr::AT_LifetimeBound: | |||
8295 | if (TAL == TAL_DeclChunk) | |||
8296 | HandleLifetimeBoundAttr(state, type, attr); | |||
8297 | break; | |||
8298 | ||||
8299 | case ParsedAttr::AT_NoDeref: { | |||
8300 | ASTContext &Ctx = state.getSema().Context; | |||
8301 | type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr), | |||
8302 | type, type); | |||
8303 | attr.setUsedAsTypeAttr(); | |||
8304 | state.setParsedNoDeref(true); | |||
8305 | break; | |||
8306 | } | |||
8307 | ||||
8308 | case ParsedAttr::AT_MatrixType: | |||
8309 | HandleMatrixTypeAttr(type, attr, state.getSema()); | |||
8310 | attr.setUsedAsTypeAttr(); | |||
8311 | break; | |||
8312 | ||||
8313 | MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr ::AT_SPtr: case ParsedAttr::AT_UPtr: | |||
8314 | if (!handleMSPointerTypeQualifierAttr(state, attr, type)) | |||
8315 | attr.setUsedAsTypeAttr(); | |||
8316 | break; | |||
8317 | ||||
8318 | ||||
8319 | NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable : case ParsedAttr::AT_TypeNullableResult: case ParsedAttr::AT_TypeNullUnspecified: | |||
8320 | // Either add nullability here or try to distribute it. We | |||
8321 | // don't want to distribute the nullability specifier past any | |||
8322 | // dependent type, because that complicates the user model. | |||
8323 | if (type->canHaveNullability() || type->isDependentType() || | |||
8324 | type->isArrayType() || | |||
8325 | !distributeNullabilityTypeAttr(state, type, attr)) { | |||
8326 | unsigned endIndex; | |||
8327 | if (TAL == TAL_DeclChunk) | |||
8328 | endIndex = state.getCurrentChunkIndex(); | |||
8329 | else | |||
8330 | endIndex = state.getDeclarator().getNumTypeObjects(); | |||
8331 | bool allowOnArrayType = | |||
8332 | state.getDeclarator().isPrototypeContext() && | |||
8333 | !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex); | |||
8334 | if (checkNullabilityTypeSpecifier( | |||
8335 | state, | |||
8336 | type, | |||
8337 | attr, | |||
8338 | allowOnArrayType)) { | |||
8339 | attr.setInvalid(); | |||
8340 | } | |||
8341 | ||||
8342 | attr.setUsedAsTypeAttr(); | |||
8343 | } | |||
8344 | break; | |||
8345 | ||||
8346 | case ParsedAttr::AT_ObjCKindOf: | |||
8347 | // '__kindof' must be part of the decl-specifiers. | |||
8348 | switch (TAL) { | |||
8349 | case TAL_DeclSpec: | |||
8350 | break; | |||
8351 | ||||
8352 | case TAL_DeclChunk: | |||
8353 | case TAL_DeclName: | |||
8354 | state.getSema().Diag(attr.getLoc(), | |||
8355 | diag::err_objc_kindof_wrong_position) | |||
8356 | << FixItHint::CreateRemoval(attr.getLoc()) | |||
8357 | << FixItHint::CreateInsertion( | |||
8358 | state.getDeclarator().getDeclSpec().getBeginLoc(), | |||
8359 | "__kindof "); | |||
8360 | break; | |||
8361 | } | |||
8362 | ||||
8363 | // Apply it regardless. | |||
8364 | if (checkObjCKindOfType(state, type, attr)) | |||
8365 | attr.setInvalid(); | |||
8366 | break; | |||
8367 | ||||
8368 | case ParsedAttr::AT_NoThrow: | |||
8369 | // Exception Specifications aren't generally supported in C mode throughout | |||
8370 | // clang, so revert to attribute-based handling for C. | |||
8371 | if (!state.getSema().getLangOpts().CPlusPlus) | |||
8372 | break; | |||
8373 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
8374 | FUNCTION_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NoReturn : case ParsedAttr::AT_Regparm: case ParsedAttr::AT_CmseNSCall : case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: case ParsedAttr ::AT_AnyX86NoCfCheck: case ParsedAttr::AT_CDecl: case ParsedAttr ::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr:: AT_ThisCall: case ParsedAttr::AT_RegCall: case ParsedAttr::AT_Pascal : case ParsedAttr::AT_SwiftCall: case ParsedAttr::AT_SwiftAsyncCall : case ParsedAttr::AT_VectorCall: case ParsedAttr::AT_AArch64VectorPcs : case ParsedAttr::AT_MSABI: case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr::AT_IntelOclBicc: case ParsedAttr ::AT_PreserveMost: case ParsedAttr::AT_PreserveAll: | |||
8375 | attr.setUsedAsTypeAttr(); | |||
8376 | ||||
8377 | // Never process function type attributes as part of the | |||
8378 | // declaration-specifiers. | |||
8379 | if (TAL == TAL_DeclSpec) | |||
8380 | distributeFunctionTypeAttrFromDeclSpec(state, attr, type); | |||
8381 | ||||
8382 | // Otherwise, handle the possible delays. | |||
8383 | else if (!handleFunctionTypeAttr(state, attr, type)) | |||
8384 | distributeFunctionTypeAttr(state, attr, type); | |||
8385 | break; | |||
8386 | case ParsedAttr::AT_AcquireHandle: { | |||
8387 | if (!type->isFunctionType()) | |||
8388 | return; | |||
8389 | ||||
8390 | if (attr.getNumArgs() != 1) { | |||
8391 | state.getSema().Diag(attr.getLoc(), | |||
8392 | diag::err_attribute_wrong_number_arguments) | |||
8393 | << attr << 1; | |||
8394 | attr.setInvalid(); | |||
8395 | return; | |||
8396 | } | |||
8397 | ||||
8398 | StringRef HandleType; | |||
8399 | if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType)) | |||
8400 | return; | |||
8401 | type = state.getAttributedType( | |||
8402 | AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr), | |||
8403 | type, type); | |||
8404 | attr.setUsedAsTypeAttr(); | |||
8405 | break; | |||
8406 | } | |||
8407 | } | |||
8408 | ||||
8409 | // Handle attributes that are defined in a macro. We do not want this to be | |||
8410 | // applied to ObjC builtin attributes. | |||
8411 | if (isa<AttributedType>(type) && attr.hasMacroIdentifier() && | |||
8412 | !type.getQualifiers().hasObjCLifetime() && | |||
8413 | !type.getQualifiers().hasObjCGCAttr() && | |||
8414 | attr.getKind() != ParsedAttr::AT_ObjCGC && | |||
8415 | attr.getKind() != ParsedAttr::AT_ObjCOwnership) { | |||
8416 | const IdentifierInfo *MacroII = attr.getMacroIdentifier(); | |||
8417 | type = state.getSema().Context.getMacroQualifiedType(type, MacroII); | |||
8418 | state.setExpansionLocForMacroQualifiedType( | |||
8419 | cast<MacroQualifiedType>(type.getTypePtr()), | |||
8420 | attr.getMacroExpansionLoc()); | |||
8421 | } | |||
8422 | } | |||
8423 | } | |||
8424 | ||||
8425 | void Sema::completeExprArrayBound(Expr *E) { | |||
8426 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { | |||
8427 | if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { | |||
8428 | if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) { | |||
8429 | auto *Def = Var->getDefinition(); | |||
8430 | if (!Def) { | |||
8431 | SourceLocation PointOfInstantiation = E->getExprLoc(); | |||
8432 | runWithSufficientStackSpace(PointOfInstantiation, [&] { | |||
8433 | InstantiateVariableDefinition(PointOfInstantiation, Var); | |||
8434 | }); | |||
8435 | Def = Var->getDefinition(); | |||
8436 | ||||
8437 | // If we don't already have a point of instantiation, and we managed | |||
8438 | // to instantiate a definition, this is the point of instantiation. | |||
8439 | // Otherwise, we don't request an end-of-TU instantiation, so this is | |||
8440 | // not a point of instantiation. | |||
8441 | // FIXME: Is this really the right behavior? | |||
8442 | if (Var->getPointOfInstantiation().isInvalid() && Def) { | |||
8443 | assert(Var->getTemplateSpecializationKind() ==(static_cast <bool> (Var->getTemplateSpecializationKind () == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? void (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "clang/lib/Sema/SemaType.cpp", 8445, __extension__ __PRETTY_FUNCTION__ )) | |||
8444 | TSK_ImplicitInstantiation &&(static_cast <bool> (Var->getTemplateSpecializationKind () == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? void (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "clang/lib/Sema/SemaType.cpp", 8445, __extension__ __PRETTY_FUNCTION__ )) | |||
8445 | "explicit instantiation with no point of instantiation")(static_cast <bool> (Var->getTemplateSpecializationKind () == TSK_ImplicitInstantiation && "explicit instantiation with no point of instantiation" ) ? void (0) : __assert_fail ("Var->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && \"explicit instantiation with no point of instantiation\"" , "clang/lib/Sema/SemaType.cpp", 8445, __extension__ __PRETTY_FUNCTION__ )); | |||
8446 | Var->setTemplateSpecializationKind( | |||
8447 | Var->getTemplateSpecializationKind(), PointOfInstantiation); | |||
8448 | } | |||
8449 | } | |||
8450 | ||||
8451 | // Update the type to the definition's type both here and within the | |||
8452 | // expression. | |||
8453 | if (Def) { | |||
8454 | DRE->setDecl(Def); | |||
8455 | QualType T = Def->getType(); | |||
8456 | DRE->setType(T); | |||
8457 | // FIXME: Update the type on all intervening expressions. | |||
8458 | E->setType(T); | |||
8459 | } | |||
8460 | ||||
8461 | // We still go on to try to complete the type independently, as it | |||
8462 | // may also require instantiations or diagnostics if it remains | |||
8463 | // incomplete. | |||
8464 | } | |||
8465 | } | |||
8466 | } | |||
8467 | } | |||
8468 | ||||
8469 | QualType Sema::getCompletedType(Expr *E) { | |||
8470 | // Incomplete array types may be completed by the initializer attached to | |||
8471 | // their definitions. For static data members of class templates and for | |||
8472 | // variable templates, we need to instantiate the definition to get this | |||
8473 | // initializer and complete the type. | |||
8474 | if (E->getType()->isIncompleteArrayType()) | |||
8475 | completeExprArrayBound(E); | |||
8476 | ||||
8477 | // FIXME: Are there other cases which require instantiating something other | |||
8478 | // than the type to complete the type of an expression? | |||
8479 | ||||
8480 | return E->getType(); | |||
8481 | } | |||
8482 | ||||
8483 | /// Ensure that the type of the given expression is complete. | |||
8484 | /// | |||
8485 | /// This routine checks whether the expression \p E has a complete type. If the | |||
8486 | /// expression refers to an instantiable construct, that instantiation is | |||
8487 | /// performed as needed to complete its type. Furthermore | |||
8488 | /// Sema::RequireCompleteType is called for the expression's type (or in the | |||
8489 | /// case of a reference type, the referred-to type). | |||
8490 | /// | |||
8491 | /// \param E The expression whose type is required to be complete. | |||
8492 | /// \param Kind Selects which completeness rules should be applied. | |||
8493 | /// \param Diagnoser The object that will emit a diagnostic if the type is | |||
8494 | /// incomplete. | |||
8495 | /// | |||
8496 | /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false | |||
8497 | /// otherwise. | |||
8498 | bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, | |||
8499 | TypeDiagnoser &Diagnoser) { | |||
8500 | return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind, | |||
8501 | Diagnoser); | |||
8502 | } | |||
8503 | ||||
8504 | bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { | |||
8505 | BoundTypeDiagnoser<> Diagnoser(DiagID); | |||
8506 | return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); | |||
8507 | } | |||
8508 | ||||
8509 | /// Ensure that the type T is a complete type. | |||
8510 | /// | |||
8511 | /// This routine checks whether the type @p T is complete in any | |||
8512 | /// context where a complete type is required. If @p T is a complete | |||
8513 | /// type, returns false. If @p T is a class template specialization, | |||
8514 | /// this routine then attempts to perform class template | |||
8515 | /// instantiation. If instantiation fails, or if @p T is incomplete | |||
8516 | /// and cannot be completed, issues the diagnostic @p diag (giving it | |||
8517 | /// the type @p T) and returns true. | |||
8518 | /// | |||
8519 | /// @param Loc The location in the source that the incomplete type | |||
8520 | /// diagnostic should refer to. | |||
8521 | /// | |||
8522 | /// @param T The type that this routine is examining for completeness. | |||
8523 | /// | |||
8524 | /// @param Kind Selects which completeness rules should be applied. | |||
8525 | /// | |||
8526 | /// @returns @c true if @p T is incomplete and a diagnostic was emitted, | |||
8527 | /// @c false otherwise. | |||
8528 | bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, | |||
8529 | CompleteTypeKind Kind, | |||
8530 | TypeDiagnoser &Diagnoser) { | |||
8531 | if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser)) | |||
8532 | return true; | |||
8533 | if (const TagType *Tag = T->getAs<TagType>()) { | |||
8534 | if (!Tag->getDecl()->isCompleteDefinitionRequired()) { | |||
8535 | Tag->getDecl()->setCompleteDefinitionRequired(); | |||
8536 | Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl()); | |||
8537 | } | |||
8538 | } | |||
8539 | return false; | |||
8540 | } | |||
8541 | ||||
8542 | bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { | |||
8543 | llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; | |||
8544 | if (!Suggested) | |||
8545 | return false; | |||
8546 | ||||
8547 | // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext | |||
8548 | // and isolate from other C++ specific checks. | |||
8549 | StructuralEquivalenceContext Ctx( | |||
8550 | D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, | |||
8551 | StructuralEquivalenceKind::Default, | |||
8552 | false /*StrictTypeSpelling*/, true /*Complain*/, | |||
8553 | true /*ErrorOnTagTypeMismatch*/); | |||
8554 | return Ctx.IsEquivalent(D, Suggested); | |||
8555 | } | |||
8556 | ||||
8557 | /// Determine whether there is any declaration of \p D that was ever a | |||
8558 | /// definition (perhaps before module merging) and is currently visible. | |||
8559 | /// \param D The definition of the entity. | |||
8560 | /// \param Suggested Filled in with the declaration that should be made visible | |||
8561 | /// in order to provide a definition of this entity. | |||
8562 | /// \param OnlyNeedComplete If \c true, we only need the type to be complete, | |||
8563 | /// not defined. This only matters for enums with a fixed underlying | |||
8564 | /// type, since in all other cases, a type is complete if and only if it | |||
8565 | /// is defined. | |||
8566 | bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, | |||
8567 | bool OnlyNeedComplete) { | |||
8568 | // Easy case: if we don't have modules, all declarations are visible. | |||
8569 | if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) | |||
8570 | return true; | |||
8571 | ||||
8572 | // If this definition was instantiated from a template, map back to the | |||
8573 | // pattern from which it was instantiated. | |||
8574 | if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) { | |||
8575 | // We're in the middle of defining it; this definition should be treated | |||
8576 | // as visible. | |||
8577 | return true; | |||
8578 | } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { | |||
8579 | if (auto *Pattern = RD->getTemplateInstantiationPattern()) | |||
8580 | RD = Pattern; | |||
8581 | D = RD->getDefinition(); | |||
8582 | } else if (auto *ED = dyn_cast<EnumDecl>(D)) { | |||
8583 | if (auto *Pattern = ED->getTemplateInstantiationPattern()) | |||
8584 | ED = Pattern; | |||
8585 | if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) { | |||
8586 | // If the enum has a fixed underlying type, it may have been forward | |||
8587 | // declared. In -fms-compatibility, `enum Foo;` will also forward declare | |||
8588 | // the enum and assign it the underlying type of `int`. Since we're only | |||
8589 | // looking for a complete type (not a definition), any visible declaration | |||
8590 | // of it will do. | |||
8591 | *Suggested = nullptr; | |||
8592 | for (auto *Redecl : ED->redecls()) { | |||
8593 | if (isVisible(Redecl)) | |||
8594 | return true; | |||
8595 | if (Redecl->isThisDeclarationADefinition() || | |||
8596 | (Redecl->isCanonicalDecl() && !*Suggested)) | |||
8597 | *Suggested = Redecl; | |||
8598 | } | |||
8599 | return false; | |||
8600 | } | |||
8601 | D = ED->getDefinition(); | |||
8602 | } else if (auto *FD = dyn_cast<FunctionDecl>(D)) { | |||
8603 | if (auto *Pattern = FD->getTemplateInstantiationPattern()) | |||
8604 | FD = Pattern; | |||
8605 | D = FD->getDefinition(); | |||
8606 | } else if (auto *VD = dyn_cast<VarDecl>(D)) { | |||
8607 | if (auto *Pattern = VD->getTemplateInstantiationPattern()) | |||
8608 | VD = Pattern; | |||
8609 | D = VD->getDefinition(); | |||
8610 | } | |||
8611 | assert(D && "missing definition for pattern of instantiated definition")(static_cast <bool> (D && "missing definition for pattern of instantiated definition" ) ? void (0) : __assert_fail ("D && \"missing definition for pattern of instantiated definition\"" , "clang/lib/Sema/SemaType.cpp", 8611, __extension__ __PRETTY_FUNCTION__ )); | |||
8612 | ||||
8613 | *Suggested = D; | |||
8614 | ||||
8615 | auto DefinitionIsVisible = [&] { | |||
8616 | // The (primary) definition might be in a visible module. | |||
8617 | if (isVisible(D)) | |||
8618 | return true; | |||
8619 | ||||
8620 | // A visible module might have a merged definition instead. | |||
8621 | if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D) | |||
8622 | : hasVisibleMergedDefinition(D)) { | |||
8623 | if (CodeSynthesisContexts.empty() && | |||
8624 | !getLangOpts().ModulesLocalVisibility) { | |||
8625 | // Cache the fact that this definition is implicitly visible because | |||
8626 | // there is a visible merged definition. | |||
8627 | D->setVisibleDespiteOwningModule(); | |||
8628 | } | |||
8629 | return true; | |||
8630 | } | |||
8631 | ||||
8632 | return false; | |||
8633 | }; | |||
8634 | ||||
8635 | if (DefinitionIsVisible()) | |||
8636 | return true; | |||
8637 | ||||
8638 | // The external source may have additional definitions of this entity that are | |||
8639 | // visible, so complete the redeclaration chain now and ask again. | |||
8640 | if (auto *Source = Context.getExternalSource()) { | |||
8641 | Source->CompleteRedeclChain(D); | |||
8642 | return DefinitionIsVisible(); | |||
8643 | } | |||
8644 | ||||
8645 | return false; | |||
8646 | } | |||
8647 | ||||
8648 | /// Locks in the inheritance model for the given class and all of its bases. | |||
8649 | static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { | |||
8650 | RD = RD->getMostRecentNonInjectedDecl(); | |||
8651 | if (!RD->hasAttr<MSInheritanceAttr>()) { | |||
8652 | MSInheritanceModel IM; | |||
8653 | bool BestCase = false; | |||
8654 | switch (S.MSPointerToMemberRepresentationMethod) { | |||
8655 | case LangOptions::PPTMK_BestCase: | |||
8656 | BestCase = true; | |||
8657 | IM = RD->calculateInheritanceModel(); | |||
8658 | break; | |||
8659 | case LangOptions::PPTMK_FullGeneralitySingleInheritance: | |||
8660 | IM = MSInheritanceModel::Single; | |||
8661 | break; | |||
8662 | case LangOptions::PPTMK_FullGeneralityMultipleInheritance: | |||
8663 | IM = MSInheritanceModel::Multiple; | |||
8664 | break; | |||
8665 | case LangOptions::PPTMK_FullGeneralityVirtualInheritance: | |||
8666 | IM = MSInheritanceModel::Unspecified; | |||
8667 | break; | |||
8668 | } | |||
8669 | ||||
8670 | SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid() | |||
8671 | ? S.ImplicitMSInheritanceAttrLoc | |||
8672 | : RD->getSourceRange(); | |||
8673 | RD->addAttr(MSInheritanceAttr::CreateImplicit( | |||
8674 | S.getASTContext(), BestCase, Loc, AttributeCommonInfo::AS_Microsoft, | |||
8675 | MSInheritanceAttr::Spelling(IM))); | |||
8676 | S.Consumer.AssignInheritanceModel(RD); | |||
8677 | } | |||
8678 | } | |||
8679 | ||||
8680 | /// The implementation of RequireCompleteType | |||
8681 | bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, | |||
8682 | CompleteTypeKind Kind, | |||
8683 | TypeDiagnoser *Diagnoser) { | |||
8684 | // FIXME: Add this assertion to make sure we always get instantiation points. | |||
8685 | // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); | |||
8686 | // FIXME: Add this assertion to help us flush out problems with | |||
8687 | // checking for dependent types and type-dependent expressions. | |||
8688 | // | |||
8689 | // assert(!T->isDependentType() && | |||
8690 | // "Can't ask whether a dependent type is complete"); | |||
8691 | ||||
8692 | if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { | |||
8693 | if (!MPTy->getClass()->isDependentType()) { | |||
8694 | if (getLangOpts().CompleteMemberPointers && | |||
8695 | !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() && | |||
8696 | RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind, | |||
8697 | diag::err_memptr_incomplete)) | |||
8698 | return true; | |||
8699 | ||||
8700 | // We lock in the inheritance model once somebody has asked us to ensure | |||
8701 | // that a pointer-to-member type is complete. | |||
8702 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
8703 | (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0)); | |||
8704 | assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl()); | |||
8705 | } | |||
8706 | } | |||
8707 | } | |||
8708 | ||||
8709 | NamedDecl *Def = nullptr; | |||
8710 | bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless); | |||
8711 | bool Incomplete = (T->isIncompleteType(&Def) || | |||
8712 | (!AcceptSizeless && T->isSizelessBuiltinType())); | |||
8713 | ||||
8714 | // Check that any necessary explicit specializations are visible. For an | |||
8715 | // enum, we just need the declaration, so don't check this. | |||
8716 | if (Def && !isa<EnumDecl>(Def)) | |||
8717 | checkSpecializationVisibility(Loc, Def); | |||
8718 | ||||
8719 | // If we have a complete type, we're done. | |||
8720 | if (!Incomplete) { | |||
8721 | // If we know about the definition but it is not visible, complain. | |||
8722 | NamedDecl *SuggestedDef = nullptr; | |||
8723 | if (Def && | |||
8724 | !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) { | |||
8725 | // If the user is going to see an error here, recover by making the | |||
8726 | // definition visible. | |||
8727 | bool TreatAsComplete = Diagnoser && !isSFINAEContext(); | |||
8728 | if (Diagnoser && SuggestedDef) | |||
8729 | diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition, | |||
8730 | /*Recover*/TreatAsComplete); | |||
8731 | return !TreatAsComplete; | |||
8732 | } else if (Def && !TemplateInstCallbacks.empty()) { | |||
8733 | CodeSynthesisContext TempInst; | |||
8734 | TempInst.Kind = CodeSynthesisContext::Memoization; | |||
8735 | TempInst.Template = Def; | |||
8736 | TempInst.Entity = Def; | |||
8737 | TempInst.PointOfInstantiation = Loc; | |||
8738 | atTemplateBegin(TemplateInstCallbacks, *this, TempInst); | |||
8739 | atTemplateEnd(TemplateInstCallbacks, *this, TempInst); | |||
8740 | } | |||
8741 | ||||
8742 | return false; | |||
8743 | } | |||
8744 | ||||
8745 | TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def); | |||
8746 | ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def); | |||
8747 | ||||
8748 | // Give the external source a chance to provide a definition of the type. | |||
8749 | // This is kept separate from completing the redeclaration chain so that | |||
8750 | // external sources such as LLDB can avoid synthesizing a type definition | |||
8751 | // unless it's actually needed. | |||
8752 | if (Tag || IFace) { | |||
8753 | // Avoid diagnosing invalid decls as incomplete. | |||
8754 | if (Def->isInvalidDecl()) | |||
8755 | return true; | |||
8756 | ||||
8757 | // Give the external AST source a chance to complete the type. | |||
8758 | if (auto *Source = Context.getExternalSource()) { | |||
8759 | if (Tag && Tag->hasExternalLexicalStorage()) | |||
8760 | Source->CompleteType(Tag); | |||
8761 | if (IFace && IFace->hasExternalLexicalStorage()) | |||
8762 | Source->CompleteType(IFace); | |||
8763 | // If the external source completed the type, go through the motions | |||
8764 | // again to ensure we're allowed to use the completed type. | |||
8765 | if (!T->isIncompleteType()) | |||
8766 | return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); | |||
8767 | } | |||
8768 | } | |||
8769 | ||||
8770 | // If we have a class template specialization or a class member of a | |||
8771 | // class template specialization, or an array with known size of such, | |||
8772 | // try to instantiate it. | |||
8773 | if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) { | |||
8774 | bool Instantiated = false; | |||
8775 | bool Diagnosed = false; | |||
8776 | if (RD->isDependentContext()) { | |||
8777 | // Don't try to instantiate a dependent class (eg, a member template of | |||
8778 | // an instantiated class template specialization). | |||
8779 | // FIXME: Can this ever happen? | |||
8780 | } else if (auto *ClassTemplateSpec = | |||
8781 | dyn_cast<ClassTemplateSpecializationDecl>(RD)) { | |||
8782 | if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { | |||
8783 | runWithSufficientStackSpace(Loc, [&] { | |||
8784 | Diagnosed = InstantiateClassTemplateSpecialization( | |||
8785 | Loc, ClassTemplateSpec, TSK_ImplicitInstantiation, | |||
8786 | /*Complain=*/Diagnoser); | |||
8787 | }); | |||
8788 | Instantiated = true; | |||
8789 | } | |||
8790 | } else { | |||
8791 | CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass(); | |||
8792 | if (!RD->isBeingDefined() && Pattern) { | |||
8793 | MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo(); | |||
8794 | assert(MSI && "Missing member specialization information?")(static_cast <bool> (MSI && "Missing member specialization information?" ) ? void (0) : __assert_fail ("MSI && \"Missing member specialization information?\"" , "clang/lib/Sema/SemaType.cpp", 8794, __extension__ __PRETTY_FUNCTION__ )); | |||
8795 | // This record was instantiated from a class within a template. | |||
8796 | if (MSI->getTemplateSpecializationKind() != | |||
8797 | TSK_ExplicitSpecialization) { | |||
8798 | runWithSufficientStackSpace(Loc, [&] { | |||
8799 | Diagnosed = InstantiateClass(Loc, RD, Pattern, | |||
8800 | getTemplateInstantiationArgs(RD), | |||
8801 | TSK_ImplicitInstantiation, | |||
8802 | /*Complain=*/Diagnoser); | |||
8803 | }); | |||
8804 | Instantiated = true; | |||
8805 | } | |||
8806 | } | |||
8807 | } | |||
8808 | ||||
8809 | if (Instantiated) { | |||
8810 | // Instantiate* might have already complained that the template is not | |||
8811 | // defined, if we asked it to. | |||
8812 | if (Diagnoser && Diagnosed) | |||
8813 | return true; | |||
8814 | // If we instantiated a definition, check that it's usable, even if | |||
8815 | // instantiation produced an error, so that repeated calls to this | |||
8816 | // function give consistent answers. | |||
8817 | if (!T->isIncompleteType()) | |||
8818 | return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); | |||
8819 | } | |||
8820 | } | |||
8821 | ||||
8822 | // FIXME: If we didn't instantiate a definition because of an explicit | |||
8823 | // specialization declaration, check that it's visible. | |||
8824 | ||||
8825 | if (!Diagnoser) | |||
8826 | return true; | |||
8827 | ||||
8828 | Diagnoser->diagnose(*this, Loc, T); | |||
8829 | ||||
8830 | // If the type was a forward declaration of a class/struct/union | |||
8831 | // type, produce a note. | |||
8832 | if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid()) | |||
8833 | Diag(Tag->getLocation(), | |||
8834 | Tag->isBeingDefined() ? diag::note_type_being_defined | |||
8835 | : diag::note_forward_declaration) | |||
8836 | << Context.getTagDeclType(Tag); | |||
8837 | ||||
8838 | // If the Objective-C class was a forward declaration, produce a note. | |||
8839 | if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid()) | |||
8840 | Diag(IFace->getLocation(), diag::note_forward_class); | |||
8841 | ||||
8842 | // If we have external information that we can use to suggest a fix, | |||
8843 | // produce a note. | |||
8844 | if (ExternalSource) | |||
8845 | ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); | |||
8846 | ||||
8847 | return true; | |||
8848 | } | |||
8849 | ||||
8850 | bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, | |||
8851 | CompleteTypeKind Kind, unsigned DiagID) { | |||
8852 | BoundTypeDiagnoser<> Diagnoser(DiagID); | |||
8853 | return RequireCompleteType(Loc, T, Kind, Diagnoser); | |||
8854 | } | |||
8855 | ||||
8856 | /// Get diagnostic %select index for tag kind for | |||
8857 | /// literal type diagnostic message. | |||
8858 | /// WARNING: Indexes apply to particular diagnostics only! | |||
8859 | /// | |||
8860 | /// \returns diagnostic %select index. | |||
8861 | static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { | |||
8862 | switch (Tag) { | |||
8863 | case TTK_Struct: return 0; | |||
8864 | case TTK_Interface: return 1; | |||
8865 | case TTK_Class: return 2; | |||
8866 | default: llvm_unreachable("Invalid tag kind for literal type diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for literal type diagnostic!" , "clang/lib/Sema/SemaType.cpp", 8866); | |||
8867 | } | |||
8868 | } | |||
8869 | ||||
8870 | /// Ensure that the type T is a literal type. | |||
8871 | /// | |||
8872 | /// This routine checks whether the type @p T is a literal type. If @p T is an | |||
8873 | /// incomplete type, an attempt is made to complete it. If @p T is a literal | |||
8874 | /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, | |||
8875 | /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving | |||
8876 | /// it the type @p T), along with notes explaining why the type is not a | |||
8877 | /// literal type, and returns true. | |||
8878 | /// | |||
8879 | /// @param Loc The location in the source that the non-literal type | |||
8880 | /// diagnostic should refer to. | |||
8881 | /// | |||
8882 | /// @param T The type that this routine is examining for literalness. | |||
8883 | /// | |||
8884 | /// @param Diagnoser Emits a diagnostic if T is not a literal type. | |||
8885 | /// | |||
8886 | /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, | |||
8887 | /// @c false otherwise. | |||
8888 | bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, | |||
8889 | TypeDiagnoser &Diagnoser) { | |||
8890 | assert(!T->isDependentType() && "type should not be dependent")(static_cast <bool> (!T->isDependentType() && "type should not be dependent") ? void (0) : __assert_fail ( "!T->isDependentType() && \"type should not be dependent\"" , "clang/lib/Sema/SemaType.cpp", 8890, __extension__ __PRETTY_FUNCTION__ )); | |||
8891 | ||||
8892 | QualType ElemType = Context.getBaseElementType(T); | |||
8893 | if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) && | |||
8894 | T->isLiteralType(Context)) | |||
8895 | return false; | |||
8896 | ||||
8897 | Diagnoser.diagnose(*this, Loc, T); | |||
8898 | ||||
8899 | if (T->isVariableArrayType()) | |||
8900 | return true; | |||
8901 | ||||
8902 | const RecordType *RT = ElemType->getAs<RecordType>(); | |||
8903 | if (!RT) | |||
8904 | return true; | |||
8905 | ||||
8906 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); | |||
8907 | ||||
8908 | // A partially-defined class type can't be a literal type, because a literal | |||
8909 | // class type must have a trivial destructor (which can't be checked until | |||
8910 | // the class definition is complete). | |||
8911 | if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) | |||
8912 | return true; | |||
8913 | ||||
8914 | // [expr.prim.lambda]p3: | |||
8915 | // This class type is [not] a literal type. | |||
8916 | if (RD->isLambda() && !getLangOpts().CPlusPlus17) { | |||
8917 | Diag(RD->getLocation(), diag::note_non_literal_lambda); | |||
8918 | return true; | |||
8919 | } | |||
8920 | ||||
8921 | // If the class has virtual base classes, then it's not an aggregate, and | |||
8922 | // cannot have any constexpr constructors or a trivial default constructor, | |||
8923 | // so is non-literal. This is better to diagnose than the resulting absence | |||
8924 | // of constexpr constructors. | |||
8925 | if (RD->getNumVBases()) { | |||
8926 | Diag(RD->getLocation(), diag::note_non_literal_virtual_base) | |||
8927 | << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); | |||
8928 | for (const auto &I : RD->vbases()) | |||
8929 | Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) | |||
8930 | << I.getSourceRange(); | |||
8931 | } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && | |||
8932 | !RD->hasTrivialDefaultConstructor()) { | |||
8933 | Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; | |||
8934 | } else if (RD->hasNonLiteralTypeFieldsOrBases()) { | |||
8935 | for (const auto &I : RD->bases()) { | |||
8936 | if (!I.getType()->isLiteralType(Context)) { | |||
8937 | Diag(I.getBeginLoc(), diag::note_non_literal_base_class) | |||
8938 | << RD << I.getType() << I.getSourceRange(); | |||
8939 | return true; | |||
8940 | } | |||
8941 | } | |||
8942 | for (const auto *I : RD->fields()) { | |||
8943 | if (!I->getType()->isLiteralType(Context) || | |||
8944 | I->getType().isVolatileQualified()) { | |||
8945 | Diag(I->getLocation(), diag::note_non_literal_field) | |||
8946 | << RD << I << I->getType() | |||
8947 | << I->getType().isVolatileQualified(); | |||
8948 | return true; | |||
8949 | } | |||
8950 | } | |||
8951 | } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor() | |||
8952 | : !RD->hasTrivialDestructor()) { | |||
8953 | // All fields and bases are of literal types, so have trivial or constexpr | |||
8954 | // destructors. If this class's destructor is non-trivial / non-constexpr, | |||
8955 | // it must be user-declared. | |||
8956 | CXXDestructorDecl *Dtor = RD->getDestructor(); | |||
8957 | assert(Dtor && "class has literal fields and bases but no dtor?")(static_cast <bool> (Dtor && "class has literal fields and bases but no dtor?" ) ? void (0) : __assert_fail ("Dtor && \"class has literal fields and bases but no dtor?\"" , "clang/lib/Sema/SemaType.cpp", 8957, __extension__ __PRETTY_FUNCTION__ )); | |||
8958 | if (!Dtor) | |||
8959 | return true; | |||
8960 | ||||
8961 | if (getLangOpts().CPlusPlus20) { | |||
8962 | Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor) | |||
8963 | << RD; | |||
8964 | } else { | |||
8965 | Diag(Dtor->getLocation(), Dtor->isUserProvided() | |||
8966 | ? diag::note_non_literal_user_provided_dtor | |||
8967 | : diag::note_non_literal_nontrivial_dtor) | |||
8968 | << RD; | |||
8969 | if (!Dtor->isUserProvided()) | |||
8970 | SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI, | |||
8971 | /*Diagnose*/ true); | |||
8972 | } | |||
8973 | } | |||
8974 | ||||
8975 | return true; | |||
8976 | } | |||
8977 | ||||
8978 | bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { | |||
8979 | BoundTypeDiagnoser<> Diagnoser(DiagID); | |||
8980 | return RequireLiteralType(Loc, T, Diagnoser); | |||
8981 | } | |||
8982 | ||||
8983 | /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified | |||
8984 | /// by the nested-name-specifier contained in SS, and that is (re)declared by | |||
8985 | /// OwnedTagDecl, which is nullptr if this is not a (re)declaration. | |||
8986 | QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, | |||
8987 | const CXXScopeSpec &SS, QualType T, | |||
8988 | TagDecl *OwnedTagDecl) { | |||
8989 | if (T.isNull()) | |||
8990 | return T; | |||
8991 | NestedNameSpecifier *NNS; | |||
8992 | if (SS.isValid()) | |||
8993 | NNS = SS.getScopeRep(); | |||
8994 | else { | |||
8995 | if (Keyword == ETK_None) | |||
8996 | return T; | |||
8997 | NNS = nullptr; | |||
8998 | } | |||
8999 | return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl); | |||
9000 | } | |||
9001 | ||||
9002 | QualType Sema::BuildTypeofExprType(Expr *E) { | |||
9003 | assert(!E->hasPlaceholderType() && "unexpected placeholder")(static_cast <bool> (!E->hasPlaceholderType() && "unexpected placeholder") ? void (0) : __assert_fail ("!E->hasPlaceholderType() && \"unexpected placeholder\"" , "clang/lib/Sema/SemaType.cpp", 9003, __extension__ __PRETTY_FUNCTION__ )); | |||
9004 | ||||
9005 | if (!getLangOpts().CPlusPlus && E->refersToBitField()) | |||
9006 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2; | |||
9007 | ||||
9008 | if (!E->isTypeDependent()) { | |||
9009 | QualType T = E->getType(); | |||
9010 | if (const TagType *TT = T->getAs<TagType>()) | |||
9011 | DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); | |||
9012 | } | |||
9013 | return Context.getTypeOfExprType(E); | |||
9014 | } | |||
9015 | ||||
9016 | /// getDecltypeForExpr - Given an expr, will return the decltype for | |||
9017 | /// that expression, according to the rules in C++11 | |||
9018 | /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. | |||
9019 | QualType Sema::getDecltypeForExpr(Expr *E) { | |||
9020 | if (E->isTypeDependent()) | |||
9021 | return Context.DependentTy; | |||
9022 | ||||
9023 | Expr *IDExpr = E; | |||
9024 | if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E)) | |||
9025 | IDExpr = ImplCastExpr->getSubExpr(); | |||
9026 | ||||
9027 | // C++11 [dcl.type.simple]p4: | |||
9028 | // The type denoted by decltype(e) is defined as follows: | |||
9029 | ||||
9030 | // C++20: | |||
9031 | // - if E is an unparenthesized id-expression naming a non-type | |||
9032 | // template-parameter (13.2), decltype(E) is the type of the | |||
9033 | // template-parameter after performing any necessary type deduction | |||
9034 | // Note that this does not pick up the implicit 'const' for a template | |||
9035 | // parameter object. This rule makes no difference before C++20 so we apply | |||
9036 | // it unconditionally. | |||
9037 | if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr)) | |||
9038 | return SNTTPE->getParameterType(Context); | |||
9039 | ||||
9040 | // - if e is an unparenthesized id-expression or an unparenthesized class | |||
9041 | // member access (5.2.5), decltype(e) is the type of the entity named | |||
9042 | // by e. If there is no such entity, or if e names a set of overloaded | |||
9043 | // functions, the program is ill-formed; | |||
9044 | // | |||
9045 | // We apply the same rules for Objective-C ivar and property references. | |||
9046 | if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) { | |||
9047 | const ValueDecl *VD = DRE->getDecl(); | |||
9048 | QualType T = VD->getType(); | |||
9049 | return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T; | |||
9050 | } | |||
9051 | if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) { | |||
9052 | if (const auto *VD = ME->getMemberDecl()) | |||
9053 | if (isa<FieldDecl>(VD) || isa<VarDecl>(VD)) | |||
9054 | return VD->getType(); | |||
9055 | } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) { | |||
9056 | return IR->getDecl()->getType(); | |||
9057 | } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) { | |||
9058 | if (PR->isExplicitProperty()) | |||
9059 | return PR->getExplicitProperty()->getType(); | |||
9060 | } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) { | |||
9061 | return PE->getType(); | |||
9062 | } | |||
9063 | ||||
9064 | // C++11 [expr.lambda.prim]p18: | |||
9065 | // Every occurrence of decltype((x)) where x is a possibly | |||
9066 | // parenthesized id-expression that names an entity of automatic | |||
9067 | // storage duration is treated as if x were transformed into an | |||
9068 | // access to a corresponding data member of the closure type that | |||
9069 | // would have been declared if x were an odr-use of the denoted | |||
9070 | // entity. | |||
9071 | if (getCurLambda() && isa<ParenExpr>(IDExpr)) { | |||
9072 | if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) { | |||
9073 | if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) { | |||
9074 | QualType T = getCapturedDeclRefType(Var, DRE->getLocation()); | |||
9075 | if (!T.isNull()) | |||
9076 | return Context.getLValueReferenceType(T); | |||
9077 | } | |||
9078 | } | |||
9079 | } | |||
9080 | ||||
9081 | return Context.getReferenceQualifiedType(E); | |||
9082 | } | |||
9083 | ||||
9084 | QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) { | |||
9085 | assert(!E->hasPlaceholderType() && "unexpected placeholder")(static_cast <bool> (!E->hasPlaceholderType() && "unexpected placeholder") ? void (0) : __assert_fail ("!E->hasPlaceholderType() && \"unexpected placeholder\"" , "clang/lib/Sema/SemaType.cpp", 9085, __extension__ __PRETTY_FUNCTION__ )); | |||
9086 | ||||
9087 | if (AsUnevaluated && CodeSynthesisContexts.empty() && | |||
9088 | !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) { | |||
9089 | // The expression operand for decltype is in an unevaluated expression | |||
9090 | // context, so side effects could result in unintended consequences. | |||
9091 | // Exclude instantiation-dependent expressions, because 'decltype' is often | |||
9092 | // used to build SFINAE gadgets. | |||
9093 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); | |||
9094 | } | |||
9095 | return Context.getDecltypeType(E, getDecltypeForExpr(E)); | |||
9096 | } | |||
9097 | ||||
9098 | QualType Sema::BuildUnaryTransformType(QualType BaseType, | |||
9099 | UnaryTransformType::UTTKind UKind, | |||
9100 | SourceLocation Loc) { | |||
9101 | switch (UKind) { | |||
9102 | case UnaryTransformType::EnumUnderlyingType: | |||
9103 | if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) { | |||
9104 | Diag(Loc, diag::err_only_enums_have_underlying_types); | |||
9105 | return QualType(); | |||
9106 | } else { | |||
9107 | QualType Underlying = BaseType; | |||
9108 | if (!BaseType->isDependentType()) { | |||
9109 | // The enum could be incomplete if we're parsing its definition or | |||
9110 | // recovering from an error. | |||
9111 | NamedDecl *FwdDecl = nullptr; | |||
9112 | if (BaseType->isIncompleteType(&FwdDecl)) { | |||
9113 | Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; | |||
9114 | Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; | |||
9115 | return QualType(); | |||
9116 | } | |||
9117 | ||||
9118 | EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl(); | |||
9119 | assert(ED && "EnumType has no EnumDecl")(static_cast <bool> (ED && "EnumType has no EnumDecl" ) ? void (0) : __assert_fail ("ED && \"EnumType has no EnumDecl\"" , "clang/lib/Sema/SemaType.cpp", 9119, __extension__ __PRETTY_FUNCTION__ )); | |||
9120 | ||||
9121 | DiagnoseUseOfDecl(ED, Loc); | |||
9122 | ||||
9123 | Underlying = ED->getIntegerType(); | |||
9124 | assert(!Underlying.isNull())(static_cast <bool> (!Underlying.isNull()) ? void (0) : __assert_fail ("!Underlying.isNull()", "clang/lib/Sema/SemaType.cpp" , 9124, __extension__ __PRETTY_FUNCTION__)); | |||
9125 | } | |||
9126 | return Context.getUnaryTransformType(BaseType, Underlying, | |||
9127 | UnaryTransformType::EnumUnderlyingType); | |||
9128 | } | |||
9129 | } | |||
9130 | llvm_unreachable("unknown unary transform type")::llvm::llvm_unreachable_internal("unknown unary transform type" , "clang/lib/Sema/SemaType.cpp", 9130); | |||
9131 | } | |||
9132 | ||||
9133 | QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { | |||
9134 | if (!isDependentOrGNUAutoType(T)) { | |||
9135 | // FIXME: It isn't entirely clear whether incomplete atomic types | |||
9136 | // are allowed or not; for simplicity, ban them for the moment. | |||
9137 | if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) | |||
9138 | return QualType(); | |||
9139 | ||||
9140 | int DisallowedKind = -1; | |||
9141 | if (T->isArrayType()) | |||
9142 | DisallowedKind = 1; | |||
9143 | else if (T->isFunctionType()) | |||
9144 | DisallowedKind = 2; | |||
9145 | else if (T->isReferenceType()) | |||
9146 | DisallowedKind = 3; | |||
9147 | else if (T->isAtomicType()) | |||
9148 | DisallowedKind = 4; | |||
9149 | else if (T.hasQualifiers()) | |||
9150 | DisallowedKind = 5; | |||
9151 | else if (T->isSizelessType()) | |||
9152 | DisallowedKind = 6; | |||
9153 | else if (!T.isTriviallyCopyableType(Context)) | |||
9154 | // Some other non-trivially-copyable type (probably a C++ class) | |||
9155 | DisallowedKind = 7; | |||
9156 | else if (T->isBitIntType()) | |||
9157 | DisallowedKind = 8; | |||
9158 | ||||
9159 | if (DisallowedKind != -1) { | |||
9160 | Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; | |||
9161 | return QualType(); | |||
9162 | } | |||
9163 | ||||
9164 | // FIXME: Do we need any handling for ARC here? | |||
9165 | } | |||
9166 | ||||
9167 | // Build the pointer type. | |||
9168 | return Context.getAtomicType(T); | |||
9169 | } |